teapot-coding-agent 0.37.148 → 0.37.149

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
3
3
  `)).split(`
4
4
  `))}function ze(e){let t=[],n=0;for(;n<e.length;){let o=e[n],s=o.match(/^(`{3,})([^\n]*)$/);if(s&&!/^```.+\`\`\`/.test(o)){let r=s[1].length,i=s[2].trim().split(/\s+/)[0]??``,a=[];n++;let o=RegExp("^`{"+r+`,}\\s*$`);for(;n<e.length&&!o.test(e[n]);)a.push(e[n++]);n++;let c=i?i.split(/\s+/)[0]:``,l=c?c.split(`/`).pop().split(`.`).pop().replace(/[^\w+#-]/g,``):``,u=l?` class="language-${l}"`:``;t.push(`<pre><code${u}>${a.join(`
5
5
  `)}</code></pre>`);continue}if(/^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(o)){t.push(`<hr>`),n++;continue}let c=o.match(/^(#{1,6})\s+(.*)$/);if(c){t.push(`<h${c[1].length}>${a(c[2])}</h${c[1].length}>`),n++;continue}if(/^\s*&gt;/.test(o)){let r=[];for(;n<e.length&&/^\s*&gt;/.test(e[n]);)r.push(e[n++].replace(/^\s*&gt;\s?/,``));t.push(`<blockquote>${ze(r)}</blockquote>`);continue}if(o.includes(`|`)&&n+1<e.length&&Ve(e[n+1])){let r=Be(e[n+1]).map(e=>e.startsWith(`:`)&&e.endsWith(`:`)?`center`:e.endsWith(`:`)?`right`:`left`),i=Be(o);n+=2;let s=[];for(;n<e.length&&/\S/.test(e[n])&&e[n].includes(`|`);)s.push(Be(e[n])),n++;let c=(e,t,n)=>{let i=r[t];return`<${n}${i&&i!==`left`?` style="text-align:${i}"`:``}>${a(e)}</${n}>`},l=i.some(e=>e!==``);t.push(`<div class="tbl"><table>`+(l?`<thead><tr>${i.map((e,t)=>c(e,t,`th`)).join(``)}</tr></thead>`:``)+`<tbody>${s.map(e=>`<tr>${e.map((e,t)=>c(e,t,`td`)).join(``)}</tr>`).join(``)}</tbody></table></div>`);continue}if(Le.test(o)){t.push(i(r(o.match(Le)[1])));continue}if(/^\s*$/.test(o)){n++;continue}let l=n,u=[];for(;n<e.length&&!/^\s*$/.test(e[n])&&!/^#{1,6}\s/.test(e[n])&&!e[n].startsWith("```")&&!/^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(e[n])&&!/^\s*&gt;/.test(e[n])&&!Le.test(e[n])&&!(e[n].includes(`|`)&&n+1<e.length&&Ve(e[n+1]));)u.push(e[n++]);n===l&&u.push(e[n++]),t.push(`<p>${u.map(a).join(`<br>`)}</p>`)}return t.join(`
6
- `);function r(e){return e.replace(/\t/g,` `).length}function i(t){let o=null,s=1,c=[];for(;n<e.length;){let l=e[n].match(Le);if(!l)break;let u=r(l[1]);if(u<t)break;let d=/^\d/.test(l[2]);if(o===null)o=d;else if(d!==o)break;if(o&&c.length===0){let e=Number.parseInt(l[2],10);Number.isFinite(e)&&(s=e)}n++;let f=l[3];for(;n<e.length&&/\S/.test(e[n])&&!Le.test(e[n])&&!/^#{1,6}\s/.test(e[n])&&!e[n].startsWith("```")&&!/^\s*&gt;/.test(e[n])&&!/^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(e[n])&&!/^ {0,3}={3,}\s*$/.test(e[n])&&!(e[n].includes(`|`)&&n+1<e.length&&Ve(e[n+1]));)f+=` `+e[n].trim(),n++;let p=``,m=e[n]?.match(Le);m&&r(m[1])>u&&(p=i(r(m[1])));let h=f.match(/^\[( |x|X)\]\s+(.*)$/),g=h?`<input type="checkbox" disabled${h[1].toLowerCase()===`x`?` checked`:``}> `:``;c.push(`<li>${g}${a(h?h[2]:f)}${p}</li>`);let _=n;for(;_<e.length&&!/\S/.test(e[_]);)_++;let v=e[_]?.match(Le);_>n&&v&&r(v[1])===u&&/^\d/.test(v[2])===o&&(n=_)}return o?s===1?`<ol>${c.join(``)}</ol>`:`<ol start="${s}">${c.join(``)}</ol>`:`<ul>${c.join(``)}</ul>`}function a(e){let t=[];return e=e.replace(/\u0000/g,``),e=e.replace(/`([^`]+)`/g,(e,n)=>(t.push(`<code>${n}</code>`),`\ue000${t.length-1}\uE001`)),e=e.replace(/!\[([^\]]*)\]\((https?:\/\/[^)\s]+)(?:\s+&quot;[^)]*&quot;)?\)/g,(e,n,r)=>(t.push(`<img src="${r}" alt="${n}" loading="lazy">`),`\ue000${t.length-1}\uE001`)),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)(?:\s+&quot;[^)]*&quot;)?\)/g,(e,n,r)=>(t.push(`<a href="${r}" rel="noopener noreferrer" target="_blank">${n}</a>`),`\ue000${t.length-1}\uE001`)),e=e.replace(/(?<!["'=\w])(https?:\/\/[^\s<>"')\]]*[^\s<>"')\].,;:!?"')\]])/g,`<a href="$1">$1</a>`),e=e.replace(/\*\*\*([\s\S]+?)\*\*\*/g,`<strong><em>$1</em></strong>`),e=e.replace(/\*\*([\s\S]+?)\*\*/g,`<strong>$1</strong>`),e=e.replace(/(^|[^\w])__(?=\S)([\s\S]*?\S)__(?!\w)/g,`$1<strong>$2</strong>`),e=e.replace(/(^|[^\w*])\*(?!\s)([^*\n]+?)\*(?![\w*])/g,`$1<em>$2</em>`),e=e.replace(/(^|[^\w])_(?!\s)([^_\n]+?)_(?!\w)/g,`$1<em>$2</em>`),e=e.replace(/~~([\s\S]+?)~~/g,`<del>$1</del>`),e.replace(/\ue000(\d+)\ue001/g,(e,n)=>t[+n]??``)}}function Be(e){let t=e.trim();t.startsWith(`|`)&&(t=t.slice(1));let n=[],r=``;for(let e=0;e<t.length;e++){let i=t[e];if(i===`\\`&&t[e+1]===`|`)r+=`|`,e++;else if(i==="`"){let n=t.indexOf("`",e+1);if(n!==-1){r+=t.slice(e,n+1).replace(/\\\|/g,`|`),e=n;continue}r+=i}else{if(i===`|`&&e===t.length-1)break;i===`|`?(n.push(r.trim()),r=``):r+=i}}return n.push(r.trim()),n.filter((e,r)=>!(e===``&&r===n.length-1&&t.endsWith(`|`)))}function Ve(e){let t=e.trim();if(!t.includes(`|`)||!t.includes(`-`))return!1;let n=Be(t);return n.every(e=>/^:?-+:?$/.test(e))&&n.some(e=>e!==``)}function He(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`)}function Ue(e){return Math.max(0,e.height-e.viewport)}function We(e){return e?Math.max(0,e.height-e.top-e.viewport):1/0}function Ge(e,t=24){return e?We(e)<=t:!1}function Ke(e,t,n,r){if(r!==void 0&&Math.abs(e.viewport-r)>.5||n!==void 0&&Math.abs(e.height-n)>.5)return`layout`;if(t){let n=Math.min(t.top,Ue(e));if(Math.abs(e.top-n)<=.5)return`programmatic`}return`reader`}function qe(e,t){return e?We(t)<=64:!1}function Je(e,t,n,r){return t===`reader`?r!==void 0&&n.top<r-.5?!1:Ge(n):e||Ge(n)}function Ye(e,t,n=.5){return e?We(t)>n:!1}var Xe=We;function Ze(e,t,n=200){return!t||e-t>=n}function Qe(e,t){let n=String(e??``).trim();return!n||!t||n===t}var[$e,et]=y(null),tt=$e;function nt(e){e&&et(e)}function rt(){et(null)}function it(e,t){let n=0,r=()=>{let t=0;for(let n of e.values())t+=n.bytes;return t};for(;e.size>t.maxEntries||r()>t.maxBytes;){let t,r=1/0;for(let[n,i]of e)i.at<r&&(r=i.at,t=n);if(t===void 0||(e.delete(t),n++,e.size===0))break}return n}function at(e,t=0){if(t>8)return 8;if(e==null)return 4;switch(typeof e){case`string`:return 16+e.length*2;case`number`:case`boolean`:return 8;case`object`:{if(Array.isArray(e)){let n=16;for(let r of e)n+=at(r,t+1);return n}let n=16;for(let[r,i]of Object.entries(e))n+=8+r.length*2+at(i,t+1);return n}default:return 8}}var ot=new Map,st=0,ct=500,lt=4194304;function ut(e){let t=ot.get(e);if(t!==void 0)return t;let n=Re(e);for(ot.set(e,n),st+=(e.length+n.length)*2;(ot.size>ct||st>lt)&&ot.size;){let e=ot.keys().next().value;if(e===void 0)break;let t=ot.get(e)??``;st-=(e.length+t.length)*2,ot.delete(e)}return n}function dt(e){if(e==null||!Number.isFinite(e))return`?`;let t=Math.max(0,e);if(t<1e3)return`${Math.round(t)}ms`;if(t<6e4)return`${(Math.floor(t/100)/10).toFixed(1)}s`;let n=Math.round(t/1e3);if(n<3600){let e=Math.floor(n/60),t=n%60;return t?`${e}m ${t}s`:`${e}m`}let r=Math.round(n/60),i=Math.floor(r/60),a=r%60;return a?`${i}h ${a}m`:`${i}h`}function ft(e,t){return e.length>t?e.slice(0,t)+` …`:e}function pt(e){let t=new Date(e).getTime()-Date.now(),n=Math.abs(t),r=n<9e4?`${Math.round(n/1e3)}s`:n<54e5?`${Math.round(n/6e4)}m`:`${(n/36e5).toFixed(1)}h`;return t>=0?`in ${r}`:`${r} ago`}function mt(e,t,n,r=Date.now()){let i=new Map(e);return i.set(t,{text:n.text??``,reasoning:n.reasoning??``,at:r}),i}function ht(e,t){if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}function gt(e){let t=e;return t?.type===`state`&&t.data?.detail===`llm turn start`||t?.type===`question`}function _t(e){return e===`running`||e===`waiting`||e===`needs_operator`}function vt(e,t,n){let r=e.text.trim(),i=St(t),a=_t(n);return{textCovered:!r||i.has(r),reasoningStale:!e.reasoning.trim()||xt(t).has(e.reasoning.trim())||a&&bt(t,e.at)}}function yt(e,t,n){let r=vt(e,t,n),i=r.textCovered?``:e.text,a=r.reasoningStale?``:e.reasoning,o=_t(n),s=!i.trim()&&!a.trim(),c=!!e.text.trim()||!!e.reasoning.trim();return{text:i,reasoning:a,live:o,empty:s&&(!o||c)}}function bt(e,t){return t?e.some(e=>{if(e.type!==`tool_call`)return!1;let n=Date.parse(String(e.ts??``));return Number.isFinite(n)&&n>t}):!1}function xt(e){let t=new Set;for(let n of e){let e=String(n.data?.reasoning??``).trim();e&&t.add(e)}return t}function St(e){let t=new Set;for(let n of e)n.type===`message`&&n.data?.role===`assistant`&&t.add(String(n.data.content??``).trim());return t}function Ct(e){if(!e)return!1;let t=e.data?.actor;return!(typeof t==`string`&&t.length>0)}var wt=new Set([`stopped`,`error`]),Tt=2e3;function Et(e,t,n=Date.now()){let r=[];for(let[i,a]of e){let e=t(i);e!==void 0&&(!wt.has(e)&&(_t(e)||n-Number(a?.at??0)<=Tt)||r.push(i))}if(r.length===0)return e;let i=new Map(e);for(let e of r)i.delete(e);return i}function Dt(e,t,n){if(!e)return null;let r=yt(e,t,n);return r.empty?null:r.text===e.text&&r.reasoning===e.reasoning?e:{text:r.text,reasoning:r.reasoning,at:e.at}}function Ot(e,t,n,r){if(!e)return 0;if(r)return e;if(!n)return 0;let i=t.find(e=>e.id===n);return i?.status===`running`||i?.status===`waiting`||i?.status===`needs_operator`?e:0}function kt(e,t){if(!t.length)return[...e].sort((e,t)=>e.seq-t.seq);let n=e.reduce((e,t)=>Math.max(e,t.seq),0),r=t.map((e,t)=>e.seq>n?e:{...e,seq:n+1+t});return[...e,...r].sort((e,t)=>e.seq-t.seq)}function At(e,t){if(t===void 0||t<=e.seq)return e;let n=jt.get(e);n||(n=new Map,jt.set(e,n));let r=n.get(t);if(r)return r;let i={...e,seq:t};return n.set(t,i),i}var jt=new WeakMap;function Mt(e,t){return t===void 0?e.reduce((e,t)=>Math.max(e,t.seq),0)+1:t}var Nt=new Set([`report_progress`,`ask_user`,`record_decision`]);function Pt(e){let{events:t,consumed:n,feedTypes:r}=e;return t.filter(e=>{if(e.type===`sub`)return!0;if(!r.has(e.type))return!1;let t=e.type===`tool_call`||e.type===`tool_result`?String(e.data?.name??``):``;if(Nt.has(t))return!1;if(e.type===`tool_result`)return!n.has(e.id);if(e.type===`message`){let t=String(e.data?.content??``),n=String(e.data?.reasoning??``);return t.trim()===``&&n.trim()!==``&&e.data?._prevKind===`tool`||e.data?.progressEcho||!e.data?.final&&t.trim()===`(tool call)`?!1:t.trim()!==``||n.trim()!==``||!!e.data?.final}return!0})}function Ft(e){let t=[];for(let n of e){if(n.type!==`sub`){t.push(n);continue}let e=n.data,r=String(e?.type??`message`);r!==`state`&&t.push({...n,type:r,data:{...e?.data??{},actor:e?.sub}})}return t}var It=e=>String(e??``).replace(/\s+/g,` `).trim().toLowerCase();function Lt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.type===`message`&&r.data?.role===`assistant`){let e=t[t.length-1],n=e?.type;if(n===`progress`||n===`decision`||e?.data?.progressEcho){let t=It(r.data?.content),n=It(e?.data?.content);if(t&&t===n)continue}}t.push(r)}return t}function Rt(e){let t=new Set,n=new Set,r=new Map,i=new Map;for(let a of e){let e=a.data?.promptId;e&&(a.type===`prompt`&&a.data?.source===`user`&&n.add(String(e)),a.type===`system_note`&&a.data?.event===`prompt-delivered`&&(t.add(String(e)),r.set(String(e),a.seq)),a.type===`system_note`&&a.data?.event===`prompt-cancelled`&&i.set(String(e),a.seq))}return{deliveredIds:t,loggedUserPrompts:n,deliveredNotes:r,cancelledNotes:i}}function zt(e,t,n){return e.filter(e=>{if(!t.renderedTypes.has(e.type))return e.type===`system_note`&&t.renderedNoteEvents.has(String(e.data?.event??``));if(e.type!==`prompt`||e.data?.source!==`user`)return!0;let r=String(e.data?.promptId??``);return r===``||!n.has(r)})}var Bt=new WeakMap;function Vt(e,t){let n=Bt.get(e);n||(n=new Map,Bt.set(e,n));let r=n.get(t);if(r)return r;let i={...e,data:{...e.data??{},cancelled:!0}};return n.set(t,i),i}function Ht(e,t){let n=t=>Mt(e,t),r=[];for(let i of e){if(i.type!==`prompt`||i.data?.source!==`user`){r.push(i);continue}let e=String(i.data?.promptId??``),a=t.cancelledNotes.get(e),o=t.deliveredNotes.get(e)??0,s=Math.max(o,a??0)||void 0,c=a===void 0?i:Vt(i,a);if(s!==void 0){r.push(At(c,s));continue}let l=n(c.seq);r.push(c.seq===l?c:{...c,seq:l})}return r}function Ut(e,t){return e.filter(e=>!e.promptId||!(t.deliveredIds.has(e.promptId)&&t.loggedUserPrompts.has(e.promptId)))}function Wt(e){let t=Lt(Ft(Pt(e))),n=Rt(t),r=new Set;for(let t of e.pending)t.promptId&&!n.deliveredIds.has(t.promptId)&&r.add(t.promptId);let i=Ht(zt(t,e,r),n),a=Ut(e.pending,n).map(e.echo);return{rows:kt(i,a),pendingCount:a.length}}function Gt(e){let t=e.event;return t===`status`||t===`audit-started`||t===`audit`||t===`audit-failed`?t:`other`}function Kt(e){let t=e.trim().toLowerCase();return t===``||t===`(no detail)`||t===`no detail`||t===`(none)`||t===`(empty)`}function qt(e,t){let n=String(e??``).trim();return Kt(n)?Kt(t)?``:t:n}function Jt(e){switch(Gt(e)){case`audit-started`:return{label:`🔍️ completion audit started`,detail:String(e.verify??``).trim()||`checking the verification contract…`,tone:``,markdown:!1,hasCard:!0};case`audit`:{let t=!Kt(String(e.feedback??``));return e.verdict===`approved`?{label:`✅ audit: approved`,detail:qt(e.feedback??``,``),tone:`ok`,markdown:!0,hasCard:t}:{label:`⚠ audit: changes required`,detail:qt(e.feedback??``,``),tone:`warn`,markdown:!0,hasCard:t}}case`audit-failed`:return{label:`🔍️ audit unavailable — finish accepted`,detail:String(e.detail??``).trim()||`the auditor could not be reached`,tone:`err`,markdown:!1,hasCard:!0};case`status`:{let t=String(e.status??``).trim();return t?t===`done`?String(e.by??``).trim()===`operator`?{label:`🏁 goal marked done`,detail:`you marked this goal done — no audit runs for a manual completion`,tone:``,markdown:!1,hasCard:!0}:{label:`🏁 finish claimed — pending audit`,detail:`the agent called finish(goalComplete=true); the verification contract is now being audited`,tone:``,markdown:!1,hasCard:!0}:t===`active`?String(e.by??``).trim()===`auditor`?{label:`▶ goal reopened`,detail:`the audit rejected the finish — work continues on the same goal`,tone:`warn`,markdown:!1,hasCard:!0}:{label:`▶ goal resumed`,detail:`marked active again — auto-continue picks the goal up from the next turn`,tone:``,markdown:!1,hasCard:!0}:{label:`🎯 goal ${t||`updated`}`,detail:String(e.text??``).trim()||`the goal is now ${t}`,tone:``,markdown:!0,hasCard:!0}:{label:`🎯 goal status updated`,detail:String(e.text??``).trim()||`no status recorded`,tone:``,markdown:!0,hasCard:!0}}default:{let t=String(e.text??``).trim(),n=String(e.event??``).trim();return{label:n?`🎯 goal ${n}`:`🎯 goal updated`,detail:t||`the "${n||`goal`}" event carried no further detail`,tone:``,markdown:!0,hasCard:!0}}}}var Yt=F(`<span class="meta muted">`),Xt=F(`<div class=ctitle>`),Zt=F(`<div>`),Qt=F(`<div class=cardbody>`);function $t(e){let t=()=>{let t=e.tone;return[`card`,t?`card-${t}`:``,e.class??``].filter(Boolean).join(` `)},n=()=>e.markdown===!1?Re(`\`\`\`\n${e.body}\n\`\`\``):Re(e.body);return(()=>{var r=Zt();return R(r,j(N,{get when(){return e.title},get children(){var t=Xt();return R(t,()=>e.title,null),R(t,j(N,{get when(){return e.meta},get children(){var t=Yt();return R(t,()=>e.meta),t}}),null),t}}),null),R(r,()=>e.children??(()=>{var e=Qt();return b(()=>e.innerHTML=n()),e})(),null),b(()=>L(r,t())),r})()}function en(e){let t=e.hideGhosts?e.agents.filter(e=>!e.workspaceMissing):e.agents,n=t.length?t:e.agents,r=e.urlId,i=r?e.ownerOf(r):void 0;return(i?n.find(e=>e.id===i):void 0)??n.find(t=>t.id===e.lastId)??n[0]}function tn(e,t){let n=new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()]}var nn=[320,640,1280,1920,2560,3840],rn=nn[0],an=/^\/api\/assets\/[a-f0-9]{32}\.(png|jpg|jpeg|gif|webp|avif)$/i;function on(e,t){if(e)return an.test(e)?`${e}?w=${t}`:e}function sn(e){if(e)return nn.map(t=>`${on(e,t)} ${t}w`).join(`, `)}function cn(e,t=rn){return on(e,t)}function ln(e,t=new Set,n=!1,r=new Set){let i=n?e.filter(t=>{if(!t.workspaceMissing)return!0;let n=[t.id],r=new Set;for(;n.length;){let t=n.pop();if(!r.has(t)){r.add(t);for(let i of e)i.parent===t&&!r.has(i.id)&&n.push(i.id)}}for(let t of r){let n=e.find(e=>e.id===t);if(n&&!n.workspaceMissing)return!0}return!1}):e,a=new Map,o=[];for(let e of i)e.parent&&i.some(t=>t.id===e.parent)?(a.has(e.parent)||a.set(e.parent,[]),a.get(e.parent).unshift(e)):o.push(e);let s=[],c=(e,n)=>{for(let o of e){let e=n===0&&r.has(mn(i,o));if(s.push({a:o,depth:n}),e)continue;let l=a.get(o.id);l?.length&&!t.has(o.id)&&c(l,n+1)}},l=[],u=new Map;for(let e of o){if(e.parent)continue;let t=un(i,e.id),n=u.get(t);n?n.push(e):(u.set(t,[e]),l.push(t))}for(let t of o){if(!t.parent)continue;let n=un(e,t.id)||``,r=u.get(n);r?r.push(t):(u.set(n,[t]),l.push(n))}for(let e of l)c(u.get(e),0);return s}function un(e,t,n=new Set){let r=e.find(e=>e.id===t);return r?!r.parent||n.has(t)?r.workspace||``:(n.add(t),un(e,r.parent,n)||r.workspace||``):``}function dn(e){return e.isSub?e.hasChildren:e.collapsed||e.hasChildren}function fn(e,t=[]){let n=e.indexOf(`-sub`);if(n===-1)return null;let r=e.slice(n+4).replace(/^-+/,``);if(!r)return null;let i=r.split(`-`);return(t.includes(i[0]??``)?i.slice(1).join(`-`):r).replace(/_/g,` `).trim()||null}function pn(e,t,n=new Set){let r=[],i=new Set(n);for(let n of e)n.parent===t&&(i.has(n.id)||(i.add(n.id),r.push(n,...pn(e,n.id,i))));return r}function mn(e,t){let n=t.id,r=new Set;for(;;){let t=e.find(e=>e.id===n);if(!t?.parent||r.has(n))break;r.add(n),n=t.parent}return`chat:${n||t.id}`}function hn(e){let t=new Map;for(let n of e){if(n.parent)continue;let r=un(e,n.id);r&&t.set(r,(t.get(r)??0)+1)}return t}function gn(e,t,n=new Set){let r=[],i=null;for(let a of t){let t=un(e,a.a.id);t?(t!==i&&(i=t,r.push({a:a.a,depth:0,headerOnly:!0,wsHeader:t,wsCollapsedGroup:n.has(`ws:${t}`)})),!n.has(`ws:${t}`)&&(n.has(mn(e,a.a))?r.push({a:a.a,depth:a.depth,chatCollapsedGroup:!0}):r.push({a:a.a,depth:a.depth}))):r.push({a:a.a,depth:a.depth})}return r}function _n(e,t=new Set){let n=new Set,r=-1,i=-1;for(let t of e)t.type===`question`?r=t.seq:t.type===`prompt`&&t.data?.source===`user`?i=t.seq:t.type===`system_note`&&t.data?.event===`prompt-delivered`&&(i=Math.max(i,t.seq));if(r>=0&&i>r)for(let t of e)t.type===`question`&&t.seq<=i&&n.add(String(t.data?.callId??``));for(let e of t)n.add(e);return n}var vn=(e,t,n)=>{if(t>=e.length)return e;if(n?.length){let r=new Set(n),i=e.filter(e=>e.promptId&&r.has(e.promptId));if(i.length){let n=e.filter(e=>!e.promptId);return n.length?[...i,...n].slice(0,t):i}}return e.slice(0,t)};function yn(e,t){let n=new Set(e.map(e=>e.promptId).filter(e=>!!e)),r=e.filter(e=>!e.promptId).map(e=>e.text),i=[];for(let e of t){let t=typeof e.id==`string`?e.id:``;if(!t||n.has(t))continue;let a=r.indexOf(String(e.text??``));a===-1?i.push({id:`p${t}`,text:String(e.text??``),at:Number(e.at)||Date.now(),promptId:t,images:e.images?.map(e=>e.url),...e.source?{source:e.source}:{}}):r.splice(a,1)}return i.length?[...e,...i]:e}function bn(e,t,n){let r=e??[];return n&&r.includes(n)?n:t&&r.includes(t)||t&&r.length===0?t:r[0]??null}function xn(e,t,n){return!t||n&&t===n?!0:typeof e==`string`&&e===t}function Sn(e,t,n){return!e||!t||e.agent!==t?!1:xn(e.session,n,t)}function Cn(e,t,n){return!e||!t||e.agentId!==t||!e.sessionId?!1:xn(e.sessionId,n,t)}function wn(e,t,n){return n?!e||!t||t===e.id||!e.session||e.session===t:!1}function Tn(e,t){if(t>=1)return e;let n=/^#([0-9a-f]{6})$/i.exec(e.trim());if(n){let e=Number.parseInt(n[1],16);return`rgba(${e>>16&255}, ${e>>8&255}, ${e&255}, ${Math.max(0,Math.min(1,t))})`}let r=/^rgba?\(([^)]+)\)$/i.exec(e.trim());if(r){let[e,n,i]=r[1].split(`,`).map(e=>e.trim());return`rgba(${e}, ${n}, ${i}, ${Math.max(0,Math.min(1,t))})`}return e}function En(e=1){let t=``,n=``,r=``,i=``;try{let e=getComputedStyle(document.documentElement);t=e.getPropertyValue(`--term-bg`).trim(),n=e.getPropertyValue(`--term-fg`).trim(),r=e.getPropertyValue(`--term-cursor`).trim(),i=e.getPropertyValue(`--term-cursor-accent`).trim()}catch{}let a=t||`#0d0e12`,o=Tn(a,e),s=n||`#dcdee4`;return{background:o,foreground:s,cursor:r||s,cursorAccent:i||a,selectionBackground:On(s),selectionForeground:s}}function Dn(e,t=1){let n=En(t),r=e.options.theme;r&&r.background===n.background&&r.foreground===n.foreground&&r.cursor===n.cursor&&r.cursorAccent===n.cursorAccent&&r.selectionBackground===n.selectionBackground||(e.options.theme=n)}function On(e){let t=e.trim(),n=/^#([0-9a-f]{6})$/i.exec(t);return n?`#${n[1]}47`:`rgba(128, 128, 128, 0.35)`}function kn(e,t,n){return e?.provider||n||Object.keys(t??{})[0]||``}function An(e,t){return t?String(e?.[t]?.model??``).trim():``}function jn(e,t,n){return An(e,t)||(n&&t===(n.provider??``)?n.model??``:``)}function Mn(e,t,n,r){return n?.model&&t===r?n.model:An(e,t)||n?.model||``}function Nn(e){return!e}function Pn(e){return!e}function Fn(e,t){return e!==t}function In(e,t){return Math.max(1,Math.min(e,t))}function Ln(e){return typeof e!=`number`||!Number.isFinite(e)?!1:e<0}function Rn(e){return e===`PageUp`||e===`ArrowUp`||e===`Home`}function zn(e,t,n){if(!n)return null;let r=e.find(e=>e.top+e.height>t+.5);if(!r)return null;let i=Math.min(Math.max(0,Math.round(t-r.top)),Math.max(0,Math.round(r.height)));return{session:n,eid:r.eid,offset:i}}function Bn(e,t,n){if(!e)return null;let r=t.find(t=>t.eid===e.eid);if(!r)return null;let i=Math.max(0,Math.min(n,Math.round(r.top+e.offset)));return Number.isFinite(n)&&i>=n-1?null:i}var Vn=`teapot.textareaH.`;function Hn(e){try{let t=Number(localStorage.getItem(Vn+e)??``);return Number.isFinite(t)&&t>0?t:0}catch{return 0}}function Un(e,t){try{localStorage.setItem(Vn+e,String(Math.round(t)))}catch{}}function Wn(e,t,n){return!n||!Number.isFinite(e)||e<=0?!1:!Number.isFinite(t)||t<=0||Math.abs(e-t)>=1}function Gn(e,t){let n=Hn(t);n>0&&(e.style.height=`${n}px`);let r=!1,i=()=>{r=!0};e.addEventListener(`pointerdown`,i);let a=new ResizeObserver(()=>{let n=e.offsetHeight;Wn(n,Hn(t),r)&&Un(t,n)});return a.observe(e),()=>{e.removeEventListener(`pointerdown`,i),a.disconnect()}}var Kn=e=>e?e.sessionTitle?.trim()||e.id:``,qn=(e,t)=>{if(!e)return``;let n=Kn(e),r=t?` — ${t}`:``;return n===e.id?`${n}${r}`:`${n} — ${e.id}${r}`},Jn=e=>e?Math.max(e.pendingPromptQueue?.length??0,e.pendingPromptIds?.length??0,e.pendingPrompts??0):0,Yn=e=>{let t=e.sameSession?Jn(e.agent):0;return Math.max(t,e.echoCount)},Xn=[{key:`bgDarkest`,cssVar:`--bg-darkest`,label:`surface (deepest)`},{key:`bgDark`,cssVar:`--bg-dark`,label:`surface`},{key:`bgMid`,cssVar:`--bg-mid`,label:`surface (raised)`},{key:`bgLight`,cssVar:`--bg-light`,label:`surface (control)`},{key:`fg`,cssVar:`--fg`,label:`text`},{key:`dim`,cssVar:`--dim`,label:`text (muted)`},{key:`line`,cssVar:`--line`,label:`divider`},{key:`acc`,cssVar:`--acc`,label:`accent`},{key:`ok`,cssVar:`--ok`,label:`success`},{key:`warn`,cssVar:`--warn`,label:`warning`},{key:`err`,cssVar:`--err`,label:`error`},{key:`tool`,cssVar:`--tool`,label:`tool accent`},{key:`termBg`,cssVar:`--term-bg`,label:`terminal background`},{key:`termFg`,cssVar:`--term-fg`,label:`terminal text`}],Zn=`teapot.customThemes`,Qn={bgDarkest:`#1a1c22`,bgDark:`#232630`,bgMid:`#2b2e39`,bgLight:`#343845`,fg:`#dcdee4`,dim:`#9298a5`,line:`#1d2027`,acc:`#5865f2`,ok:`#3ba55d`,warn:`#faa81a`,err:`#ed4245`,tool:`#3ba0c9`,termBg:`#0d0e12`,termFg:`#dcdee4`},$n={dark:{bgDarkest:`#1a1c22`,bgDark:`#232630`,bgMid:`#2b2e39`,bgLight:`#343845`,fg:`#dcdee4`,dim:`#9298a5`,line:`#1d2027`,acc:`#5865f2`,ok:`#3ba55d`,warn:`#faa81a`,err:`#ed4245`,tool:`#3ba0c9`,termBg:`#0d0e12`,termFg:`#dcdee4`},midnight:{bgDarkest:`#0d0f18`,bgDark:`#12141f`,bgMid:`#1b1f31`,bgLight:`#252a42`,fg:`#dfe2f2`,dim:`#8a90ad`,line:`#0a0c14`,acc:`#8b7cf7`,ok:`#54c08a`,warn:`#e5b567`,err:`#ef6a6a`,tool:`#6aa9e9`,termBg:`#0a0c13`,termFg:`#dfe2f2`},tea:{bgDarkest:`#241c16`,bgDark:`#2e241c`,bgMid:`#3b2f24`,bgLight:`#493b2d`,fg:`#f0e4d2`,dim:`#b39d82`,line:`#1b140f`,acc:`#d98e32`,ok:`#7fa653`,warn:`#e0b058`,err:`#cf5b47`,tool:`#c9975f`,termBg:`#1d1712`,termFg:`#ecdcc3`},coffee:{bgDarkest:`#191410`,bgDark:`#211a14`,bgMid:`#30271e`,bgLight:`#403527`,fg:`#ede3d0`,dim:`#a89478`,line:`#120d07`,acc:`#c68a4b`,ok:`#8aa15c`,warn:`#d9a441`,err:`#c25450`,tool:`#a67c52`,termBg:`#15100c`,termFg:`#e8dcc5`},matcha:{bgDarkest:`#1b2217`,bgDark:`#232b1e`,bgMid:`#2f3a28`,bgLight:`#3c4a33`,fg:`#e8eeda`,dim:`#9aab84`,line:`#131a10`,acc:`#8db64e`,ok:`#6fae4e`,warn:`#d8b13c`,err:`#cd5c50`,tool:`#5da88f`,termBg:`#151b11`,termFg:`#dfe8cb`},matrix:{bgDarkest:`#060a06`,bgDark:`#0a0f0a`,bgMid:`#122116`,bgLight:`#18301d`,fg:`#c9f2cf`,dim:`#6fa075`,line:`#030603`,acc:`#2fd558`,ok:`#39c95f`,warn:`#b8d977`,err:`#ff6b6b`,tool:`#57c99b`,termBg:`#030503`,termFg:`#33ff77`},sunset:{bgDarkest:`#1c1422`,bgDark:`#241b2b`,bgMid:`#33253e`,bgLight:`#452f52`,fg:`#f2e6ea`,dim:`#ab93a8`,line:`#150e1b`,acc:`#f2784b`,ok:`#63b46f`,warn:`#eda63d`,err:`#e25563`,tool:`#b06ac9`,termBg:`#170f1d`,termFg:`#f0dfe4`},sakura:{bgDarkest:`#22131f`,bgDark:`#251322`,bgMid:`#311a2d`,bgLight:`#3f213a`,fg:`#f6eaf3`,dim:`#bba6bd`,line:`#402b43`,acc:`#f2558e`,ok:`#34bd73`,warn:`#f5b83d`,err:`#f43f5e`,tool:`#a77bff`,termBg:`#170b15`,termFg:`#f2e6f0`},light:{bgDarkest:`#eceef4`,bgDark:`#f6f7fa`,bgMid:`#e2e5ee`,bgLight:`#ffffff`,fg:`#24272f`,dim:`#5d6470`,line:`#d8dbe4`,acc:`#4757d8`,ok:`#2b8a4b`,warn:`#b97a0f`,err:`#d83c3f`,tool:`#2278a8`,termBg:`#ffffff`,termFg:`#24272f`},strawberry:{bgDarkest:`#fbe4ea`,bgDark:`#fdf0f3`,bgMid:`#f7d4de`,bgLight:`#fffafb`,fg:`#4a2733`,dim:`#96707e`,line:`#f0ccd6`,acc:`#e05575`,ok:`#4d9e63`,warn:`#c98a2d`,err:`#d43d51`,tool:`#b05687`,termBg:`#fff5f8`,termFg:`#4a2733`},ramune:{bgDarkest:`#ddeff7`,bgDark:`#ecf7fb`,bgMid:`#c9e7f4`,bgLight:`#fbfeff`,fg:`#173342`,dim:`#5b7d90`,line:`#c2e2ef`,acc:`#1d86ae`,ok:`#3a9e6e`,warn:`#cf9a2a`,err:`#d64f5c`,tool:`#3a9db8`,termBg:`#f4fbfd`,termFg:`#173342`}},er=e=>typeof e==`string`&&e.length>0&&e.length<=64&&!/[;{}]/.test(e);function tr(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.id!=`string`||!/^[a-z0-9-]{1,40}$/i.test(t.id)||typeof t.label!=`string`||!t.label.trim()||t.mode!==`dark`&&t.mode!==`light`)return null;let n=t.palette;if(!n||typeof n!=`object`)return null;let r={};for(let{key:e}of Xn){if(!er(n[e]))return null;r[e]=n[e]}let i={id:t.id,label:t.label.slice(0,40),mode:t.mode,palette:r};if(typeof t.backgroundImage==`string`){let e=t.backgroundImage,n=/^\/api\/assets\/[a-f0-9]{32}\.(png|jpe?g|gif|webp|avif)$/i.test(e),r=/^data:image\//.test(e)&&e.length<=15e5,a=/^https?:\/\//.test(e);(n||r||a)&&(i.backgroundImage=e)}return typeof t.backgroundDim==`number`&&Number.isFinite(t.backgroundDim)&&(i.backgroundDim=Math.min(.9,Math.max(0,t.backgroundDim))),typeof t.backgroundImageBytes==`number`&&Number.isFinite(t.backgroundImageBytes)&&(i.backgroundImageBytes=Math.max(0,Math.round(t.backgroundImageBytes))),typeof t.surfaceAlpha==`number`&&Number.isFinite(t.surfaceAlpha)&&(i.surfaceAlpha=Math.min(1,Math.max(.35,t.surfaceAlpha))),i}function nr(){try{let e=localStorage.getItem(Zn);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(tr).filter(e=>e!==null):[]}catch{return[]}}function rr(e){try{return localStorage.setItem(Zn,JSON.stringify(e)),fetch(`/api/themes`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({themes:e})}).catch(()=>{}),{ok:!0}}catch(e){return{ok:!1,error:e.name===`QuotaExceededError`||/quota/i.test(String(e.message))?`storage is full — that background image is too large. Try a smaller one, or remove another theme.`:`could not save: ${e.message}`}}}async function ir(){try{let e=await fetch(`/api/themes`);if(!e.ok)return null;let t=await e.json();return Array.isArray(t.themes)?t.themes.map(tr).filter(e=>e!==null):null}catch{return null}}function ar(e){for(let t=0;;t++){let n=`custom-${Date.now().toString(36)}${t?`-${t}`:``}`;if(!e.includes(n))return n}}function or(e,t){let n=new Set([`--bg-darkest`,`--bg-dark`,`--bg-mid`,`--bg-light`]),r=!!t?.backgroundImage;for(let{key:i,cssVar:a}of Xn){let o=t?t.palette[i]:``;r&&n.has(a)?e.style.getPropertyValue(a)&&e.style.removeProperty(a):e.style.getPropertyValue(a)!==o&&(o?e.style.setProperty(a,o):e.style.removeProperty(a))}let i=t?.backgroundImage?String(t.backgroundDim??.55):``,a=t?.backgroundImage?String(t.surfaceAlpha??.82):``;for(let[t,n]of[[`--bg-image-dim`,i],[`--surface-alpha`,a]])e.style.getPropertyValue(t)!==n&&(n?e.style.setProperty(t,n):e.style.removeProperty(t));if(t?.backgroundImage){e.dataset&&(e.dataset.bgImage=`on`);for(let[n,r]of[[`--bg-darkest-solid`,t.palette.bgDarkest],[`--bg-dark-solid`,t.palette.bgDark],[`--bg-mid-solid`,t.palette.bgMid],[`--bg-light-solid`,t.palette.bgLight]]){let t=sr(r);e.style.getPropertyValue(n)!==t&&e.style.setProperty(n,t)}}else{e.dataset&&delete e.dataset.bgImage;for(let t of[`--bg-darkest-solid`,`--bg-dark-solid`,`--bg-mid-solid`,`--bg-light-solid`])e.style.removeProperty(t)}}function sr(e){let t=/^#([0-9a-f]{6})[0-9a-f]{2}$/i.exec(e.trim());return t?`#${t[1]}`:e}function cr(e){let t=e.trim().toLowerCase(),n=/^#?([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(t);if(!n)return null;let r=n[1];return r.length===3?`#${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}`:`#${r}`}function lr(e){if(e.customIds.includes(e.want)||e.presetIds.includes(e.want))return{active:e.want,repaired:!1};let t=e.fallback&&e.presetIds.includes(e.fallback)?e.fallback:`dark`;return{active:e.presetIds.includes(t)?t:e.presetIds[0]??`dark`,repaired:!0}}function ur(e,t,n){return e.find(e=>e.id===t)??e.find(e=>e.id===n)??e[0]}function dr(e){return e.preview?e.preview:e.auto?e.prefersLight?e.light:e.dark:e.fixed}var fr=Object.defineProperty,pr=Object.getOwnPropertyDescriptor,mr=(e,t)=>{for(var n in t)fr(e,n,{get:t[n],enumerable:!0})},hr=(e,t,n,r)=>{for(var i=r>1?void 0:r?pr(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&fr(t,n,i),i},z=(e,t)=>(n,r)=>t(n,r,e),gr=`Terminal input`,B={get:()=>gr,set:e=>gr=e},_r=`Too much output to announce, navigate to rows manually to read`,vr={get:()=>_r,set:e=>_r=e};function yr(e){return e.replace(/\r?\n/g,`\r`)}function br(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function xr(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function Sr(e,t,n,r){e.stopPropagation(),e.clipboardData&&Cr(e.clipboardData.getData(`text/plain`),t,n,r)}function Cr(e,t,n,r){e=yr(e),e=br(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function wr(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function Tr(e,t,n,r,i){wr(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Er(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Dr(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var Or=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},kr=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128||(c=(i&31)<<6|a&63,c<128)){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},Ar=``,jr=` `,Mr=class e{constructor(){this.fg=0,this.bg=0,this.extended=new Nr}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Nr=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Pr=class e extends Mr{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nr,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Er(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Fr=`di$target`,Ir=`di$dependencies`,Lr=new Map;function Rr(e){return e[Ir]||[]}function zr(e){if(Lr.has(e))return Lr.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);Br(t,e,r)};return t._id=e,Lr.set(e,t),t}function Br(e,t,n){t[Fr]===t?t[Ir].push({id:e,index:n}):(t[Ir]=[{id:e,index:n}],t[Fr]=t)}var Vr=zr(`BufferService`),Hr=zr(`CoreMouseService`),Ur=zr(`CoreService`),Wr=zr(`CharsetService`),Gr=zr(`InstantiationService`),Kr=zr(`LogService`),qr=zr(`OptionsService`),Jr=zr(`OscLinkService`),Yr=zr(`UnicodeService`),Xr=zr(`DecorationService`),Zr=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new Pr,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(c!==-1||n.hasContent(t)){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId){if(c===-1){c=t,s=a.extended.urlId;continue}l=a.extended.urlId!==s}else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):Qr(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};Zr=hr([z(0,Vr),z(1,qr),z(2,Jr)],Zr);function Qr(e,t){if(confirm(`Do you want to navigate to ${t}?
6
+ `);function r(e){return e.replace(/\t/g,` `).length}function i(t){let o=null,s=1,c=[];for(;n<e.length;){let l=e[n].match(Le);if(!l)break;let u=r(l[1]);if(u<t)break;let d=/^\d/.test(l[2]);if(o===null)o=d;else if(d!==o)break;if(o&&c.length===0){let e=Number.parseInt(l[2],10);Number.isFinite(e)&&(s=e)}n++;let f=l[3];for(;n<e.length&&/\S/.test(e[n])&&!Le.test(e[n])&&!/^#{1,6}\s/.test(e[n])&&!e[n].startsWith("```")&&!/^\s*&gt;/.test(e[n])&&!/^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(e[n])&&!/^ {0,3}={3,}\s*$/.test(e[n])&&!(e[n].includes(`|`)&&n+1<e.length&&Ve(e[n+1]));)f+=` `+e[n].trim(),n++;let p=``,m=e[n]?.match(Le);m&&r(m[1])>u&&(p=i(r(m[1])));let h=f.match(/^\[( |x|X)\]\s+(.*)$/),g=h?`<input type="checkbox" disabled${h[1].toLowerCase()===`x`?` checked`:``}> `:``;c.push(`<li>${g}${a(h?h[2]:f)}${p}</li>`);let _=n;for(;_<e.length&&!/\S/.test(e[_]);)_++;let v=e[_]?.match(Le);_>n&&v&&r(v[1])===u&&/^\d/.test(v[2])===o&&(n=_)}return o?s===1?`<ol>${c.join(``)}</ol>`:`<ol start="${s}">${c.join(``)}</ol>`:`<ul>${c.join(``)}</ul>`}function a(e){let t=[];return e=e.replace(/\u0000/g,``),e=e.replace(/`([^`]+)`/g,(e,n)=>(t.push(`<code>${n}</code>`),`\ue000${t.length-1}\uE001`)),e=e.replace(/!\[([^\]]*)\]\((https?:\/\/[^)\s]+)(?:\s+&quot;[^)]*&quot;)?\)/g,(e,n,r)=>(t.push(`<img src="${r}" alt="${n}" loading="lazy">`),`\ue000${t.length-1}\uE001`)),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)(?:\s+&quot;[^)]*&quot;)?\)/g,(e,n,r)=>(t.push(`<a href="${r}" rel="noopener noreferrer" target="_blank">${n}</a>`),`\ue000${t.length-1}\uE001`)),e=e.replace(/(?<!["'=\w])(https?:\/\/[^\s<>"')\]]*[^\s<>"')\].,;:!?"')\]])/g,`<a href="$1">$1</a>`),e=e.replace(/\*\*\*([\s\S]+?)\*\*\*/g,`<strong><em>$1</em></strong>`),e=e.replace(/\*\*([\s\S]+?)\*\*/g,`<strong>$1</strong>`),e=e.replace(/(^|[^\w])__(?=\S)([\s\S]*?\S)__(?!\w)/g,`$1<strong>$2</strong>`),e=e.replace(/(^|[^\w*])\*(?!\s)([^*\n]+?)\*(?![\w*])/g,`$1<em>$2</em>`),e=e.replace(/(^|[^\w])_(?!\s)([^_\n]+?)_(?!\w)/g,`$1<em>$2</em>`),e=e.replace(/~~([\s\S]+?)~~/g,`<del>$1</del>`),e.replace(/\ue000(\d+)\ue001/g,(e,n)=>t[+n]??``)}}function Be(e){let t=e.trim();t.startsWith(`|`)&&(t=t.slice(1));let n=[],r=``;for(let e=0;e<t.length;e++){let i=t[e];if(i===`\\`&&t[e+1]===`|`)r+=`|`,e++;else if(i==="`"){let n=t.indexOf("`",e+1);if(n!==-1){r+=t.slice(e,n+1).replace(/\\\|/g,`|`),e=n;continue}r+=i}else{if(i===`|`&&e===t.length-1)break;i===`|`?(n.push(r.trim()),r=``):r+=i}}return n.push(r.trim()),n.filter((e,r)=>!(e===``&&r===n.length-1&&t.endsWith(`|`)))}function Ve(e){let t=e.trim();if(!t.includes(`|`)||!t.includes(`-`))return!1;let n=Be(t);return n.every(e=>/^:?-+:?$/.test(e))&&n.some(e=>e!==``)}function He(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`)}function Ue(e){return Math.max(0,e.height-e.viewport)}function We(e){return e?Math.max(0,e.height-e.top-e.viewport):1/0}function Ge(e,t=24){return e?We(e)<=t:!1}function Ke(e,t,n,r){if(r!==void 0&&Math.abs(e.viewport-r)>.5||n!==void 0&&Math.abs(e.height-n)>.5)return`layout`;if(t){let n=Math.min(t.top,Ue(e));if(Math.abs(e.top-n)<=.5)return`programmatic`}return`reader`}function qe(e,t){return e?We(t)<=64:!1}function Je(e,t,n,r){return t===`reader`?r!==void 0&&n.top<r-.5?!1:Ge(n):e||Ge(n)}function Ye(e,t,n=.5){return e?We(t)>n:!1}var Xe=We;function Ze(e,t,n=200){return!t||e-t>=n}function Qe(e,t){let n=String(e??``).trim();return!n||!t||n===t}var[$e,et]=y(null),tt=$e;function nt(e){e&&et(e)}function rt(){et(null)}function it(e,t){let n=0,r=()=>{let t=0;for(let n of e.values())t+=n.bytes;return t};for(;e.size>t.maxEntries||r()>t.maxBytes;){let t,r=1/0;for(let[n,i]of e)i.at<r&&(r=i.at,t=n);if(t===void 0||(e.delete(t),n++,e.size===0))break}return n}function at(e,t=0){if(t>8)return 8;if(e==null)return 4;switch(typeof e){case`string`:return 16+e.length*2;case`number`:case`boolean`:return 8;case`object`:{if(Array.isArray(e)){let n=16;for(let r of e)n+=at(r,t+1);return n}let n=16;for(let[r,i]of Object.entries(e))n+=8+r.length*2+at(i,t+1);return n}default:return 8}}var ot=new Map,st=0,ct=500,lt=4194304;function ut(e){let t=ot.get(e);if(t!==void 0)return t;let n=Re(e);for(ot.set(e,n),st+=(e.length+n.length)*2;(ot.size>ct||st>lt)&&ot.size;){let e=ot.keys().next().value;if(e===void 0)break;let t=ot.get(e)??``;st-=(e.length+t.length)*2,ot.delete(e)}return n}function dt(e){if(e==null||!Number.isFinite(e))return`?`;let t=Math.max(0,e);if(t<1e3)return`${Math.round(t)}ms`;if(t<6e4)return`${(Math.floor(t/100)/10).toFixed(1)}s`;let n=Math.round(t/1e3);if(n<3600){let e=Math.floor(n/60),t=n%60;return t?`${e}m ${t}s`:`${e}m`}let r=Math.round(n/60),i=Math.floor(r/60),a=r%60;return a?`${i}h ${a}m`:`${i}h`}function ft(e,t){return e.length>t?e.slice(0,t)+` …`:e}function pt(e){let t=new Date(e).getTime()-Date.now(),n=Math.abs(t),r=n<9e4?`${Math.round(n/1e3)}s`:n<54e5?`${Math.round(n/6e4)}m`:`${(n/36e5).toFixed(1)}h`;return t>=0?`in ${r}`:`${r} ago`}function mt(e,t,n,r=Date.now()){let i=new Map(e);return i.set(t,{text:n.text??``,reasoning:n.reasoning??``,at:r}),i}function ht(e,t){if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}function gt(e){let t=e;return t?.type===`state`&&t.data?.detail===`llm turn start`||t?.type===`question`}function _t(e){return e===`running`||e===`waiting`||e===`needs_operator`}function vt(e,t,n){let r=e.text.trim(),i=St(t),a=_t(n);return{textCovered:!r||i.has(r),reasoningStale:!e.reasoning.trim()||xt(t).has(e.reasoning.trim())||a&&bt(t,e.at)}}function yt(e,t,n){let r=vt(e,t,n),i=r.textCovered?``:e.text,a=r.reasoningStale?``:e.reasoning,o=_t(n),s=!i.trim()&&!a.trim(),c=!!e.text.trim()||!!e.reasoning.trim();return{text:i,reasoning:a,live:o,empty:s&&(!o||c)}}function bt(e,t){return t?e.some(e=>{if(e.type!==`tool_call`)return!1;let n=Date.parse(String(e.ts??``));return Number.isFinite(n)&&n>t}):!1}function xt(e){let t=new Set;for(let n of e){let e=String(n.data?.reasoning??``).trim();e&&t.add(e)}return t}function St(e){let t=new Set;for(let n of e)n.type===`message`&&n.data?.role===`assistant`&&t.add(String(n.data.content??``).trim());return t}function Ct(e){if(!e)return!1;let t=e.data?.actor;return!(typeof t==`string`&&t.length>0)}var wt=new Set([`stopped`,`error`]),Tt=2e3;function Et(e,t,n=Date.now()){let r=[];for(let[i,a]of e){let e=t(i);e!==void 0&&(!wt.has(e)&&(_t(e)||n-Number(a?.at??0)<=Tt)||r.push(i))}if(r.length===0)return e;let i=new Map(e);for(let e of r)i.delete(e);return i}function Dt(e,t,n){if(!e)return null;let r=yt(e,t,n);return r.empty?null:r.text===e.text&&r.reasoning===e.reasoning?e:{text:r.text,reasoning:r.reasoning,at:e.at}}function Ot(e,t,n,r){if(!e)return 0;if(r)return e;if(!n)return 0;let i=t.find(e=>e.id===n);return i?.status===`running`||i?.status===`waiting`||i?.status===`needs_operator`?e:0}function kt(e,t){if(!t.length)return[...e].sort((e,t)=>e.seq-t.seq);let n=e.reduce((e,t)=>Math.max(e,t.seq),0),r=t.map((e,t)=>e.seq>n?e:{...e,seq:n+1+t});return[...e,...r].sort((e,t)=>e.seq-t.seq)}function At(e,t){if(t===void 0||t<=e.seq)return e;let n=jt.get(e);n||(n=new Map,jt.set(e,n));let r=n.get(t);if(r)return r;let i={...e,seq:t};return n.set(t,i),i}var jt=new WeakMap;function Mt(e,t){return t===void 0?e.reduce((e,t)=>Math.max(e,t.seq),0)+1:t}var Nt=new Set([`report_progress`,`ask_user`,`record_decision`]);function Pt(e){let{events:t,consumed:n,feedTypes:r}=e;return t.filter(e=>{if(e.type===`sub`)return!0;if(!r.has(e.type))return!1;let t=e.type===`tool_call`||e.type===`tool_result`?String(e.data?.name??``):``;if(Nt.has(t))return!1;if(e.type===`tool_result`)return!n.has(e.id);if(e.type===`message`){let t=String(e.data?.content??``),n=String(e.data?.reasoning??``);return t.trim()===``&&n.trim()!==``&&e.data?._prevKind===`tool`||e.data?.progressEcho||!e.data?.final&&t.trim()===`(tool call)`?!1:t.trim()!==``||n.trim()!==``||!!e.data?.final}return!0})}function Ft(e){let t=[];for(let n of e){if(n.type!==`sub`){t.push(n);continue}let e=n.data,r=String(e?.type??`message`);r!==`state`&&t.push({...n,type:r,data:{...e?.data??{},actor:e?.sub}})}return t}var It=e=>String(e??``).replace(/\s+/g,` `).trim().toLowerCase();function Lt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.type===`message`&&r.data?.role===`assistant`){let e=t[t.length-1],n=e?.type;if(n===`progress`||n===`decision`||e?.data?.progressEcho){let t=It(r.data?.content),n=It(e?.data?.content);if(t&&t===n)continue}}t.push(r)}return t}function Rt(e){let t=new Set,n=new Set,r=new Map,i=new Map;for(let a of e){let e=a.data?.promptId;e&&(a.type===`prompt`&&a.data?.source===`user`&&n.add(String(e)),a.type===`system_note`&&a.data?.event===`prompt-delivered`&&(t.add(String(e)),r.set(String(e),a.seq)),a.type===`system_note`&&a.data?.event===`prompt-cancelled`&&i.set(String(e),a.seq))}return{deliveredIds:t,loggedUserPrompts:n,deliveredNotes:r,cancelledNotes:i}}function zt(e,t,n){return e.filter(e=>{if(!t.renderedTypes.has(e.type))return e.type===`system_note`&&t.renderedNoteEvents.has(String(e.data?.event??``));if(e.type!==`prompt`||e.data?.source!==`user`)return!0;let r=String(e.data?.promptId??``);return r===``||!n.has(r)})}var Bt=new WeakMap;function Vt(e,t){let n=Bt.get(e);n||(n=new Map,Bt.set(e,n));let r=n.get(t);if(r)return r;let i={...e,data:{...e.data??{},cancelled:!0}};return n.set(t,i),i}function Ht(e,t){let n=t=>Mt(e,t),r=[];for(let i of e){if(i.type!==`prompt`||i.data?.source!==`user`){r.push(i);continue}let e=String(i.data?.promptId??``),a=t.cancelledNotes.get(e),o=t.deliveredNotes.get(e)??0,s=Math.max(o,a??0)||void 0,c=a===void 0?i:Vt(i,a);if(s!==void 0){r.push(At(c,s));continue}let l=n(c.seq);r.push(c.seq===l?c:{...c,seq:l})}return r}function Ut(e,t){return e.filter(e=>!e.promptId||!(t.deliveredIds.has(e.promptId)&&t.loggedUserPrompts.has(e.promptId)))}function Wt(e){let t=Lt(Ft(Pt(e))),n=Rt(t),r=new Set;for(let t of e.pending)t.promptId&&!n.deliveredIds.has(t.promptId)&&r.add(t.promptId);let i=Ht(zt(t,e,r),n),a=Ut(e.pending,n).map(e.echo);return{rows:kt(i,a),pendingCount:a.length}}function Gt(e){let t=e.event;return t===`status`||t===`audit-started`||t===`audit`||t===`audit-failed`?t:`other`}function Kt(e){let t=e.trim().toLowerCase();return t===``||t===`(no detail)`||t===`no detail`||t===`(none)`||t===`(empty)`}function qt(e,t){let n=String(e??``).trim();return Kt(n)?Kt(t)?``:t:n}function Jt(e){switch(Gt(e)){case`audit-started`:return{label:`🔍️ completion audit started`,detail:String(e.verify??``).trim()||`checking the verification contract…`,tone:``,markdown:!1,hasCard:!0};case`audit`:{let t=!Kt(String(e.feedback??``));return e.verdict===`approved`?{label:`✅ audit: approved`,detail:qt(e.feedback??``,``),tone:`ok`,markdown:!0,hasCard:t}:{label:`⚠ audit: changes required`,detail:qt(e.feedback??``,``),tone:`warn`,markdown:!0,hasCard:t}}case`audit-failed`:return{label:`🔍️ audit unavailable — finish accepted`,detail:String(e.detail??``).trim()||`the auditor could not be reached`,tone:`err`,markdown:!1,hasCard:!0};case`status`:{let t=String(e.status??``).trim();return t?t===`done`?String(e.by??``).trim()===`operator`?{label:`🏁 goal marked done`,detail:`you marked this goal done — no audit runs for a manual completion`,tone:``,markdown:!1,hasCard:!0}:{label:`🏁 finish claimed — pending audit`,detail:`the agent called finish(goalComplete=true); the verification contract is now being audited`,tone:``,markdown:!1,hasCard:!0}:t===`active`?String(e.by??``).trim()===`auditor`?{label:`▶ goal reopened`,detail:`the audit rejected the finish — work continues on the same goal`,tone:`warn`,markdown:!1,hasCard:!0}:{label:`▶ goal resumed`,detail:`marked active again — auto-continue picks the goal up from the next turn`,tone:``,markdown:!1,hasCard:!0}:{label:`🎯 goal ${t||`updated`}`,detail:String(e.text??``).trim()||`the goal is now ${t}`,tone:``,markdown:!0,hasCard:!0}:{label:`🎯 goal status updated`,detail:String(e.text??``).trim()||`no status recorded`,tone:``,markdown:!0,hasCard:!0}}default:{let t=String(e.text??``).trim(),n=String(e.event??``).trim();return{label:n?`🎯 goal ${n}`:`🎯 goal updated`,detail:t||`the "${n||`goal`}" event carried no further detail`,tone:``,markdown:!0,hasCard:!0}}}}var Yt=F(`<span class="meta muted">`),Xt=F(`<div class=ctitle>`),Zt=F(`<div>`),Qt=F(`<div class=cardbody>`);function $t(e){let t=()=>{let t=e.tone;return[`card`,t?`card-${t}`:``,e.class??``].filter(Boolean).join(` `)},n=()=>e.markdown===!1?Re(`\`\`\`\n${e.body}\n\`\`\``):Re(e.body);return(()=>{var r=Zt();return R(r,j(N,{get when(){return e.title},get children(){var t=Xt();return R(t,()=>e.title,null),R(t,j(N,{get when(){return e.meta},get children(){var t=Yt();return R(t,()=>e.meta),t}}),null),t}}),null),R(r,()=>e.children??(()=>{var e=Qt();return b(()=>e.innerHTML=n()),e})(),null),b(()=>L(r,t())),r})()}function en(e){let t=e.hideGhosts?e.agents.filter(e=>!e.workspaceMissing):e.agents,n=t.length?t:e.agents,r=e.urlId,i=r?e.ownerOf(r):void 0;return(i?n.find(e=>e.id===i):void 0)??n.find(t=>t.id===e.lastId)??n[0]}function tn(e,t){let n=new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()]}var nn=[320,640,1280,1920,2560,3840],rn=nn[0],an=/^\/api\/assets\/[a-f0-9]{32}\.(png|jpg|jpeg|gif|webp|avif)$/i;function on(e,t){if(e)return an.test(e)?`${e}?w=${t}`:e}function sn(e){if(e)return nn.map(t=>`${on(e,t)} ${t}w`).join(`, `)}function cn(e,t=rn){return on(e,t)}function ln(e,t=new Set,n=!1,r=new Set){let i=n?e.filter(t=>{if(!t.workspaceMissing)return!0;let n=[t.id],r=new Set;for(;n.length;){let t=n.pop();if(!r.has(t)){r.add(t);for(let i of e)i.parent===t&&!r.has(i.id)&&n.push(i.id)}}for(let t of r){let n=e.find(e=>e.id===t);if(n&&!n.workspaceMissing)return!0}return!1}):e,a=new Map,o=[];for(let e of i)e.parent&&i.some(t=>t.id===e.parent)?(a.has(e.parent)||a.set(e.parent,[]),a.get(e.parent).unshift(e)):o.push(e);let s=[],c=(e,n)=>{for(let o of e){let e=n===0&&r.has(mn(i,o));if(s.push({a:o,depth:n}),e)continue;let l=a.get(o.id);l?.length&&!t.has(o.id)&&c(l,n+1)}},l=[],u=new Map;for(let e of o){if(e.parent)continue;let t=un(i,e.id),n=u.get(t);n?n.push(e):(u.set(t,[e]),l.push(t))}for(let t of o){if(!t.parent)continue;let n=un(e,t.id)||``,r=u.get(n);r?r.push(t):(u.set(n,[t]),l.push(n))}for(let e of l)c(u.get(e),0);return s}function un(e,t,n=new Set){let r=e.find(e=>e.id===t);return r?!r.parent||n.has(t)?r.workspace||``:(n.add(t),un(e,r.parent,n)||r.workspace||``):``}function dn(e){return e.isSub?e.hasChildren:e.collapsed||e.hasChildren}function fn(e,t=[]){let n=e.indexOf(`-sub`);if(n===-1)return null;let r=e.slice(n+4).replace(/^-+/,``);if(!r)return null;let i=r.split(`-`);return(t.includes(i[0]??``)?i.slice(1).join(`-`):r).replace(/_/g,` `).trim()||null}function pn(e,t,n=new Set){let r=[],i=new Set(n);for(let n of e)n.parent===t&&(i.has(n.id)||(i.add(n.id),r.push(n,...pn(e,n.id,i))));return r}function mn(e,t){let n=t.id,r=new Set;for(;;){let t=e.find(e=>e.id===n);if(!t?.parent||r.has(n))break;r.add(n),n=t.parent}return`chat:${n||t.id}`}function hn(e){let t=new Map;for(let n of e){if(n.parent)continue;let r=un(e,n.id);r&&t.set(r,(t.get(r)??0)+1)}return t}function gn(e,t,n=new Set){let r=[],i=null;for(let a of t){let t=un(e,a.a.id);t?(t!==i&&(i=t,r.push({a:a.a,depth:0,headerOnly:!0,wsHeader:t,wsCollapsedGroup:n.has(`ws:${t}`)})),!n.has(`ws:${t}`)&&(n.has(mn(e,a.a))?r.push({a:a.a,depth:a.depth,chatCollapsedGroup:!0}):r.push({a:a.a,depth:a.depth}))):r.push({a:a.a,depth:a.depth})}return r}function _n(e,t=new Set){let n=new Set,r=-1,i=-1;for(let t of e)t.type===`question`?r=t.seq:t.type===`prompt`&&t.data?.source===`user`?i=t.seq:t.type===`system_note`&&t.data?.event===`prompt-delivered`&&(i=Math.max(i,t.seq));if(r>=0&&i>r)for(let t of e)t.type===`question`&&t.seq<=i&&n.add(String(t.data?.callId??``));for(let e of t)n.add(e);return n}var vn=(e,t,n)=>{if(t>=e.length)return e;if(n?.length){let r=new Set(n),i=e.filter(e=>e.promptId&&r.has(e.promptId));if(i.length){let n=e.filter(e=>!e.promptId);return n.length?[...i,...n].slice(0,t):i}}return e.slice(0,t)};function yn(e,t){let n=new Set(e.map(e=>e.promptId).filter(e=>!!e)),r=e.filter(e=>!e.promptId).map(e=>e.text),i=[];for(let e of t){let t=typeof e.id==`string`?e.id:``;if(!t||n.has(t))continue;let a=r.indexOf(String(e.text??``));a===-1?i.push({id:`p${t}`,text:String(e.text??``),at:Number(e.at)||Date.now(),promptId:t,images:e.images?.map(e=>e.url),...e.source?{source:e.source}:{}}):r.splice(a,1)}return i.length?[...e,...i]:e}function bn(e,t,n){let r=e??[];return n&&r.includes(n)?n:t&&r.includes(t)||t&&r.length===0?t:r[0]??null}function xn(e,t,n){return!t||n&&t===n?!0:typeof e==`string`&&e===t}function Sn(e,t,n){return!e||!t||e.agent!==t?!1:xn(e.session,n,t)}function Cn(e,t,n){return!e||!t||e.agentId!==t||!e.sessionId?!1:xn(e.sessionId,n,t)}function wn(e,t,n){return n?!e||!t||t===e.id||!e.session||e.session===t:!1}function Tn(e,t){if(t>=1)return e;let n=/^#([0-9a-f]{6})$/i.exec(e.trim());if(n){let e=Number.parseInt(n[1],16);return`rgba(${e>>16&255}, ${e>>8&255}, ${e&255}, ${Math.max(0,Math.min(1,t))})`}let r=/^rgba?\(([^)]+)\)$/i.exec(e.trim());if(r){let[e,n,i]=r[1].split(`,`).map(e=>e.trim());return`rgba(${e}, ${n}, ${i}, ${Math.max(0,Math.min(1,t))})`}return e}function En(e=1){let t=``,n=``,r=``,i=``;try{let e=getComputedStyle(document.documentElement);t=e.getPropertyValue(`--term-bg`).trim(),n=e.getPropertyValue(`--term-fg`).trim(),r=e.getPropertyValue(`--term-cursor`).trim(),i=e.getPropertyValue(`--term-cursor-accent`).trim()}catch{}let a=t||`#0d0e12`,o=Tn(a,e),s=n||`#dcdee4`;return{background:o,foreground:s,cursor:r||s,cursorAccent:i||a,selectionBackground:On(s),selectionForeground:s}}function Dn(e,t=1){let n=En(t),r=e.options.theme;r&&r.background===n.background&&r.foreground===n.foreground&&r.cursor===n.cursor&&r.cursorAccent===n.cursorAccent&&r.selectionBackground===n.selectionBackground||(e.options.theme=n)}function On(e){let t=e.trim(),n=/^#([0-9a-f]{6})$/i.exec(t);return n?`#${n[1]}47`:`rgba(128, 128, 128, 0.35)`}function kn(e,t,n){return e?.provider||n||Object.keys(t??{})[0]||``}function An(e,t){return t?String(e?.[t]?.model??``).trim():``}function jn(e,t,n){return An(e,t)||(n&&t===(n.provider??``)?n.model??``:``)}function Mn(e,t,n,r){return n?.model&&t===r?n.model:An(e,t)||n?.model||``}function Nn(e){return!e}function Pn(e){return!e}function Fn(e,t){return e!==t}function In(e,t){return Math.max(1,Math.min(e,t))}function Ln(e){return typeof e!=`number`||!Number.isFinite(e)?!1:e<0}function Rn(e){return e===`PageUp`||e===`ArrowUp`||e===`Home`}function zn(e,t,n){if(!n)return null;let r=e.find(e=>e.top+e.height>t+.5);if(!r)return null;let i=Math.min(Math.max(0,Math.round(t-r.top)),Math.max(0,Math.round(r.height)));return{session:n,eid:r.eid,offset:i}}function Bn(e,t,n){if(!e)return null;let r=t.find(t=>t.eid===e.eid);if(!r)return null;let i=Math.max(0,Math.min(n,Math.round(r.top+e.offset)));return Number.isFinite(n)&&i>=n-1?null:i}var Vn=`teapot.textareaH.`;function Hn(e){try{let t=Number(localStorage.getItem(Vn+e)??``);return Number.isFinite(t)&&t>0?t:0}catch{return 0}}function Un(e,t){try{localStorage.setItem(Vn+e,String(Math.round(t)))}catch{}}function Wn(e,t,n){return!n||!Number.isFinite(e)||e<=0?!1:!Number.isFinite(t)||t<=0||Math.abs(e-t)>=1}function Gn(e,t){let n=Hn(t);n>0&&(e.style.height=`${n}px`);let r=!1,i=()=>{r=!0};e.addEventListener(`pointerdown`,i);let a=new ResizeObserver(()=>{let n=e.offsetHeight;Wn(n,Hn(t),r)&&Un(t,n)});return a.observe(e),()=>{e.removeEventListener(`pointerdown`,i),a.disconnect()}}var Kn=e=>e?e.sessionTitle?.trim()||e.id:``,qn=(e,t)=>{if(!e)return``;let n=Kn(e),r=t?` — ${t}`:``;return n===e.id?`${n}${r}`:`${n} — ${e.id}${r}`},Jn=e=>e?Math.max(e.pendingPromptQueue?.length??0,e.pendingPromptIds?.length??0,e.pendingPrompts??0):0,Yn=e=>{let t=e.sameSession?Jn(e.agent):0;return Math.max(t,e.echoCount)},Xn=[{key:`bgDarkest`,cssVar:`--bg-darkest`,label:`surface (deepest)`},{key:`bgDark`,cssVar:`--bg-dark`,label:`surface`},{key:`bgMid`,cssVar:`--bg-mid`,label:`surface (raised)`},{key:`bgLight`,cssVar:`--bg-light`,label:`surface (control)`},{key:`fg`,cssVar:`--fg`,label:`text`},{key:`dim`,cssVar:`--dim`,label:`text (muted)`},{key:`line`,cssVar:`--line`,label:`divider`},{key:`acc`,cssVar:`--acc`,label:`accent`},{key:`ok`,cssVar:`--ok`,label:`success`},{key:`warn`,cssVar:`--warn`,label:`warning`},{key:`err`,cssVar:`--err`,label:`error`},{key:`tool`,cssVar:`--tool`,label:`tool accent`},{key:`termBg`,cssVar:`--term-bg`,label:`terminal background`},{key:`termFg`,cssVar:`--term-fg`,label:`terminal text`}],Zn=`teapot.customThemes`,Qn={bgDarkest:`#1a1c22`,bgDark:`#232630`,bgMid:`#2b2e39`,bgLight:`#343845`,fg:`#dcdee4`,dim:`#9298a5`,line:`#1d2027`,acc:`#5865f2`,ok:`#3ba55d`,warn:`#faa81a`,err:`#ed4245`,tool:`#3ba0c9`,termBg:`#0d0e12`,termFg:`#dcdee4`},$n={dark:{bgDarkest:`#1a1c22`,bgDark:`#232630`,bgMid:`#2b2e39`,bgLight:`#343845`,fg:`#dcdee4`,dim:`#9298a5`,line:`#1d2027`,acc:`#5865f2`,ok:`#3ba55d`,warn:`#faa81a`,err:`#ed4245`,tool:`#3ba0c9`,termBg:`#0d0e12`,termFg:`#dcdee4`},midnight:{bgDarkest:`#0d0f18`,bgDark:`#12141f`,bgMid:`#1b1f31`,bgLight:`#252a42`,fg:`#dfe2f2`,dim:`#8a90ad`,line:`#0a0c14`,acc:`#8b7cf7`,ok:`#54c08a`,warn:`#e5b567`,err:`#ef6a6a`,tool:`#6aa9e9`,termBg:`#0a0c13`,termFg:`#dfe2f2`},tea:{bgDarkest:`#241c16`,bgDark:`#2e241c`,bgMid:`#3b2f24`,bgLight:`#493b2d`,fg:`#f0e4d2`,dim:`#b39d82`,line:`#1b140f`,acc:`#d98e32`,ok:`#7fa653`,warn:`#e0b058`,err:`#cf5b47`,tool:`#c9975f`,termBg:`#1d1712`,termFg:`#ecdcc3`},coffee:{bgDarkest:`#191410`,bgDark:`#211a14`,bgMid:`#30271e`,bgLight:`#403527`,fg:`#ede3d0`,dim:`#a89478`,line:`#120d07`,acc:`#c68a4b`,ok:`#8aa15c`,warn:`#d9a441`,err:`#c25450`,tool:`#a67c52`,termBg:`#15100c`,termFg:`#e8dcc5`},matcha:{bgDarkest:`#1b2217`,bgDark:`#232b1e`,bgMid:`#2f3a28`,bgLight:`#3c4a33`,fg:`#e8eeda`,dim:`#9aab84`,line:`#131a10`,acc:`#8db64e`,ok:`#6fae4e`,warn:`#d8b13c`,err:`#cd5c50`,tool:`#5da88f`,termBg:`#151b11`,termFg:`#dfe8cb`},matrix:{bgDarkest:`#060a06`,bgDark:`#0a0f0a`,bgMid:`#122116`,bgLight:`#18301d`,fg:`#c9f2cf`,dim:`#6fa075`,line:`#030603`,acc:`#2fd558`,ok:`#39c95f`,warn:`#b8d977`,err:`#ff6b6b`,tool:`#57c99b`,termBg:`#030503`,termFg:`#33ff77`},sunset:{bgDarkest:`#1c1422`,bgDark:`#241b2b`,bgMid:`#33253e`,bgLight:`#452f52`,fg:`#f2e6ea`,dim:`#ab93a8`,line:`#150e1b`,acc:`#f2784b`,ok:`#63b46f`,warn:`#eda63d`,err:`#e25563`,tool:`#b06ac9`,termBg:`#170f1d`,termFg:`#f0dfe4`},sakura:{bgDarkest:`#22131f`,bgDark:`#251322`,bgMid:`#311a2d`,bgLight:`#3f213a`,fg:`#f6eaf3`,dim:`#bba6bd`,line:`#402b43`,acc:`#f2558e`,ok:`#34bd73`,warn:`#f5b83d`,err:`#f43f5e`,tool:`#a77bff`,termBg:`#170b15`,termFg:`#f2e6f0`},light:{bgDarkest:`#eceef4`,bgDark:`#f6f7fa`,bgMid:`#e2e5ee`,bgLight:`#ffffff`,fg:`#24272f`,dim:`#5d6470`,line:`#d8dbe4`,acc:`#4757d8`,ok:`#2b8a4b`,warn:`#b97a0f`,err:`#d83c3f`,tool:`#2278a8`,termBg:`#ffffff`,termFg:`#24272f`},strawberry:{bgDarkest:`#fbe4ea`,bgDark:`#fdf0f3`,bgMid:`#f7d4de`,bgLight:`#fffafb`,fg:`#4a2733`,dim:`#96707e`,line:`#f0ccd6`,acc:`#e05575`,ok:`#4d9e63`,warn:`#c98a2d`,err:`#d43d51`,tool:`#b05687`,termBg:`#fff5f8`,termFg:`#4a2733`},ramune:{bgDarkest:`#ddeff7`,bgDark:`#ecf7fb`,bgMid:`#c9e7f4`,bgLight:`#fbfeff`,fg:`#173342`,dim:`#5b7d90`,line:`#c2e2ef`,acc:`#1d86ae`,ok:`#3a9e6e`,warn:`#cf9a2a`,err:`#d64f5c`,tool:`#3a9db8`,termBg:`#f4fbfd`,termFg:`#173342`}},er=e=>typeof e==`string`&&e.length>0&&e.length<=64&&!/[;{}]/.test(e);function tr(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.id!=`string`||!/^[a-z0-9-]{1,40}$/i.test(t.id)||typeof t.label!=`string`||!t.label.trim()||t.mode!==`dark`&&t.mode!==`light`)return null;let n=t.palette;if(!n||typeof n!=`object`)return null;let r={};for(let{key:e}of Xn){if(!er(n[e]))return null;r[e]=n[e]}let i={id:t.id,label:t.label.slice(0,40),mode:t.mode,palette:r};if(typeof t.backgroundImage==`string`){let e=t.backgroundImage,n=/^\/api\/assets\/[a-f0-9]{32}\.(png|jpe?g|gif|webp|avif)$/i.test(e),r=/^data:image\//.test(e)&&e.length<=15e5,a=/^https?:\/\//.test(e);(n||r||a)&&(i.backgroundImage=e)}return typeof t.backgroundDim==`number`&&Number.isFinite(t.backgroundDim)&&(i.backgroundDim=Math.min(.9,Math.max(0,t.backgroundDim))),typeof t.backgroundImageBytes==`number`&&Number.isFinite(t.backgroundImageBytes)&&(i.backgroundImageBytes=Math.max(0,Math.round(t.backgroundImageBytes))),typeof t.surfaceAlpha==`number`&&Number.isFinite(t.surfaceAlpha)&&(i.surfaceAlpha=Math.min(1,Math.max(.35,t.surfaceAlpha))),i}function nr(){try{let e=localStorage.getItem(Zn);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(tr).filter(e=>e!==null):[]}catch{return[]}}function rr(e){try{return localStorage.setItem(Zn,JSON.stringify(e)),fetch(`/api/themes`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({themes:e})}).catch(()=>{}),{ok:!0}}catch(e){return{ok:!1,error:e.name===`QuotaExceededError`||/quota/i.test(String(e.message))?`storage is full — that background image is too large. Try a smaller one, or remove another theme.`:`could not save: ${e.message}`}}}async function ir(){try{let e=await fetch(`/api/themes`);if(!e.ok)return null;let t=await e.json();return Array.isArray(t.themes)?t.themes.map(tr).filter(e=>e!==null):null}catch{return null}}function ar(e){for(let t=0;;t++){let n=`custom-${Date.now().toString(36)}${t?`-${t}`:``}`;if(!e.includes(n))return n}}function or(e,t){let n=new Set([`--bg-darkest`,`--bg-dark`,`--bg-mid`,`--bg-light`]),r=!!t?.backgroundImage;for(let{key:i,cssVar:a}of Xn){let o=t?t.palette[i]:``;r&&n.has(a)?e.style.getPropertyValue(a)&&e.style.removeProperty(a):e.style.getPropertyValue(a)!==o&&(o?e.style.setProperty(a,o):e.style.removeProperty(a))}let i=t?.backgroundImage?String(t.backgroundDim??.55):``,a=t?.backgroundImage?String(t.surfaceAlpha??.82):``;for(let[t,n]of[[`--bg-image-dim`,i],[`--surface-alpha`,a]])e.style.getPropertyValue(t)!==n&&(n?e.style.setProperty(t,n):e.style.removeProperty(t));if(t?.backgroundImage){e.dataset&&(e.dataset.bgImage=`on`);for(let[n,r]of[[`--bg-darkest-solid`,t.palette.bgDarkest],[`--bg-dark-solid`,t.palette.bgDark],[`--bg-mid-solid`,t.palette.bgMid],[`--bg-light-solid`,t.palette.bgLight]]){let t=sr(r);e.style.getPropertyValue(n)!==t&&e.style.setProperty(n,t)}}else{e.dataset&&delete e.dataset.bgImage;for(let t of[`--bg-darkest-solid`,`--bg-dark-solid`,`--bg-mid-solid`,`--bg-light-solid`])e.style.removeProperty(t)}}function sr(e){let t=/^#([0-9a-f]{6})[0-9a-f]{2}$/i.exec(e.trim());return t?`#${t[1]}`:e}function cr(e){let t=e.trim().toLowerCase(),n=/^#?([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(t);if(!n)return null;let r=n[1];return r.length===3?`#${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}`:`#${r}`}function lr(e){if(e.customIds.includes(e.want)||e.presetIds.includes(e.want))return{active:e.want,repaired:!1};let t=e.fallback&&e.presetIds.includes(e.fallback)?e.fallback:`dark`;return{active:e.presetIds.includes(t)?t:e.presetIds[0]??`dark`,repaired:!0}}function ur(e,t,n){return e.find(e=>e.id===t)??e.find(e=>e.id===n)??e[0]}function dr(e){return e.preview?e.preview:e.auto?e.prefersLight?e.light:e.dark:e.fixed}var fr=Object.defineProperty,pr=Object.getOwnPropertyDescriptor,mr=(e,t)=>{for(var n in t)fr(e,n,{get:t[n],enumerable:!0})},hr=(e,t,n,r)=>{for(var i=r>1?void 0:r?pr(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&fr(t,n,i),i},z=(e,t)=>(n,r)=>t(n,r,e),gr=`Terminal input`,_r={get:()=>gr,set:e=>gr=e},vr=`Too much output to announce, navigate to rows manually to read`,yr={get:()=>vr,set:e=>vr=e};function br(e){return e.replace(/\r?\n/g,`\r`)}function xr(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function Sr(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function B(e,t,n,r){e.stopPropagation(),e.clipboardData&&Cr(e.clipboardData.getData(`text/plain`),t,n,r)}function Cr(e,t,n,r){e=br(e),e=xr(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function wr(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function Tr(e,t,n,r,i){wr(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Er(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Dr(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var Or=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},kr=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128||(c=(i&31)<<6|a&63,c<128)){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},Ar=``,jr=` `,Mr=class e{constructor(){this.fg=0,this.bg=0,this.extended=new Nr}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Nr=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Pr=class e extends Mr{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nr,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Er(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Fr=`di$target`,Ir=`di$dependencies`,Lr=new Map;function Rr(e){return e[Ir]||[]}function zr(e){if(Lr.has(e))return Lr.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);Br(t,e,r)};return t._id=e,Lr.set(e,t),t}function Br(e,t,n){t[Fr]===t?t[Ir].push({id:e,index:n}):(t[Ir]=[{id:e,index:n}],t[Fr]=t)}var Vr=zr(`BufferService`),Hr=zr(`CoreMouseService`),Ur=zr(`CoreService`),Wr=zr(`CharsetService`),Gr=zr(`InstantiationService`),Kr=zr(`LogService`),qr=zr(`OptionsService`),Jr=zr(`OscLinkService`),Yr=zr(`UnicodeService`),Xr=zr(`DecorationService`),Zr=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new Pr,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(c!==-1||n.hasContent(t)){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId){if(c===-1){c=t,s=a.extended.urlId;continue}l=a.extended.urlId!==s}else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):Qr(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};Zr=hr([z(0,Vr),z(1,qr),z(2,Jr)],Zr);function Qr(e,t){if(confirm(`Do you want to navigate to ${t}?
7
7
 
8
8
  WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var $r=zr(`CharSizeService`),ei=zr(`CoreBrowserService`),ti=zr(`MouseService`),ni=zr(`RenderService`),ri=zr(`SelectionService`),ii=zr(`CharacterJoinerService`),ai=zr(`ThemeService`),oi=zr(`LinkProviderService`),si=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?pi.isErrorNoTelemetry(e)?new pi(e.message+`
9
9
 
@@ -17,8 +17,8 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
17
17
  `:`
18
18
  `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),yc&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=Hc(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=rc(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-Uc),Uc),t/=Uc,t/Math.abs(t)+Math.round(t*(Wc-1)))}shouldForceSelection(e){return hc?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Gc)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(hc&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<Kc&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=Oc(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);n?!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n):this._oldHasSelection&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Hc(n,this._bufferService.cols)}};Jc=hr([z(3,Vr),z(4,Ur),z(5,ti),z(6,qr),z(7,ni),z(8,ei)],Jc);var Yc=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Xc=class{constructor(){this._color=new Yc,this._css=new Yc}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Zc=Object.freeze((()=>{let e=[Ts.toColor(`#2e3436`),Ts.toColor(`#cc0000`),Ts.toColor(`#4e9a06`),Ts.toColor(`#c4a000`),Ts.toColor(`#3465a4`),Ts.toColor(`#75507b`),Ts.toColor(`#06989a`),Ts.toColor(`#d3d7cf`),Ts.toColor(`#555753`),Ts.toColor(`#ef2929`),Ts.toColor(`#8ae234`),Ts.toColor(`#fce94f`),Ts.toColor(`#729fcf`),Ts.toColor(`#ad7fa8`),Ts.toColor(`#34e2e2`),Ts.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:Cs.toCss(r,i,a),rgba:Cs.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:Cs.toCss(n,n,n),rgba:Cs.toRgba(n,n,n)})}return e})()),Qc=Ts.toColor(`#ffffff`),$c=Ts.toColor(`#000000`),el=Ts.toColor(`#ffffff`),tl=$c,nl={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},rl=Qc,il=class extends H{constructor(e){super(),this._optionsService=e,this._contrastCache=new Xc,this._halfContrastCache=new Xc,this._onChangeColors=this._register(new U),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:Qc,background:$c,cursor:el,cursorAccent:tl,selectionForeground:void 0,selectionBackgroundTransparent:nl,selectionBackgroundOpaque:ws.blend($c,nl),selectionInactiveBackgroundTransparent:nl,selectionInactiveBackgroundOpaque:ws.blend($c,nl),scrollbarSliderBackground:ws.opacity(Qc,.2),scrollbarSliderHoverBackground:ws.opacity(Qc,.4),scrollbarSliderActiveBackground:ws.opacity(Qc,.5),overviewRulerBorder:Qc,ansi:Zc.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=K(e.foreground,Qc),t.background=K(e.background,$c),t.cursor=ws.blend(t.background,K(e.cursor,el)),t.cursorAccent=ws.blend(t.background,K(e.cursorAccent,tl)),t.selectionBackgroundTransparent=K(e.selectionBackground,nl),t.selectionBackgroundOpaque=ws.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=K(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ws.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?K(e.selectionForeground,Ss):void 0,t.selectionForeground===Ss&&(t.selectionForeground=void 0),ws.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ws.opacity(t.selectionBackgroundTransparent,.3)),ws.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ws.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=K(e.scrollbarSliderBackground,ws.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=K(e.scrollbarSliderHoverBackground,ws.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=K(e.scrollbarSliderActiveBackground,ws.opacity(t.foreground,.5)),t.overviewRulerBorder=K(e.overviewRulerBorder,rl),t.ansi=Zc.slice(),t.ansi[0]=K(e.black,Zc[0]),t.ansi[1]=K(e.red,Zc[1]),t.ansi[2]=K(e.green,Zc[2]),t.ansi[3]=K(e.yellow,Zc[3]),t.ansi[4]=K(e.blue,Zc[4]),t.ansi[5]=K(e.magenta,Zc[5]),t.ansi[6]=K(e.cyan,Zc[6]),t.ansi[7]=K(e.white,Zc[7]),t.ansi[8]=K(e.brightBlack,Zc[8]),t.ansi[9]=K(e.brightRed,Zc[9]),t.ansi[10]=K(e.brightGreen,Zc[10]),t.ansi[11]=K(e.brightYellow,Zc[11]),t.ansi[12]=K(e.brightBlue,Zc[12]),t.ansi[13]=K(e.brightMagenta,Zc[13]),t.ansi[14]=K(e.brightCyan,Zc[14]),t.ansi[15]=K(e.brightWhite,Zc[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=K(e.extendedAnsi[r],Zc[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0)for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];else switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};il=hr([z(0,qr)],il);function K(e,t){if(e!==void 0)try{return Ts.toColor(e)}catch{}return t}var al=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},ol=class{constructor(){this._services=new al,this._services.set(Gr,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=Rr(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},sl={trace:0,debug:1,info:2,warn:3,error:4,off:5},cl=`xterm.js: `,ll=class extends H{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),ul=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=sl[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:cl)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};ll=hr([z(0,qr)],ll);var ul,dl=class extends H{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new U),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new U),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new U),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},q=3,fl=Object.freeze(new Mr),pl=0,ml=2,hl=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*q);let r=t||Pr.fromCharData([0,Ar,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*q+0],n=t&2097151;return[this._data[e*q+1],t&2097152?this._combined[e]:n?Er(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*q+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*q+0]=e|2097152|t[2]<<22):this._data[e*q+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*q+0]>>22}hasWidth(e){return this._data[e*q+0]&12582912}getFg(e){return this._data[e*q+1]}getBg(e){return this._data[e*q+2]}hasContent(e){return this._data[e*q+0]&4194303}getCodePoint(e){let t=this._data[e*q+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*q+0]&2097152}getString(e){let t=this._data[e*q+0];return t&2097152?this._combined[e]:t&2097151?Er(t&2097151):``}isProtected(e){return this._data[e*q+2]&536870912}loadCell(e,t){return pl=e*q,t.content=this._data[pl+0],t.fg=this._data[pl+1],t.bg=this._data[pl+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*q+0]=t.content,this._data[e*q+1]=t.fg,this._data[e*q+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*q+0]=t|n<<22,this._data[e*q+1]=r.fg,this._data[e*q+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*q+0];r&2097152?this._combined[e]+=Er(t):r&2097151?(this._combined[e]=Er(r&2097151)+Er(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*q+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new Pr;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new Pr;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*ml<this._data.buffer.byteLength;let n=e*q;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*ml<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*ml<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*q+0]&4194303)return e+(this._data[e*q+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*q+0]&4194303||this._data[e*q+2]&50331648)return e+(this._data[e*q+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<q;e++)this._data[(n+i)*q+e]=a[(t+i)*q+e];a[(t+i)*q+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<q;e++)this._data[(n+i)*q+e]=a[(t+i)*q+e];a[(t+i)*q+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*q+0],n=e&2097151,a=e&2097152?this._combined[t]:n?Er(n):jr;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function gl(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=bl(u,d,t),p=1,m=0;for(;p<u.length;){let e=bl(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function _l(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function vl(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function yl(e,t,n){let r=[],i=e.map((n,r)=>bl(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=bl(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function bl(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var xl=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new U),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Ti(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};xl._nextId=1;var Sl=xl,Cl={},wl=Cl.B;Cl[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:`␤`,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},Cl.A={"#":`£`},Cl.B=void 0,Cl[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},Cl.C=Cl[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Cl.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},Cl.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},Cl.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},Cl.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},Cl.E=Cl[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},Cl.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},Cl.H=Cl[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Cl[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var Tl=4294967295,El=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=fl.clone(),this.savedCharset=wl,this.markers=[],this._nullCell=Pr.fromCharData([0,Ar,1,0]),this._whitespaceCell=Pr.fromCharData([0,jr,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new wc,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new dl(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Nr),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Nr),this._whitespaceCell}getBlankLine(e,t){return new hl(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>Tl?Tl:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=fl);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new dl(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(fl),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new hl(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new hl(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=gl(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(fl),n);if(r.length>0){let n=_l(this.lines,r);vl(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(fl),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new hl(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(fl),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=yl(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(fl,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=bl(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-->0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new Sl(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Dl=class extends H{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new U),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new El(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new El(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Ol=2,kl=1,Al=class extends H{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new U),this.onResize=this._onResize.event,this._onScroll=this._register(new U),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Ol),this.rows=Math.max(e.rawOptions.rows||0,kl),this.buffers=this._register(new Dl(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Al=hr([z(0,qr)],Al);var jl={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:hc,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Ml=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],Nl=class extends H{constructor(e){super(),this._onOptionChange=this._register(new U),this.onOptionChange=this._onOptionChange.event;let t={...jl};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(V(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in jl))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in jl))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=jl[e],!Pl(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=jl[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Ml.includes(t)?t:jl[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function Pl(e){return e===`block`||e===`underline`||e===`bar`}function Fl(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&Fl(e[r],t-1);return n}var Il=Object.freeze({insertMode:!1}),Ll=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Rl=class extends H{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new U),this.onData=this._onData.event,this._onUserInput=this._register(new U),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new U),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new U),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Fl(Il),this.decPrivateModes=Fl(Ll)}reset(){this.modes=Fl(Il),this.decPrivateModes=Fl(Ll)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};Rl=hr([z(0,Vr),z(1,Kr),z(2,qr)],Rl);var zl={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function Bl(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var Vl=String.fromCharCode,Hl={DEFAULT:e=>{let t=[Bl(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${Vl(t[0])}${Vl(t[1])}${Vl(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Bl(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Bl(e,!0)};${e.x};${e.y}${t}`}},Ul=class extends H{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new U),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(zl))this.addProtocol(e,zl[e]);for(let e of Object.keys(Hl))this.addEncoding(e,Hl[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};Ul=hr([z(0,Vr),z(1,Ur),z(2,qr)],Ul);var Wl=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],Gl=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Kl;function ql(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var Jl=class{constructor(){if(this.version=`6`,!Kl){Kl=new Uint8Array(65536),Kl.fill(1),Kl[0]=0,Kl.fill(0,1,32),Kl.fill(0,127,160),Kl.fill(2,4352,4448),Kl[9001]=2,Kl[9002]=2,Kl.fill(2,11904,42192),Kl[12351]=1,Kl.fill(2,44032,55204),Kl.fill(2,63744,64256),Kl.fill(2,65040,65050),Kl.fill(2,65072,65136),Kl.fill(2,65280,65377),Kl.fill(2,65504,65511);for(let e=0;e<Wl.length;++e)Kl.fill(0,Wl[e][0],Wl[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?Kl[e]:ql(e,Gl)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=Yl.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return Yl.createPropertyValue(0,n,r)}},Yl=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new U,this.onChange=this._onChange.event;let e=new Jl;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},Xl=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Zl(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var Ql=2147483647,$l=256,eu=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>$l)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>Ql?Ql:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>Ql?Ql:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,Ql):e}},tu=[],nu=class{constructor(){this._state=0,this._active=tu,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=tu}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=tu,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||tu,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,Dr(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=tu,this._id=-1,this._state=0}}},ru=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=Dr(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},iu=[],au=class{constructor(){this._handlers=Object.create(null),this._active=iu,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=iu}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=iu,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||iu,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,Dr(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=iu,this._ident=0}},ou=new eu;ou.addParam(0);var su=class{constructor(e){this._handler=e,this._data=``,this._params=ou,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():ou,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=Dr(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=ou,this._data=``,this._hitLimit=!1,e));return this._params=ou,this._data=``,this._hitLimit=!1,t}},cu=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},lu=160,uu=function(){let e=new cu(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(lu,0,2,0),e.add(lu,8,5,8),e.add(lu,6,0,6),e.add(lu,11,0,11),e.add(lu,13,13,13),e}(),du=class extends H{constructor(e=uu){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new eu,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(V(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new nu),this._dcsParser=this._register(new au),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:lu)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<lu||++i>=t||(r=e[i])<32||r>126&&r<lu||++i>=t||(r=e[i])<32||r>126&&r<lu||++i>=t||(r=e[i])<32||r>126&&r<lu){this._printHandler(e,n,i),n=i-1;break}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<lu){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<lu){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=i&15}}},fu=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,pu=/^[\da-f]+$/;function mu(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=fu.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),pu.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function hu(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function gu(e,t=16){let[n,r,i]=e;return`rgb:${hu(n,t)}/${hu(r,t)}/${hu(i,t)}`}var _u={"(":0,")":1,"*":2,"+":3,"-":1,".":2},vu=131072,yu=10;function bu(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var xu=5e3,Su=0,Cu=class extends H{constructor(e,t,n,r,i,a,o,s,c=new du){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Or,this._utf8Decoder=new kr,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=fl.clone(),this._eraseAttrDataInternal=fl.clone(),this._onRequestBell=this._register(new U),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new U),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new U),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new U),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new U),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new U),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new U),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new U),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new U),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new U),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new U),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new U),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new U),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new wu(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler(G.BEL,()=>this.bell()),this._parser.setExecuteHandler(G.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(G.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(G.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(G.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(G.BS,()=>this.backspace()),this._parser.setExecuteHandler(G.HT,()=>this.tab()),this._parser.setExecuteHandler(G.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(G.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(hs.IND,()=>this.index()),this._parser.setExecuteHandler(hs.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(hs.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new ru(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new ru(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new ru(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new ru(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new ru(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new ru(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new ru(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new ru(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new ru(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new ru(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new ru(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new ru(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in Cl)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new su((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),xu))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${xu} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>vu&&(a=this._parseStack.position+vu)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<vu&&(this._parseBuffer=new Uint32Array(Math.min(e.length,vu))),o||this._dirtyRowTracker.clearRange(),e.length>vu)for(let t=a;t<e.length;t+=vu){let a=t+vu<e.length?t+vu:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=Yl.extractWidth(t);let n=Yl.extractShouldJoin(t),m=n?Yl.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(Er(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof hl&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}else if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!bu(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new su(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new ru(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(fl));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=Yl.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(G.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(G.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(G.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(G.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(G.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,wl),this._charsetService.setgCharset(1,wl),this._charsetService.setgCharset(2,wl),this._charsetService.setgCharset(3,wl);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${G.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=Mr.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=fl.fg,e.bg=fl.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=fl.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=fl.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=fl.fg&16777215,r.bg&=-67108864,r.bg|=fl.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${G.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${G.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${G.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=fl.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!bu(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${G.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>yu&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>yu&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(Tu(n)){if(r===`?`)t.push({type:0,index:n});else{let e=mu(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=mu(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);Tu(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,wl),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(_u[e[0]],Cl[e[1]]||wl),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=fl.clone(),this._eraseAttrDataInternal=fl.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Pr;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${G.ESC}${e}${G.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},wu=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Su=e,e=t,t=Su),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};wu=hr([z(0,Vr)],wu);function Tu(e){return 0<=e&&e<256}var Eu=5e7,Du=12,Ou=50,ku=class extends H{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new U),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>Eu)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=Du?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=Du)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>Ou&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Au=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Au=hr([z(0,Vr)],Au);var ju=!1,Mu=class extends H{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new ki),this._onBinary=this._register(new U),this.onBinary=this._onBinary.event,this._onData=this._register(new U),this.onData=this._onData.event,this._onLineFeed=this._register(new U),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new U),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new U),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new U),this._instantiationService=new ol,this.optionsService=this._register(new Nl(e)),this._instantiationService.setService(qr,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Al)),this._instantiationService.setService(Vr,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(ll)),this._instantiationService.setService(Kr,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Rl)),this._instantiationService.setService(Ur,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Ul)),this._instantiationService.setService(Hr,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Yl)),this._instantiationService.setService(Yr,this.unicodeService),this._charsetService=this._instantiationService.createInstance(Xl),this._instantiationService.setService(Wr,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Au),this._instantiationService.setService(Jr,this._oscLinkService),this._inputHandler=this._register(new Cu(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Ii.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Ii.forward(this._bufferService.onResize,this._onResize)),this._register(Ii.forward(this.coreService.onData,this._onData)),this._register(Ii.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new ku((e,t)=>this._inputHandler.parse(e,t))),this._register(Ii.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new U),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!ju&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),ju=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Ol),t=Math.max(t,kl),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Zl.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(Zl(this._bufferService),!1))),this._windowsWrappingHeuristics.value=V(()=>{for(let t of e)t.dispose()})}}},Nu={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function Pu(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?G.ESC+`OA`:G.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?G.ESC+`OD`:G.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?G.ESC+`OC`:G.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?G.ESC+`OB`:G.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:G.DEL,e.altKey&&(i.key=G.ESC+i.key);break;case 9:if(e.shiftKey){i.key=G.ESC+`[Z`;break}i.key=G.HT,i.cancel=!0;break;case 13:i.key=e.altKey?G.ESC+G.CR:G.CR,i.cancel=!0;break;case 27:i.key=G.ESC,e.altKey&&(i.key=G.ESC+G.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?G.ESC+`[1;`+(a+1)+`D`:t?G.ESC+`OD`:G.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?G.ESC+`[1;`+(a+1)+`C`:t?G.ESC+`OC`:G.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?G.ESC+`[1;`+(a+1)+`A`:t?G.ESC+`OA`:G.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?G.ESC+`[1;`+(a+1)+`B`:t?G.ESC+`OB`:G.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=G.ESC+`[2~`);break;case 46:i.key=a?G.ESC+`[3;`+(a+1)+`~`:G.ESC+`[3~`;break;case 36:i.key=a?G.ESC+`[1;`+(a+1)+`H`:t?G.ESC+`OH`:G.ESC+`[H`;break;case 35:i.key=a?G.ESC+`[1;`+(a+1)+`F`:t?G.ESC+`OF`:G.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?G.ESC+`[5;`+(a+1)+`~`:G.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?G.ESC+`[6;`+(a+1)+`~`:G.ESC+`[6~`;break;case 112:i.key=a?G.ESC+`[1;`+(a+1)+`P`:G.ESC+`OP`;break;case 113:i.key=a?G.ESC+`[1;`+(a+1)+`Q`:G.ESC+`OQ`;break;case 114:i.key=a?G.ESC+`[1;`+(a+1)+`R`:G.ESC+`OR`;break;case 115:i.key=a?G.ESC+`[1;`+(a+1)+`S`:G.ESC+`OS`;break;case 116:i.key=a?G.ESC+`[15;`+(a+1)+`~`:G.ESC+`[15~`;break;case 117:i.key=a?G.ESC+`[17;`+(a+1)+`~`:G.ESC+`[17~`;break;case 118:i.key=a?G.ESC+`[18;`+(a+1)+`~`:G.ESC+`[18~`;break;case 119:i.key=a?G.ESC+`[19;`+(a+1)+`~`:G.ESC+`[19~`;break;case 120:i.key=a?G.ESC+`[20;`+(a+1)+`~`:G.ESC+`[20~`;break;case 121:i.key=a?G.ESC+`[21;`+(a+1)+`~`:G.ESC+`[21~`;break;case 122:i.key=a?G.ESC+`[23;`+(a+1)+`~`:G.ESC+`[23~`;break;case 123:i.key=a?G.ESC+`[24;`+(a+1)+`~`:G.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=G.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=G.DEL:e.keyCode===219?i.key=G.ESC:e.keyCode===220?i.key=G.FS:e.keyCode===221&&(i.key=G.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=Nu[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=G.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=G.ESC+n}else if(e.keyCode===32)i.key=G.ESC+(e.ctrlKey?G.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=G.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=G.US),e.key===`@`&&(i.key=G.NUL))}return i}var Fu=0,Iu=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new wc,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new wc,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(Fu=this._search(t),Fu===-1)||this._getKey(this._array[Fu])!==t)return!1;do if(this._array[Fu]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Fu),!0;while(++Fu<this._array.length&&this._getKey(this._array[Fu])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Fu=this._search(e),!(Fu<0||Fu>=this._array.length)&&this._getKey(this._array[Fu])===e))do yield this._array[Fu];while(++Fu<this._array.length&&this._getKey(this._array[Fu])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Fu=this._search(e),!(Fu<0||Fu>=this._array.length)&&this._getKey(this._array[Fu])===e))do t(this._array[Fu]);while(++Fu<this._array.length&&this._getKey(this._array[Fu])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},Lu=0,Ru=0,zu=class extends H{constructor(){super(),this._decorations=new Iu(e=>e?.marker.line),this._onDecorationRegistered=this._register(new U),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new U),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(V(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Bu(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{Lu=t.options.x??0,Ru=Lu+(t.options.width??1),e>=Lu&&e<Ru&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},Bu=class extends Oi{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new U),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new U),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this._cachedBg=this.options.backgroundColor?Ts.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?Ts.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Vu=1e3,Hu=class{constructor(e,t=Vu){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Uu=20,Wu=class extends H{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Hu(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
19
19
  `))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(W(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(V(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<Uu+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
20
- `&&(this._liveRegionLineCount++,this._liveRegionLineCount===Uu+1&&(this._liveRegion.textContent+=vr.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};Wu=hr([z(1,Gr),z(2,ei),z(3,ni)],Wu);var Gu=class extends H{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new U),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new U),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(V(()=>{Ti(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(W(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(W(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(W(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(W(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){this._activeLine!==e.y||this._wasResized?(this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1):this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&Ku(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Ti(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};Gu=hr([z(1,ti),z(2,ni),z(3,Vr),z(4,oi)],Gu);function Ku(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var qu=class extends Mu{constructor(e={}){super(e),this._linkifier=this._register(new ki),this.browser=sc,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new ki),this._onCursorMove=this._register(new U),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new U),this.onKey=this._onKey.event,this._onRender=this._register(new U),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new U),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new U),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new U),this.onBell=this._onBell.event,this._onFocus=this._register(new U),this._onBlur=this._register(new U),this._onA11yCharEmitter=this._register(new U),this._onA11yTabEmitter=this._register(new U),this._onWillOpen=this._register(new U),this._setup(),this._decorationService=this._instantiationService.createInstance(zu),this._instantiationService.setService(Xr,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(nc),this._instantiationService.setService(oi,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Zr)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(Ii.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Ii.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Ii.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Ii.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(V(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=ws.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${G.ESC}]${n};${gu(r)}${gs.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=Cs.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=Cs.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Wu,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(G.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(G.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(W(this.element,`copy`,e=>{this.hasSelection()&&xr(e,this._selectionService)}));let e=e=>Sr(e,this.textarea,this.coreService,this.optionsService);this._register(W(this.textarea,`paste`,e)),this._register(W(this.element,`paste`,e)),dc?this._register(W(this.element,`mousedown`,e=>{e.button===2&&Tr(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(W(this.element,`contextmenu`,e=>{Tr(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),yc&&this._register(W(this.element,`auxclick`,e=>{e.button===1&&wr(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(W(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(W(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(W(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(W(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(W(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(W(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(W(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(W(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,B.get()),bc||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(ec,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(ei,this._coreBrowserService),this._register(W(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(W(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Xs,this._document,this._helperContainer),this._instantiationService.setService($r,this._charSizeService),this._themeService=this._instantiationService.createInstance(il),this._instantiationService.setService(ai,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(js),this._instantiationService.setService(ii,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Ec,this.rows,this.screenElement)),this._instantiationService.setService(ni,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(_s,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(ac),this._instantiationService.setService(ti,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Gu,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(cs,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(Jc,this.element,this.screenElement,r)),this._instantiationService.setService(ri,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(Ii.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(ls,this.screenElement)),this._register(W(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Wu,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ms,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ms,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Ys,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(W(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(W(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=G.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Cr(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=Pu(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===G.ETX||n.key===G.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Ju(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e===this.cols&&t===this.rows?this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure():super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(fl));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent(G.ESC+`[I`):this.coreService.triggerDataEvent(G.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${G.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${G.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function Ju(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var Yu=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},Xu=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Pr)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},Zu=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new Xu(t)}getNullCell(){return new Pr}},Qu=class extends H{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new U),this.onBufferChange=this._onBufferChange.event,this._normal=new Zu(this._core.buffers.normal,`normal`),this._alternate=new Zu(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},$u=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},ed=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},td=[`cols`,`rows`],nd=0,rd=class extends H{constructor(e){super(),this._core=this._register(new qu(e)),this._addonManager=this._register(new Yu),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(td.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new $u(this._core),this._parser}get unicode(){return this._checkProposedApi(),new ed(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new Qu(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
21
- `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return B.get()},set promptLabel(e){B.set(e)},get tooMuchOutput(){return vr.get()},set tooMuchOutput(e){vr.set(e)}}}_verifyIntegers(...e){for(nd of e)if(nd===1/0||isNaN(nd)||nd%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(nd of e)if(nd&&(nd===1/0||isNaN(nd)||nd%1!=0||nd<0))throw Error(`This API only accepts positive integers`)}},id=2,ad=1,od=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(id,Math.floor(u/e.css.cell.width)),rows:Math.max(ad,Math.floor(l/e.css.cell.height))}}};function sd(e){return e.length}function cd(e,t){return t<=0||e<0?-1:Math.min(e,t-1)}function ld(e,t,n){return cd(e===t?t:e>t?e-1:e,n)}function ud(e,t){return Array.from({length:t},(e,t)=>t).find(t=>t!==e)??-1}function dd(e,t){let n=e.filter(e=>!t.has(e.id));return n.find(e=>!e.workspaceMissing)??n[0]??null}function fd(e){return!(e.key!==`Enter`||e.shiftKey||e.composing||e.maximized)}function pd(e){return e}async function md(e,t={}){if(!e)return`unsupported`;let n=t.clipboard===void 0?typeof navigator<`u`?navigator.clipboard??null:null:t.clipboard,r=t.execCommand??(typeof document<`u`?document.execCommand.bind(document):void 0),i=t.makeTextarea??(()=>{let e=document.createElement(`textarea`);return document.body.appendChild(e),{set value(t){e.value=t},get value(){return e.value},style:{get position(){return e.style.position},set position(t){e.style.position=t},get opacity(){return e.style.opacity},set opacity(t){e.style.opacity=t}},select:()=>e.select(),remove:()=>e.remove()}}),a=n?.writeText;if(typeof a==`function`)try{return await a.call(n,e),`copied`}catch{}let o=null;try{let t=i();return o=t,t.value=e,t.style.position=`fixed`,t.style.opacity=`0`,t.select(),r&&r(`copy`)?`copied`:`failed`}catch{return`failed`}finally{o?.remove()}}var hd=F(`<button type=button><span class=iconbtn-glyph>`),gd=F(`<button class=copybtn>`),_d=F(`<div class=overlay><div class=modal><div class=modal-head><b></b><button class=iconbtn>✕`);function vd(e){return(()=>{var t=hd(),n=t.firstChild;return De(t,`click`,e.onClick,!0),R(n,()=>e.icon),b(n=>{var r=`iconbtn`+(e.active?` active`:``)+(e.class?` `+e.class:``),i=e.title,a=e.style;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),n.a=Oe(t,a,n.a),n},{e:void 0,t:void 0,a:void 0}),t})()}function yd(e){let[t,n]=y(!1),[r,i]=y(!1),a=t=>{t.preventDefault(),t.stopPropagation(),md(e.text??``).then(e=>{e===`unsupported`||e===`failed`?(i(!0),setTimeout(()=>i(!1),1200)):(n(!0),setTimeout(()=>n(!1),900))})};return(()=>{var n=gd();return n.$$click=a,R(n,(()=>{var n=P(()=>!!t());return()=>n()?`✓`:P(()=>!!r())()?`✗`:e.label??`⧉`})()),b(()=>I(n,`title`,e.title??`copy to clipboard`)),n})()}function bd(e){return(()=>{var t=_d(),n=t.firstChild,r=n.firstChild.firstChild,i=r.nextSibling;return t.$$click=t=>t.target===t.currentTarget&&e.onClose(),R(r,()=>e.title),De(i,`click`,e.onClose,!0),R(n,()=>e.children,null),t})()}Ee([`click`]);var xd={fg:void 0,bg:void 0,bold:!1,dim:!1,italic:!1,underline:!1,inverse:!1},Sd=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`];function Cd(e){let t=[];return e.fg&&t.push(`ansi-fg-${e.fg}`),e.bg&&t.push(`ansi-bg-${e.bg}`),e.bold&&t.push(`ansi-bold`),e.dim&&t.push(`ansi-dim`),e.italic&&t.push(`ansi-italic`),e.underline&&t.push(`ansi-underline`),e.inverse&&t.push(`ansi-inverse`),t}function wd(e,t){let n={...e};t.length===0&&(t=[0]);for(let e=0;e<t.length;e++){let r=t[e];if(r===0)n.fg=void 0,n.bg=void 0,n.bold=!1,n.dim=!1,n.italic=!1,n.underline=!1,n.inverse=!1;else if(r===1)n.bold=!0;else if(r===2)n.dim=!0;else if(r===3)n.italic=!0;else if(r===4)n.underline=!0;else if(r===7)n.inverse=!0;else if(r===21||r===22)n.bold=!1,n.dim=!1;else if(r===23)n.italic=!1;else if(r===24)n.underline=!1;else if(r===27)n.inverse=!1;else if(r>=30&&r<=37)n.fg=Sd[r-30];else if(r>=90&&r<=97)n.fg=`bright-${Sd[r-90]}`;else if(r===39)n.fg=void 0;else if(r>=40&&r<=47)n.bg=Sd[r-40];else if(r>=100&&r<=107)n.bg=`bright-${Sd[r-100]}`;else if(r===49)n.bg=void 0;else if(r===38||r===48){let i=t[e+1],a=r===38?`fg`:`bg`;i===5&&t[e+2]!==void 0?(n[a]=`ext`,e+=2):i===2&&t[e+4]!==void 0?(n[a]=`ext`,e+=4):(n[a]=`ext`,e+=1)}}return n}var Td=/\x1b\[([0-9;]*)m/;function Ed(e){if(!e)return[];let t=[],n={...xd},r=``,i=()=>{if(!r)return;let e=Cd(n),i=t[t.length-1];i&&i.classes.join(` `)===e.join(` `)?i.text+=r:t.push({text:r,classes:e}),r=``};for(let t=0;t<e.length;t++){let a=e[t];if(a===`\x1B`){let r=e.slice(t),a=Td.exec(r);if(a){i();let e=(a[1]??``).split(`;`).filter(e=>e!==``).map(e=>Number(e)).filter(e=>Number.isFinite(e));n=wd(n,e),t+=a[0].length-1;continue}let o=/^\x1b\[[0-9;?]*[A-Za-z]/.exec(r);if(o){t+=o[0].length-1;continue}let s=/^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/.exec(r);if(s){t+=s[0].length-1;continue}}else if(a===`\r`){if(e[t+1]===`
20
+ `&&(this._liveRegionLineCount++,this._liveRegionLineCount===Uu+1&&(this._liveRegion.textContent+=yr.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};Wu=hr([z(1,Gr),z(2,ei),z(3,ni)],Wu);var Gu=class extends H{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new U),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new U),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(V(()=>{Ti(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(W(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(W(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(W(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(W(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){this._activeLine!==e.y||this._wasResized?(this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1):this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&Ku(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Ti(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};Gu=hr([z(1,ti),z(2,ni),z(3,Vr),z(4,oi)],Gu);function Ku(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var qu=class extends Mu{constructor(e={}){super(e),this._linkifier=this._register(new ki),this.browser=sc,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new ki),this._onCursorMove=this._register(new U),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new U),this.onKey=this._onKey.event,this._onRender=this._register(new U),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new U),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new U),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new U),this.onBell=this._onBell.event,this._onFocus=this._register(new U),this._onBlur=this._register(new U),this._onA11yCharEmitter=this._register(new U),this._onA11yTabEmitter=this._register(new U),this._onWillOpen=this._register(new U),this._setup(),this._decorationService=this._instantiationService.createInstance(zu),this._instantiationService.setService(Xr,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(nc),this._instantiationService.setService(oi,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Zr)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(Ii.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Ii.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Ii.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Ii.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(V(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=ws.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${G.ESC}]${n};${gu(r)}${gs.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=Cs.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=Cs.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Wu,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(G.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(G.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(W(this.element,`copy`,e=>{this.hasSelection()&&Sr(e,this._selectionService)}));let e=e=>B(e,this.textarea,this.coreService,this.optionsService);this._register(W(this.textarea,`paste`,e)),this._register(W(this.element,`paste`,e)),dc?this._register(W(this.element,`mousedown`,e=>{e.button===2&&Tr(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(W(this.element,`contextmenu`,e=>{Tr(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),yc&&this._register(W(this.element,`auxclick`,e=>{e.button===1&&wr(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(W(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(W(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(W(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(W(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(W(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(W(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(W(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(W(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,_r.get()),bc||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(ec,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(ei,this._coreBrowserService),this._register(W(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(W(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Xs,this._document,this._helperContainer),this._instantiationService.setService($r,this._charSizeService),this._themeService=this._instantiationService.createInstance(il),this._instantiationService.setService(ai,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(js),this._instantiationService.setService(ii,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Ec,this.rows,this.screenElement)),this._instantiationService.setService(ni,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(_s,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(ac),this._instantiationService.setService(ti,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Gu,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(cs,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(Jc,this.element,this.screenElement,r)),this._instantiationService.setService(ri,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(Ii.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(ls,this.screenElement)),this._register(W(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Wu,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ms,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ms,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Ys,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(W(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(W(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=G.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Cr(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=Pu(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===G.ETX||n.key===G.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Ju(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e===this.cols&&t===this.rows?this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure():super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(fl));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent(G.ESC+`[I`):this.coreService.triggerDataEvent(G.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${G.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${G.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function Ju(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var Yu=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},Xu=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Pr)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},Zu=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new Xu(t)}getNullCell(){return new Pr}},Qu=class extends H{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new U),this.onBufferChange=this._onBufferChange.event,this._normal=new Zu(this._core.buffers.normal,`normal`),this._alternate=new Zu(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},$u=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},ed=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},td=[`cols`,`rows`],nd=0,rd=class extends H{constructor(e){super(),this._core=this._register(new qu(e)),this._addonManager=this._register(new Yu),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(td.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new $u(this._core),this._parser}get unicode(){return this._checkProposedApi(),new ed(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new Qu(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
21
+ `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return _r.get()},set promptLabel(e){_r.set(e)},get tooMuchOutput(){return yr.get()},set tooMuchOutput(e){yr.set(e)}}}_verifyIntegers(...e){for(nd of e)if(nd===1/0||isNaN(nd)||nd%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(nd of e)if(nd&&(nd===1/0||isNaN(nd)||nd%1!=0||nd<0))throw Error(`This API only accepts positive integers`)}},id=2,ad=1,od=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(id,Math.floor(u/e.css.cell.width)),rows:Math.max(ad,Math.floor(l/e.css.cell.height))}}};function sd(e){return e.length}function cd(e,t){return t<=0||e<0?-1:Math.min(e,t-1)}function ld(e,t,n){return cd(e===t?t:e>t?e-1:e,n)}function ud(e,t){return Array.from({length:t},(e,t)=>t).find(t=>t!==e)??-1}function dd(e,t){let n=e.filter(e=>!t.has(e.id));return n.find(e=>!e.workspaceMissing)??n[0]??null}function fd(e){return!(e.key!==`Enter`||e.shiftKey||e.composing||e.maximized)}function pd(e){return e}async function md(e,t={}){if(!e)return`unsupported`;let n=t.clipboard===void 0?typeof navigator<`u`?navigator.clipboard??null:null:t.clipboard,r=t.execCommand??(typeof document<`u`?document.execCommand.bind(document):void 0),i=t.makeTextarea??(()=>{let e=document.createElement(`textarea`);return document.body.appendChild(e),{set value(t){e.value=t},get value(){return e.value},style:{get position(){return e.style.position},set position(t){e.style.position=t},get opacity(){return e.style.opacity},set opacity(t){e.style.opacity=t}},select:()=>e.select(),remove:()=>e.remove()}}),a=n?.writeText;if(typeof a==`function`)try{return await a.call(n,e),`copied`}catch{}let o=null;try{let t=i();return o=t,t.value=e,t.style.position=`fixed`,t.style.opacity=`0`,t.select(),r&&r(`copy`)?`copied`:`failed`}catch{return`failed`}finally{o?.remove()}}var hd=F(`<button type=button><span class=iconbtn-glyph>`),gd=F(`<button class=copybtn>`),_d=F(`<div class=overlay><div class=modal><div class=modal-head><b></b><button class=iconbtn>✕`);function vd(e){return(()=>{var t=hd(),n=t.firstChild;return De(t,`click`,e.onClick,!0),R(n,()=>e.icon),b(n=>{var r=`iconbtn`+(e.active?` active`:``)+(e.class?` `+e.class:``),i=e.title,a=e.style;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),n.a=Oe(t,a,n.a),n},{e:void 0,t:void 0,a:void 0}),t})()}function yd(e){let[t,n]=y(!1),[r,i]=y(!1),a=t=>{t.preventDefault(),t.stopPropagation(),md(e.text??``).then(e=>{e===`unsupported`||e===`failed`?(i(!0),setTimeout(()=>i(!1),1200)):(n(!0),setTimeout(()=>n(!1),900))})};return(()=>{var n=gd();return n.$$click=a,R(n,(()=>{var n=P(()=>!!t());return()=>n()?`✓`:P(()=>!!r())()?`✗`:e.label??`⧉`})()),b(()=>I(n,`title`,e.title??`copy to clipboard`)),n})()}function bd(e){return(()=>{var t=_d(),n=t.firstChild,r=n.firstChild.firstChild,i=r.nextSibling;return t.$$click=t=>t.target===t.currentTarget&&e.onClose(),R(r,()=>e.title),De(i,`click`,e.onClose,!0),R(n,()=>e.children,null),t})()}Ee([`click`]);var xd={fg:void 0,bg:void 0,bold:!1,dim:!1,italic:!1,underline:!1,inverse:!1},Sd=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`];function Cd(e){let t=[];return e.fg&&t.push(`ansi-fg-${e.fg}`),e.bg&&t.push(`ansi-bg-${e.bg}`),e.bold&&t.push(`ansi-bold`),e.dim&&t.push(`ansi-dim`),e.italic&&t.push(`ansi-italic`),e.underline&&t.push(`ansi-underline`),e.inverse&&t.push(`ansi-inverse`),t}function wd(e,t){let n={...e};t.length===0&&(t=[0]);for(let e=0;e<t.length;e++){let r=t[e];if(r===0)n.fg=void 0,n.bg=void 0,n.bold=!1,n.dim=!1,n.italic=!1,n.underline=!1,n.inverse=!1;else if(r===1)n.bold=!0;else if(r===2)n.dim=!0;else if(r===3)n.italic=!0;else if(r===4)n.underline=!0;else if(r===7)n.inverse=!0;else if(r===21||r===22)n.bold=!1,n.dim=!1;else if(r===23)n.italic=!1;else if(r===24)n.underline=!1;else if(r===27)n.inverse=!1;else if(r>=30&&r<=37)n.fg=Sd[r-30];else if(r>=90&&r<=97)n.fg=`bright-${Sd[r-90]}`;else if(r===39)n.fg=void 0;else if(r>=40&&r<=47)n.bg=Sd[r-40];else if(r>=100&&r<=107)n.bg=`bright-${Sd[r-100]}`;else if(r===49)n.bg=void 0;else if(r===38||r===48){let i=t[e+1],a=r===38?`fg`:`bg`;i===5&&t[e+2]!==void 0?(n[a]=`ext`,e+=2):i===2&&t[e+4]!==void 0?(n[a]=`ext`,e+=4):(n[a]=`ext`,e+=1)}}return n}var Td=/\x1b\[([0-9;]*)m/;function Ed(e){if(!e)return[];let t=[],n={...xd},r=``,i=()=>{if(!r)return;let e=Cd(n),i=t[t.length-1];i&&i.classes.join(` `)===e.join(` `)?i.text+=r:t.push({text:r,classes:e}),r=``};for(let t=0;t<e.length;t++){let a=e[t];if(a===`\x1B`){let r=e.slice(t),a=Td.exec(r);if(a){i();let e=(a[1]??``).split(`;`).filter(e=>e!==``).map(e=>Number(e)).filter(e=>Number.isFinite(e));n=wd(n,e),t+=a[0].length-1;continue}let o=/^\x1b\[[0-9;?]*[A-Za-z]/.exec(r);if(o){t+=o[0].length-1;continue}let s=/^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/.exec(r);if(s){t+=s[0].length-1;continue}}else if(a===`\r`){if(e[t+1]===`
22
22
  `){r+=`
23
23
  `,t++;continue}r=``}else r+=a}return i(),t}function Dd(e){return Ed(e).map(e=>e.text).join(``)}function Od(e){return e.includes(`\x1B`)}var kd=400,Ad=new Map;function jd(e){return Ad.get(e)}function Md(e,t){if(Ad.size>=kd){let e=Ad.keys().next();e.done||Ad.delete(e.value)}Ad.set(e,t)}var Nd=`modulepreload`,Pd=function(e){return`/`+e},Fd={},Id=function(e){return e.pathname.endsWith(`.css`)},Ld=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},J=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=Pd(t,n);let r=s(t),i=Id(r);return Ld(Fd,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:Nd,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Rd=F(`<span class=bashelapsed>running… `),zd=F(`<span class=bashelapsed> elapsed`),Bd=F(`<span class=thinktimer>`),Vd=F(`<pre class="mono toolbody ansi">`),Hd=F(`<pre class="mono toolbody">`),Ud=F(`<span>`),Wd=F(`<div class="toolbody shiki">`);function Gd(e){let t=new Date(e.startedAt).getTime(),[n,r]=y(Date.now());w(()=>{let e=setInterval(()=>r(Date.now()),500);T(()=>clearInterval(e))});let i=()=>dt(Math.max(0,n()-t));return e.inline?(()=>{var t=Rd();return t.firstChild,R(t,i,null),R(t,(()=>{var t=P(()=>!!e.timeoutMs);return()=>t()?` · timeout ${Math.round(e.timeoutMs/1e3)}s`:``})(),null),t})():(()=>{var e=zd(),t=e.firstChild;return R(e,i,t),e})()}function Kd(e){let[t,n]=y(Date.now());w(()=>{let e=setInterval(()=>n(Date.now()),500);T(()=>clearInterval(e))});let r=()=>{if(!e.startedAt)return null;let n=Math.max(0,t()-e.startedAt);return n>864e5?null:dt(n)};return j(N,{get when(){return r()!==null},fallback:null,get children(){var e=Bd();return R(e,r),e}})}function qd(e){let t=S(()=>Od(e.text)?Ed(e.text):null);return j(N,{get when(){return t()},get fallback(){return(()=>{var t=Hd();return R(t,()=>e.text),t})()},get children(){var e=Vd();return R(e,j(M,{get each(){return t()},children:e=>e.classes.length?(()=>{var t=Ud();return R(t,()=>e.text),b(()=>L(t,e.classes.join(` `))),t})():e.text})),e}})}function Jd(e){let t=()=>e.lang?`${e.lang}::${e.text.length}::${e.text}`:``,[n,r]=y((e.lang?jd(t()):void 0)??``);return x(()=>{let n=t(),i=e.text,a=e.lang;if(!a||!i.trim()){r(``);return}let o=jd(n);o===void 0?(async()=>{try{let{highlightLangChunks:e}=await J(async()=>{let{highlightLangChunks:e}=await Promise.resolve().then(()=>px);return{highlightLangChunks:e}},void 0),o=``;for await(let t of e(a,i))o+=t;if(!o)return;Md(n,o),t()===n&&r(o)}catch{}})():r(o)}),j(N,{get when(){return!!n()},get fallback(){return(()=>{var t=Hd();return R(t,()=>e.text),t})()},get children(){var e=Wd();return b(()=>e.innerHTML=n()),e}})}var Yd=[{key:`dark`,label:`Dark`,mode:`dark`,sw:[`#1a1c22`,`#2b2e39`,`#5865f2`]},{key:`midnight`,label:`Midnight`,mode:`dark`,sw:[`#0d0f18`,`#252a42`,`#8b7cf7`]},{key:`tea`,label:`Milk Tea`,mode:`dark`,sw:[`#241c16`,`#493b2d`,`#d98e32`]},{key:`coffee`,label:`Coffee`,mode:`dark`,sw:[`#191410`,`#403527`,`#c68a4b`]},{key:`matcha`,label:`Matcha`,mode:`dark`,sw:[`#1b2217`,`#3c4a33`,`#8db64e`]},{key:`matrix`,label:`Matrix`,mode:`dark`,sw:[`#060a06`,`#18301d`,`#2fd558`]},{key:`sunset`,label:`Sunset`,mode:`dark`,sw:[`#1c1422`,`#452f52`,`#f2784b`]},{key:`sakura`,label:`Sakura`,mode:`dark`,sw:[`#22131f`,`#3f213a`,`#f2558e`]},{key:`light`,label:`Light`,mode:`light`,sw:[`#eceef4`,`#ffffff`,`#4757d8`]},{key:`strawberry`,label:`Strawberry`,mode:`light`,sw:[`#fbe4ea`,`#fffafb`,`#e05575`]},{key:`ramune`,label:`Ramune`,mode:`light`,sw:[`#ddeff7`,`#fbfeff`,`#1d86ae`]}];async function Y(e,t){let n=localStorage.getItem(`teapot.token`),r=new Headers(t?.headers);n&&!r.has(`authorization`)&&r.set(`authorization`,`Bearer ${n}`);let i=await fetch(e,{...t,headers:r});if(!i.ok){i.status===401&&window.dispatchEvent(new CustomEvent(`teapot:unauthorized`));let t=null;try{t=await i.json()}catch{}let n=(t&&typeof t==`object`&&`error`in t?String(t.error):``)||`${e}: HTTP ${i.status}`;throw Object.assign(Error(n),{payload:t})}return i.json()}var Xd=.82,Zd=.9,Qd=e=>{if(Number.isFinite(e))return e<0?0:e>1?1:e};function $d(e,t){let n=Qd(e??Xd)??Xd;return{dim:Qd(t??Zd)??Zd,panel:Math.max(0,Math.min(1,n-.05)),raised:Math.max(0,Math.min(1,n+.06))}}function ef(e,t){return`color-mix(in srgb, ${e} ${Math.round((Qd(t)??Zd)*100)}%, transparent)`}function tf(e,t){let n=e?.trim();if(n)return`url("${(t?on(n,t)??n:n).replace(/"/g,`%22`)}")`}var nf=F(`<div class="content mdpreview todopane">`),rf=F(`<textarea id=todo-input class="mono todopane-edit"rows=5 placeholder="- [ ] task one
24
24
  - [ ] task two"title="shared with the agent \\u2014 it may check items off via set_todo; your unsaved edits win until you save">`),af=F(`<div class="filepreview shikiwrap">`),of=F(`<div class=muted style=padding-top:6px;font-size:11.5px>… truncated (first 100 KB)`),sf=F(`<div class=muted style=padding:8px;font-size:12px>✨ highlighting <!>…`),cf=F(`<pre class=mono style=max-height:62vh;overflow:auto;white-space:pre-wrap;margin:0>`),lf=F(`<label><input type=number min=0>`),uf=F(`<span class=tprev-bg>`),df=F(`<span class=tprev-veil>`),ff=F(`<span class=tprev><span class=tprev-nav></span><span class=tprev-head></span><span class=tprev-panel></span><span class=tprev-line style=left:32%;top:38%;width:34%;opacity:0.85></span><span class=tprev-line style=left:32%;top:50%;width:22%></span><span class=tprev-line style=left:32%;top:62%;width:40%></span><span class=tprev-dot style=left:6%;top:20%></span><span class=tprev-dot style=left:6%;top:40%></span><span class=tprev-dot style=left:6%;top:60%></span><span class=tprev-dot style=left:70%;top:12%></span><span class=tprev-dot style=left:84%;top:12%>`);function pf(e){let t=Number(localStorage.getItem(`teapot.todoH`)??``),[n,r]=y(Number.isFinite(t)&&t>0?t:0),i=()=>n()>0?{height:`${n()}px`}:void 0,a=e=>{let t=new ResizeObserver(()=>{let t=e.offsetHeight;t<=0||r(e=>Math.abs(e-t)<1?e:(localStorage.setItem(`teapot.todoH`,String(t)),t))});t.observe(e),T(()=>t.disconnect())};return j(N,{get when(){return e.preview},get fallback(){return(()=>{var t=rf();return t.$$input=t=>e.onDraft(t.currentTarget.value),Ae(a,t),b(e=>Oe(t,i(),e)),b(()=>t.value=e.draft),t})()},get children(){var t=nf();return Ae(a,t),b(n=>{var r=i(),a=ut(e.draft);return n.e=Oe(t,r,n.e),a!==n.t&&(t.innerHTML=n.t=a),n},{e:void 0,t:void 0}),t}})}function mf(e){return[j(N,{get when(){return e.html},get fallback(){return P(()=>!!e.pending)()?(()=>{var t=sf(),n=t.firstChild.nextSibling;return n.nextSibling,R(t,()=>e.path.split(`/`).pop(),n),t})():(()=>{var t=cf();return R(t,()=>e.content),t})()},get children(){var t=af();return b(()=>t.innerHTML=e.html),t}}),j(N,{get when(){return e.truncated},get children(){return of()}})]}function hf(e){return(()=>{var t=lf(),n=t.firstChild;return R(t,()=>e.label,n),n.$$input=t=>e.onValue(Number(t.currentTarget.value)),b(()=>I(t,`title`,e.hint)),b(()=>n.value=e.value),t})()}function gf(e){let t=()=>e.palette,n=()=>$d(e.surfaceAlpha,e.backgroundDim);return(()=>{var r=ff(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.nextSibling,d=u.nextSibling,f=d.nextSibling,p=f.nextSibling,m=p.nextSibling;return R(r,j(N,{get when(){return e.backgroundImage},get children(){return[(()=>{var t=uf();return b(n=>ke(t,`background-image`,tf(e.backgroundImage,rn))),t})(),(()=>{var e=df();return b(r=>ke(e,`background`,ef(t().bgDark,n().dim))),e})()]}}),i),b(h=>{var g=t().bgDark,_=t().bgDarkest,v=e.backgroundImage?String(n().panel):`1`,ee=t().bgDarkest,y=e.backgroundImage?String(n().panel):`1`,b=t().bgMid,x=e.backgroundImage?String(n().raised):`1`,S=t().fg,C=t().acc,w=t().dim,T=t().acc,E=t().dim,D=t().ok,O=t().warn,te=t().err;return g!==h.e&&ke(r,`background`,h.e=g),_!==h.t&&ke(i,`background`,h.t=_),v!==h.a&&ke(i,`opacity`,h.a=v),ee!==h.o&&ke(a,`background`,h.o=ee),y!==h.i&&ke(a,`opacity`,h.i=y),b!==h.n&&ke(o,`background`,h.n=b),x!==h.s&&ke(o,`opacity`,h.s=x),S!==h.h&&ke(s,`background`,h.h=S),C!==h.r&&ke(c,`background`,h.r=C),w!==h.d&&ke(l,`background`,h.d=w),T!==h.l&&ke(u,`background`,h.l=T),E!==h.u&&ke(d,`background`,h.u=E),D!==h.c&&ke(f,`background`,h.c=D),O!==h.w&&ke(p,`background`,h.w=O),te!==h.m&&ke(m,`background`,h.m=te),h},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0,m:void 0}),r})()}Ee([`input`]);var[_f,vf]=y(``),yf,bf=e=>{vf(e),clearTimeout(yf),yf=setTimeout(()=>vf(``),3200)};function xf(e,t){if(!t.startsWith(`blobs/`)||!e)return t;let n=t.slice(6);return`/api/agents/${encodeURIComponent(e)}/blobs/${encodeURIComponent(n)}`}var Sf=class extends Error{constructor(e){super(e),this.name=`ShikiError`}};function Cf(e){return wf(e)}function wf(e){return Array.isArray(e)?Tf(e):e instanceof RegExp?e:typeof e==`object`?Ef(e):e}function Tf(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=wf(e[n]);return t}function Ef(e){let t={};for(let n in e)t[n]=wf(e[n]);return t}function Df(e,...t){return t.forEach(t=>{for(let n in t)e[n]=t[n]}),e}function Of(e){let t=~e.lastIndexOf(`/`)||~e.lastIndexOf(`\\`);return t===0?e:~t===e.length-1?Of(e.substring(0,e.length-1)):e.substr(~t+1)}var kf=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,Af=class{static hasCaptures(e){return e!==null&&(kf.lastIndex=0,kf.test(e))}static replaceCaptures(e,t,n){return e.replace(kf,(e,r,i,a)=>{let o=n[parseInt(r||i,10)];if(o){let e=t.substring(o.start,o.end);for(;e[0]===`.`;)e=e.substring(1);switch(a){case`downcase`:return e.toLowerCase();case`upcase`:return e.toUpperCase();default:return e}}else return e})}};function jf(e,t){return e<t?-1:+(e>t)}function Mf(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,r=t.length;if(n===r){for(let r=0;r<n;r++){let n=jf(e[r],t[r]);if(n!==0)return n}return 0}return n-r}function Nf(e){return!!(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{8}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e)||/^#[0-9a-f]{4}$/i.test(e))}function Pf(e){return e.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,`\\$&`)}var Ff=class{constructor(e){this.fn=e}cache=new Map;get(e){if(this.cache.has(e))return this.cache.get(e);let t=this.fn(e);return this.cache.set(e,t),t}},If=class{constructor(e,t,n){this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(Vf(e),t)}static createFromParsedTheme(e,t){return Wf(e,t)}_cachedMatchRoot=new Ff(e=>this._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,n=this._cachedMatchRoot.get(t).find(t=>Rf(e.parent,t.parentScopes));return n?new Bf(n.fontStyle,n.foreground,n.background):null}},Lf=class e{constructor(e,t){this.parent=e,this.scopeName=t}static push(t,n){for(let r of n)t=new e(t,r);return t}static from(...t){let n=null;for(let r=0;r<t.length;r++)n=new e(n,t[r]);return n}push(t){return new e(this,t)}getSegments(){let e=this,t=[];for(;e;)t.push(e.scopeName),e=e.parent;return t.reverse(),t}toString(){return this.getSegments().join(` `)}extends(e){return this===e||this.parent!==null&&this.parent.extends(e)}getExtensionIfDefined(e){let t=[],n=this;for(;n&&n!==e;)t.push(n.scopeName),n=n.parent;return n===e?t.reverse():void 0}};function Rf(e,t){if(t.length===0)return!0;for(let n=0;n<t.length;n++){let r=t[n],i=!1;if(r===`>`){if(n===t.length-1)return!1;r=t[++n],i=!0}for(;e&&!zf(e.scopeName,r);){if(i)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function zf(e,t){return t===e||e.startsWith(t)&&e[t.length]===`.`}var Bf=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}};function Vf(e){if(!e||!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],r=0;for(let e=0,i=t.length;e<i;e++){let i=t[e];if(!i.settings)continue;let a;if(typeof i.scope==`string`){let e=i.scope;e=e.replace(/^[,]+/,``),e=e.replace(/[,]+$/,``),a=e.split(`,`)}else a=Array.isArray(i.scope)?i.scope:[``];let o=-1;if(typeof i.settings.fontStyle==`string`){o=0;let e=i.settings.fontStyle.split(` `);for(let t=0,n=e.length;t<n;t++)switch(e[t]){case`italic`:o|=1;break;case`bold`:o|=2;break;case`underline`:o|=4;break;case`strikethrough`:o|=8}}let s=null;typeof i.settings.foreground==`string`&&Nf(i.settings.foreground)&&(s=i.settings.foreground);let c=null;typeof i.settings.background==`string`&&Nf(i.settings.background)&&(c=i.settings.background);for(let t=0,i=a.length;t<i;t++){let i=a[t].trim().split(` `),l=i[i.length-1],u=null;i.length>1&&(u=i.slice(0,i.length-1),u.reverse()),n[r++]=new Hf(l,u,e,o,s,c)}}return n}var Hf=class{constructor(e,t,n,r,i,a){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=r,this.foreground=i,this.background=a}},Uf=(e=>(e[e.NotSet=-1]=`NotSet`,e[e.None=0]=`None`,e[e.Italic=1]=`Italic`,e[e.Bold=2]=`Bold`,e[e.Underline=4]=`Underline`,e[e.Strikethrough=8]=`Strikethrough`,e))(Uf||{});function Wf(e,t){e.sort((e,t)=>{let n=jf(e.scope,t.scope);return n!==0||(n=Mf(e.parentScopes,t.parentScopes),n!==0)?n:e.index-t.index});let n=0,r=`#000000`,i=`#ffffff`;for(;e.length>=1&&e[0].scope===``;){let t=e.shift();t.fontStyle!==-1&&(n=t.fontStyle),t.foreground!==null&&(r=t.foreground),t.background!==null&&(i=t.background)}let a=new Gf(t),o=new Bf(n,a.getId(r),a.getId(i)),s=new Jf(new qf(0,null,-1,0,0),[]);for(let t=0,n=e.length;t<n;t++){let n=e[t];s.insert(0,n.scope,n.parentScopes,n.fontStyle,a.getId(n.foreground),a.getId(n.background))}return new If(a,o,s)}var Gf=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(e){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(e)){this._isFrozen=!0;for(let t=0,n=e.length;t<n;t++)this._color2id[e[t]]=t,this._id2color[t]=e[t]}else this._isFrozen=!1}getId(e){if(e===null)return 0;e=e.toUpperCase();let t=this._color2id[e];if(t)return t;if(this._isFrozen)throw Error(`Missing color in color map - ${e}`);return t=++this._lastColorId,this._color2id[e]=t,this._id2color[t]=e,t}getColorMap(){return this._id2color.slice(0)}},Kf=Object.freeze([]),qf=class e{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(e,t,n,r,i){this.scopeDepth=e,this.parentScopes=t||Kf,this.fontStyle=n,this.foreground=r,this.background=i}clone(){return new e(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(e){let t=[];for(let n=0,r=e.length;n<r;n++)t[n]=e[n].clone();return t}acceptOverwrite(e,t,n,r){this.scopeDepth>e?console.log(`how did this happen?`):this.scopeDepth=e,t!==-1&&(this.fontStyle=t),n!==0&&(this.foreground=n),r!==0&&(this.background=r)}},Jf=class e{constructor(e,t=[],n={}){this._mainRule=e,this._children=n,this._rulesWithParentScopes=t}_rulesWithParentScopes;static _cmpBySpecificity(e,t){if(e.scopeDepth!==t.scopeDepth)return t.scopeDepth-e.scopeDepth;let n=0,r=0;for(;e.parentScopes[n]===`>`&&n++,t.parentScopes[r]===`>`&&r++,!(n>=e.parentScopes.length||r>=t.parentScopes.length);){let i=t.parentScopes[r].length-e.parentScopes[n].length;if(i!==0)return i;n++,r++}return t.parentScopes.length-e.parentScopes.length}match(t){if(t!==``){let e=t.indexOf(`.`),n,r;if(e===-1?(n=t,r=``):(n=t.substring(0,e),r=t.substring(e+1)),this._children.hasOwnProperty(n))return this._children[n].match(r)}let n=this._rulesWithParentScopes.concat(this._mainRule);return n.sort(e._cmpBySpecificity),n}insert(t,n,r,i,a,o){if(n===``){this._doInsertHere(t,r,i,a,o);return}let s=n.indexOf(`.`),c,l;s===-1?(c=n,l=``):(c=n.substring(0,s),l=n.substring(s+1));let u;this._children.hasOwnProperty(c)?u=this._children[c]:(u=new e(this._mainRule.clone(),qf.cloneArr(this._rulesWithParentScopes)),this._children[c]=u),u.insert(t+1,l,r,i,a,o)}_doInsertHere(e,t,n,r,i){if(t===null)this._mainRule.acceptOverwrite(e,n,r,i);else{for(let a=0,o=this._rulesWithParentScopes.length;a<o;a++){let o=this._rulesWithParentScopes[a];if(Mf(o.parentScopes,t)===0){o.acceptOverwrite(e,n,r,i);return}}n===-1&&(n=this._mainRule.fontStyle),r===0&&(r=this._mainRule.foreground),i===0&&(i=this._mainRule.background),this._rulesWithParentScopes.push(new qf(e,t,n,r,i))}}},Yf=class e{static toBinaryStr(e){return e.toString(2).padStart(32,`0`)}static print(t){let n=e.getLanguageId(t),r=e.getTokenType(t),i=e.getFontStyle(t),a=e.getForeground(t),o=e.getBackground(t);console.log({languageId:n,tokenType:r,fontStyle:i,foreground:a,background:o})}static getLanguageId(e){return(e&255)>>>0}static getTokenType(e){return(e&768)>>>8}static containsBalancedBrackets(e){return!!(e&1024)}static getFontStyle(e){return(e&30720)>>>11}static getForeground(e){return(e&16744448)>>>15}static getBackground(e){return(e&4278190080)>>>24}static set(t,n,r,i,a,o,s){let c=e.getLanguageId(t),l=e.getTokenType(t),u=+!!e.containsBalancedBrackets(t),d=e.getFontStyle(t),f=e.getForeground(t),p=e.getBackground(t);return n!==0&&(c=n),r!==8&&(l=Zf(r)),i!==null&&(u=+!!i),a!==-1&&(d=a),o!==0&&(f=o),s!==0&&(p=s),(c|0|l<<8|u<<10|d<<11|f<<15|p<<24)>>>0}};function Xf(e){return e}function Zf(e){return e}function Qf(e,t){let n=[],r=ep(e),i=r.next();for(;i!==null;){let e=0;if(i.length===2&&i.charAt(1)===`:`){switch(i.charAt(0)){case`R`:e=1;break;case`L`:e=-1;break;default:console.log(`Unknown priority ${i} in scope selector`)}i=r.next()}let t=o();if(n.push({matcher:t,priority:e}),i!==`,`)break;i=r.next()}return n;function a(){if(i===`-`){i=r.next();let e=a();return t=>!!e&&!e(t)}if(i===`(`){i=r.next();let e=s();return i===`)`&&(i=r.next()),e}if($f(i)){let e=[];do e.push(i),i=r.next();while($f(i));return n=>t(e,n)}return null}function o(){let e=[],t=a();for(;t;)e.push(t),t=a();return t=>e.every(e=>e(t))}function s(){let e=[],t=o();for(;t&&(e.push(t),i===`|`||i===`,`);){do i=r.next();while(i===`|`||i===`,`);t=o()}return t=>e.some(e=>e(t))}}function $f(e){return!!e&&!!e.match(/[\w\.:]+/)}function ep(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;let r=n[0];return n=t.exec(e),r}}}function tp(e){typeof e.dispose==`function`&&e.dispose()}var np=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},rp=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},ip=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},ap=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new np(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new ip;for(let n of e)op(n,this.initialScopeName,this.repo,t);for(let e of t.references)if(e instanceof np){if(this.seenFullScopeRequests.has(e.scopeName))continue;this.seenFullScopeRequests.add(e.scopeName),this.Q.push(e)}else{if(this.seenFullScopeRequests.has(e.scopeName)||this.seenPartialScopeRequests.has(e.toKey()))continue;this.seenPartialScopeRequests.add(e.toKey()),this.Q.push(e)}}};function op(e,t,n,r){let i=n.lookup(e.scopeName);if(!i){if(e.scopeName===t)throw Error(`No grammar provided for <${t}>`);return}let a=n.lookup(t);e instanceof np?cp({baseGrammar:a,selfGrammar:i},r):sp(e.ruleName,{baseGrammar:a,selfGrammar:i,repository:i.repository},r);let o=n.injections(e.scopeName);if(o)for(let e of o)r.add(new np(e))}function sp(e,t,n){if(t.repository&&t.repository[e]){let r=t.repository[e];lp([r],t,n)}}function cp(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&lp(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&lp(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function lp(e,t,n){for(let r of e){if(n.visitedRule.has(r))continue;n.visitedRule.add(r);let e=r.repository?Df({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&lp(r.patterns,{...t,repository:e},n);let i=r.include;if(!i)continue;let a=hp(i);switch(a.kind){case 0:cp({...t,selfGrammar:t.baseGrammar},n);break;case 1:cp(t,n);break;case 2:sp(a.ruleName,{...t,repository:e},n);break;case 3:case 4:let r=a.scopeName===t.selfGrammar.scopeName?t.selfGrammar:a.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(r){let i={baseGrammar:t.baseGrammar,selfGrammar:r,repository:e};a.kind===4?sp(a.ruleName,i,n):cp(i,n)}else a.kind===4?n.add(new rp(a.scopeName,a.ruleName)):n.add(new np(a.scopeName))}}}var up=class{kind=0},dp=class{kind=1},fp=class{constructor(e){this.ruleName=e}kind=2},pp=class{constructor(e){this.scopeName=e}kind=3},mp=class{constructor(e,t){this.scopeName=e,this.ruleName=t}kind=4};function hp(e){if(e===`$base`)return new up;if(e===`$self`)return new dp;let t=e.indexOf(`#`);return t===-1?new pp(e):t===0?new fp(e.substring(1)):new mp(e.substring(0,t),e.substring(t+1))}var gp=/\\(\d+)/,_p=/\\(\d+)/g,vp=-1,yp=-2;function bp(e){return e}function xp(e){return e}var Sp=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=Af.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=Af.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${Of(this.$location.filename)}:${this.$location.line}`:`unknown`;return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:Af.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:Af.replaceCaptures(this._contentName,e,t)}},Cp=class extends Sp{retokenizeCapturedWithRuleId;constructor(e,t,n,r,i){super(e,t,n,r),this.retokenizeCapturedWithRuleId=i}dispose(){}collectPatterns(e,t){throw Error(`Not supported!`)}compile(e,t){throw Error(`Not supported!`)}compileAG(e,t,n,r){throw Error(`Not supported!`)}},wp=class extends Sp{_match;captures;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,null),this._match=new kp(r,this.id),this.captures=i,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Ap,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Tp=class extends Sp{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i){super(e,t,n,r),this.patterns=i.patterns,this.hasMissingPatterns=i.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}collectPatterns(e,t){for(let n of this.patterns)e.getRule(n).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Ap,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Ep=class extends Sp{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,i,a,o,s,c,l){super(e,t,n,r),this._begin=new kp(i,this.id),this.beginCaptures=a,this._end=new kp(o||`￿`,-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=s,this.applyEndPatternLast=c||!1,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,n,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Ap;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},Dp=class extends Sp{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r),this._begin=new kp(i,this.id),this.beginCaptures=a,this.whileCaptures=s,this._while=new kp(o,yp),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&=(this._cachedCompiledPatterns.dispose(),null),this._cachedCompiledWhilePatterns&&=(this._cachedCompiledWhilePatterns.dispose(),null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Ap;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,n,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,n,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new Ap,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||`￿`),this._cachedCompiledWhilePatterns}},Op=class e{static createCaptureRule(e,t,n,r,i){return e.registerRule(e=>new Cp(t,e,n,r,i))}static getCompiledRuleId(t,n,r){return t.id||n.registerRule(i=>{if(t.id=i,t.match)return new wp(t.$vscodeTextmateLocation,t.id,t.name,t.match,e._compileCaptures(t.captures,n,r));if(t.begin===void 0){t.repository&&(r=Df({},r,t.repository));let i=t.patterns;return i===void 0&&t.include&&(i=[{include:t.include}]),new Tp(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,e._compilePatterns(i,n,r))}return t.while?new Dp(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.while,e._compileCaptures(t.whileCaptures||t.captures,n,r),e._compilePatterns(t.patterns,n,r)):new Ep(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,e._compileCaptures(t.beginCaptures||t.captures,n,r),t.end,e._compileCaptures(t.endCaptures||t.captures,n,r),t.applyEndPatternLast,e._compilePatterns(t.patterns,n,r))}),t.id}static _compileCaptures(t,n,r){let i=[];if(t){let a=0;for(let e in t){if(e===`$vscodeTextmateLocation`)continue;let t=parseInt(e,10);t>a&&(a=t)}for(let e=0;e<=a;e++)i[e]=null;for(let a in t){if(a===`$vscodeTextmateLocation`)continue;let o=parseInt(a,10),s=0;t[a].patterns&&(s=e.getCompiledRuleId(t[a],n,r)),i[o]=e.createCaptureRule(n,t[a].$vscodeTextmateLocation,t[a].name,t[a].contentName,s)}}return i}static _compilePatterns(t,n,r){let i=[];if(t)for(let a=0,o=t.length;a<o;a++){let o=t[a],s=-1;if(o.include){let t=hp(o.include);switch(t.kind){case 0:case 1:s=e.getCompiledRuleId(r[o.include],n,r);break;case 2:let i=r[t.ruleName];i&&(s=e.getCompiledRuleId(i,n,r));break;case 3:case 4:let a=t.scopeName,c=t.kind===4?t.ruleName:null,l=n.getExternalGrammar(a,r);if(l){if(c){let t=l.repository[c];t&&(s=e.getCompiledRuleId(t,n,l.repository))}else s=e.getCompiledRuleId(l.repository.$self,n,l.repository)}}}else s=e.getCompiledRuleId(o,n,r);if(s!==-1){let e=n.getRule(s),t=!1;if((e instanceof Tp||e instanceof Ep||e instanceof Dp)&&e.hasMissingPatterns&&e.patterns.length===0&&(t=!0),t)continue;i.push(s)}}return{patterns:i,hasMissingPatterns:(t?t.length:0)!==i.length}}},kp=class e{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(e,t){if(e&&typeof e==`string`){let t=e.length,n=0,r=[],i=!1;for(let a=0;a<t;a++)if(e.charAt(a)===`\\`&&a+1<t){let t=e.charAt(a+1);t===`z`?(r.push(e.substring(n,a)),r.push(`$(?!\\n)(?<!\\n)`),n=a+2):(t===`A`||t===`G`)&&(i=!0),a++}this.hasAnchor=i,n===0?this.source=e:(r.push(e.substring(n,t)),this.source=r.join(``))}else this.hasAnchor=!1,this.source=e;this._anchorCache=this.hasAnchor?this._buildAnchorCache():null,this.ruleId=t,this.hasBackReferences=typeof this.source==`string`&&gp.test(this.source)}clone(){return new e(this.source,this.ruleId)}setSource(e){this.source!==e&&(this.source=e,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(e,t){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let n=t.map(t=>e.substring(t.start,t.end));return _p.lastIndex=0,this.source.replace(_p,(e,t)=>Pf(n[parseInt(t,10)]||``))}_buildAnchorCache(){if(typeof this.source!=`string`)throw Error(`This method should only be called if the source is a string`);let e=[],t=[],n=[],r=[],i,a,o,s;for(i=0,a=this.source.length;i<a;i++)o=this.source.charAt(i),e[i]=o,t[i]=o,n[i]=o,r[i]=o,o===`\\`&&i+1<a&&(s=this.source.charAt(i+1),s===`A`?(e[i+1]=`￿`,t[i+1]=`￿`,n[i+1]=`A`,r[i+1]=`A`):s===`G`?(e[i+1]=`￿`,t[i+1]=`G`,n[i+1]=`￿`,r[i+1]=`G`):(e[i+1]=s,t[i+1]=s,n[i+1]=s,r[i+1]=s),i++);return{A0_G0:e.join(``),A0_G1:t.join(``),A1_G0:n.join(``),A1_G1:r.join(``)}}resolveAnchors(e,t){return!this.hasAnchor||!this._anchorCache||typeof this.source!=`string`?this.source:e?t?this._anchorCache.A1_G1:this._anchorCache.A1_G0:t?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},Ap=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&=(this._cached.dispose(),null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(e){this._items.push(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}unshift(e){this._items.unshift(e),this._hasAnchors=this._hasAnchors||e.hasAnchor}length(){return this._items.length}setSource(e,t){this._items[e].source!==t&&(this._disposeCaches(),this._items[e].setSource(t))}compile(e){if(!this._cached){let t=this._items.map(e=>e.source);this._cached=new jp(e,t,this._items.map(e=>e.ruleId))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){return new jp(e,this._items.map(e=>e.resolveAnchors(t,n)),this._items.map(e=>e.ruleId))}},jp=class{constructor(e,t,n){this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}scanner;dispose(){typeof this.scanner.dispose==`function`&&this.scanner.dispose()}toString(){let e=[];for(let t=0,n=this.rules.length;t<n;t++)e.push(` - `+this.rules[t]+`: `+this.regExps[t]);return e.join(`
@@ -175,16 +175,16 @@ XID_Start XIDS`.split(/\s/).map(e=>[_y(e),e])),ub=new Map([[`s`,Yy(383)],[Yy(383
175
175
  \v\f…\u2028\u2029])`),t));else if(c===`posix`){if(!i&&(u===`graph`||u===`print`)){if(r===`strict`)throw Error(`POSIX class "${u}" requires min target ES2024 or non-strict accuracy`);let e={graph:`!-~`,print:` -~`}[u];l&&(e=`\0-${Yy(e.codePointAt(0)-1)}${Yy(e.codePointAt(2)+1)}-\u{10FFFF}`),n(Vb(Rb(`[${e}]`),t))}else n(Vb(zb(Rb(pb.get(u)),l),t))}else if(c===`property`)lb.has(_y(u))||(e.key=`sc`);else if(c===`space`)n(Bb(ly(`space`,{negate:l}),t));else if(c===`word`)n(Vb(zb(Rb(sb),l),t));else throw Error(`Unexpected character set kind "${c}"`)}},Directive({node:e,parent:t,root:n,remove:r,replaceWith:i,removeAllPrevSiblings:a,removeAllNextSiblings:o}){let{kind:s,flags:c}=e;if(s===`flags`){if(!c.enable&&!c.disable)r();else{let e=ny({flags:c});e.body[0].body=o(),i(Vb(e,t),{traverse:!0})}}else if(s===`keep`){let e=n.body[0],r=n.body.length===1&&Nv(e,{type:`Group`})&&e.body[0].body.length===1?e.body[0]:n;if(t.parent!==r||r.body.length>1)throw Error($`Uses "\K" in a way that's unsupported`);let o=ry({behind:!0});o.body[0].body=a(),i(Vb(o,t))}else throw Error(`Unexpected directive kind "${s}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw Error(`Unsupported flag "P"`);if(e.textSegmentMode===`word`)throw Error(`Unsupported flag "y{w}"`);[`digitIsAscii`,`extended`,`posixIsAscii`,`spaceIsAscii`,`wordIsAscii`,`textSegmentMode`].forEach(t=>delete e[t]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:n}=e.flags;t?.extended&&delete t.extended,n?.extended&&delete n.extended,t?.dotAll&&n?.dotAll&&delete t.dotAll,t?.ignoreCase&&n?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){let{kind:n}=e;n===`lookbehind`&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){let{kind:r}=e;if(r===`fail`)n(Vb(ry({negate:!0}),t));else throw Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type===`Quantifier`){let t=ny();t.body[0].body.push(e.body),e.body=Vb(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){let n=[],r=!1,i=!1;for(let t of e.body)if(t.body.length===1&&t.body[0].kind===`search_start`)t.body.pop();else{let e=Mb(t.body);e?(r=!0,Array.isArray(e)?n.push(...e):n.push(e)):i=!0}r&&!i&&n.forEach(e=>t.add(e))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t===`strict`&&n&&r)throw Error($`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n==`string`&&!Lb(n)&&(n=Ob(n,t),e.ref=n)}},bb={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){let{orphan:r,ref:i}=e;r||n.set(e,[...t.get(i).map(({node:e})=>e)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:i,groupsByName:a,multiplexCapturesToLeftByRef:o,openRefs:s,reffedNodesByReferencer:c}){let l=i.get(e);if(l&&s.has(e.number)){let r=Bb(Eb(e.number),t);c.set(r,s.get(e.number)),n(r);return}s.set(e.number,e),o.set(e.number,[]),e.name&&$y(o,e.name,[]);let u=o.get(e.name??e.number);for(let t=0;t<u.length;t++){let n=u[t];if(l===n.node||l&&l===n.origin||e===n.origin){u.splice(t,1);break}}if(o.get(e.number).push({node:e,origin:l}),e.name&&o.get(e.name).push({node:e,origin:l}),e.name){let t=$y(a,e.name,new Map),n=!1;if(l)n=!0;else for(let e of t.values())if(!e.hasDuplicateNameToRemove){n=!0;break}a.get(e.name).set(e,{node:e,hasDuplicateNameToRemove:n})}},exit({node:e},{openRefs:t}){t.get(e.number)===e&&t.delete(e.number)}},Group:{enter({node:e},t){t.prevFlags=t.currentFlags,e.flags&&(t.currentFlags=Qy(t.currentFlags,e.flags))},exit(e,t){t.currentFlags=t.prevFlags}},Subroutine({node:e,parent:t,replaceWith:n},r){let{isRecursive:i,ref:a}=e;if(i){let n=t;for(;(n=n.parent)&&(n.type!==`CapturingGroup`||n.name!==a&&n.number!==a););r.reffedNodesByReferencer.set(e,n);return}let o=r.subroutineRefMap.get(a),s=a===0,c=s?Eb(0):Tb(o,r.groupOriginByCopy,null),l=c;if(!s){let e=kb(Db(o,e=>e.type===`Group`&&!!e.flags)),t=e?Qy(r.globalFlags,e):r.globalFlags;Cb(t,r.currentFlags)||(l=ny({flags:Ab(t)}),l.body[0].body.push(c))}n(Vb(l,t),{traverse:!s})}},xb={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}let i=r.reffedNodesByReferencer.get(e).filter(t=>wb(t,e));i.length?i.length>1?n(Vb(ny({atomic:!0,body:i.reverse().map(e=>Kv({body:[Jv(e.number)]}))}),t)):e.ref=i[0].number:n(Vb(ry({negate:!0}),t))},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){let n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let t=0;t<n;t++){let t=Yv();e.body.at(-1).body.push(t)}}},Subroutine({node:e},t){e.isRecursive&&e.ref!==0&&(e.ref=t.reffedNodesByReferencer.get(e).number)}};function Sb(e){by(e,{"*"({node:e,parent:t}){e.parent=t}})}function Cb(e,t){return e.dotAll===t.dotAll&&e.ignoreCase===t.ignoreCase}function wb(e,t){let n=t;do{if(n.type===`Regex`)return!1;if(n.type===`Alternative`)continue;if(n===e)return!1;let t=jb(n.parent);for(let r of t){if(r===n)break;if(r===e||Nb(r,e))return!0}}while(n=n.parent);throw Error(`Unexpected path`)}function Tb(e,t,n,r){let i=Array.isArray(e)?[]:{};for(let[a,o]of Object.entries(e))a===`parent`?i.parent=Array.isArray(n)?r:n:o&&typeof o==`object`?i[a]=Tb(o,t,i,n):(a===`type`&&o===`CapturingGroup`&&t.set(i,t.get(e)??e),i[a]=o);return i}function Eb(e){let t=cy(e);return t.isRecursive=!0,t}function Db(e,t){let n=[];for(;e=e.parent;)(!t||t(e))&&n.push(e);return n}function Ob(e,t){if(t.has(e))return t.get(e);let n=`$${t.size}_${e.replace(/^[^$_\p{IDS}]|[^$\u200C\u200D\p{IDC}]/gu,`_`)}`;return t.set(e,n),n}function kb(e){let t=[`dotAll`,`ignoreCase`],n={enable:{},disable:{}};return e.forEach(({flags:e})=>{t.forEach(t=>{e.enable?.[t]&&(delete n.disable[t],n.enable[t]=!0),e.disable?.[t]&&(n.disable[t]=!0)})}),Object.keys(n.enable).length||delete n.enable,Object.keys(n.disable).length||delete n.disable,n.enable||n.disable?n:null}function Ab({dotAll:e,ignoreCase:t}){let n={};return(e||t)&&(n.enable={},e&&(n.enable.dotAll=!0),t&&(n.enable.ignoreCase=!0)),(!e||!t)&&(n.disable={},!e&&(n.disable.dotAll=!0),!t&&(n.disable.ignoreCase=!0)),n}function jb(e){if(!e)throw Error(`Node expected`);let{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function Mb(e){let t=e.find(e=>e.kind===`search_start`||Ib(e,{negate:!1})||!Pb(e));if(!t)return null;if(t.kind===`search_start`)return t;if(t.type===`LookaroundAssertion`)return t.body[0].body[0];if(t.type===`CapturingGroup`||t.type===`Group`){let e=[];for(let n of t.body){let t=Mb(n.body);if(!t)return null;Array.isArray(t)?e.push(...t):e.push(t)}return e}return null}function Nb(e,t){let n=jb(e)??[];for(let e of n)if(e===t||Nb(e,t))return!0;return!1}function Pb({type:e}){return e===`Assertion`||e===`Directive`||e===`LookaroundAssertion`}function Fb(e){let t=[`Character`,`CharacterClass`,`CharacterSet`];return t.includes(e.type)||e.type===`Quantifier`&&e.min&&t.includes(e.body.type)}function Ib(e,t){let n={negate:null,...t};return e.type===`LookaroundAssertion`&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&Nv(e.body[0],{type:`Assertion`,kind:`search_start`})}function Lb(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function Rb(e,t){let n=Iv(e,{...t,unicodePropertyMap:lb}).body;return n.length>1||n[0].body.length>1?ny({body:n}):n[0].body[0]}function zb(e,t){return e.negate=t,e}function Bb(e,t){return e.parent=t,e}function Vb(e,t){return Sb(e),e.parent=t,e}function Hb(e,t){let n=ib(t),r=eb(n.target,`ES2024`),i=eb(n.target,`ES2025`),a=n.rules.recursionLimit;if(!Number.isInteger(a)||a<2||a>20)throw Error(`Invalid recursionLimit; use 2-20`);let o=null,s=null;if(!i){let t=[e.flags.ignoreCase];by(e,Ub,{getCurrentModI:()=>t.at(-1),popModI(){t.pop()},pushModI(e){t.push(e)},setHasCasedChar(){t.at(-1)?o=!0:s=!0}})}let c={dotAll:e.flags.dotAll,ignoreCase:!(!e.flags.ignoreCase&&!o||s)},l=e,u={accuracy:n.accuracy,appliedGlobalFlags:c,captureMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},inCharClass:!1,lastNode:l,originMap:e._originMap,recursionLimit:a,useAppliedIgnoreCase:!!(!i&&o&&s),useFlagMods:i,useFlagV:r,verbose:n.verbose};function d(e){return u.lastNode=l,l=e,tb(Wb[e.type],`Unexpected node type "${e.type}"`)(e,u,d)}let f={pattern:e.body.map(d).join(`|`),flags:d(e.flags),options:{...e.options}};return r||(delete f.options.force.v,f.options.disable.v=!0,f.options.unicodeSetsPlugin=null),f._captureTransfers=new Map,f._hiddenCaptures=[],u.captureMap.forEach((e,t)=>{e.hidden&&f._hiddenCaptures.push(t),e.transferTo&&$y(f._captureTransfers,e.transferTo,[]).push(t)}),f}var Ub={"*":{enter({node:e},t){if(nx(e)){let n=t.getCurrentModI();t.pushModI(e.flags?Qy({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){nx(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){Xb(Yy(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),Zb(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind===`property`&&_b.has(e.value)&&t.setHasCasedChar()}},Wb={Alternative({body:e},t,n){return e.map(n).join(``)},Assertion({kind:e,negate:t}){if(e===`string_end`)return`$`;if(e===`string_start`)return`^`;if(e===`word_boundary`)return t?$`\B`:$`\b`;throw Error(`Unexpected assertion kind "${e}"`)},Backreference({ref:e},t){if(typeof e!=`number`)throw Error(`Unexpected named backref in transformed AST`);if(!t.useFlagMods&&t.accuracy===`strict`&&t.currentFlags.ignoreCase&&!t.captureMap.get(e).ignoreCase)throw Error(`Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy`);return`\\`+e},CapturingGroup(e,t,n){let{body:r,name:i,number:a}=e,o={ignoreCase:t.currentFlags.ignoreCase},s=t.originMap.get(e);return s&&(o.hidden=!0,a>s.number&&(o.transferTo=s.number)),t.captureMap.set(a,o),`(${i?`?<${i}>`:``}${r.map(n).join(`|`)})`},Character({value:e},t){let n=Yy(e),r=Qb(e,{escDigit:t.lastNode.type===`Backreference`,inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&Xb(n)){let e=cb(n);return t.inCharClass?e.join(``):e.length>1?`[${e.join(``)}]`:e[0]}return n},CharacterClass(e,t,n){let{kind:r,negate:i,parent:a}=e,{body:o}=e;if(r===`intersection`&&!t.useFlagV)throw Error(`Use of character class intersection requires min target ES2024`);Xy.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&o.some(ix)&&(o=[Xv(45),...o.filter(e=>!ix(e))]);let s=()=>`[${i?`^`:``}${o.map(n).join(r===`intersection`?`&&`:``)}]`;if(!t.inCharClass){if((!t.useFlagV||Xy.bugNestedClassIgnoresNegation)&&!i){let t=o.filter(e=>e.type===`CharacterClass`&&e.kind===`union`&&e.negate);if(t.length){let r=ny(),i=r.body[0];return r.parent=a,i.parent=r,o=o.filter(e=>!t.includes(e)),e.body=o,o.length?(e.parent=i,i.body.push(e)):r.body.pop(),t.forEach(e=>{let t=Kv({body:[e]});e.parent=t,t.parent=r,r.body.push(t)}),n(r)}}t.inCharClass=!0;let r=s();return t.inCharClass=!1,r}let c=o[0];if(r===`union`&&!i&&c&&((!t.useFlagV||!t.verbose)&&a.kind===`union`&&!(Xy.bugFlagVLiteralHyphenIsRange&&t.useFlagV)||!t.verbose&&a.kind===`intersection`&&o.length===1&&c.type!==`CharacterClassRange`))return o.map(n).join(``);if(!t.useFlagV&&a.type===`CharacterClass`)throw Error(`Uses nested character class in a way that requires min target ES2024`);return s()},CharacterClassRange(e,t){let n=e.min.value,r=e.max.value,i={escDigit:!1,inCharClass:!0,useFlagV:t.useFlagV},a=Qb(n,i),o=Qb(r,i),s=new Set;return t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&$b(Zb(e)).forEach(e=>{s.add(Array.isArray(e)?`${Qb(e[0],i)}-${Qb(e[1],i)}`:Qb(e,i))}),`${a}-${o}${[...s].join(``)}`},CharacterSet({kind:e,negate:t,value:n,key:r},i){if(e===`dot`)return i.currentFlags.dotAll?i.appliedGlobalFlags.dotAll||i.useFlagMods?`.`:`[^]`:$`[^\n]`;if(e===`digit`)return t?$`\D`:$`\d`;if(e===`property`){if(i.useAppliedIgnoreCase&&i.currentFlags.ignoreCase&&_b.has(n))throw Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?$`\P`:$`\p`}{${r?`${r}=`:``}${n}}`}if(e===`word`)return t?$`\W`:$`\w`;throw Error(`Unexpected character set kind "${e}"`)},Flags(e,t){return(t.appliedGlobalFlags.ignoreCase?`i`:``)+(e.dotAll?`s`:``)+(e.sticky?`y`:``)},Group({atomic:e,body:t,flags:n,parent:r},i,a){let o=i.currentFlags;n&&(i.currentFlags=Qy(o,n));let s=t.map(a).join(`|`),c=!i.verbose&&t.length===1&&r.type!==`Quantifier`&&!e&&(!i.useFlagMods||!n)?s:`(?${ex(e,n,i.useFlagMods)}${s})`;return i.currentFlags=o,c},LookaroundAssertion({body:e,kind:t,negate:n},r,i){return`(?${`${t===`lookahead`?``:`<`}${n?`!`:`=`}`}${e.map(i).join(`|`)})`},Quantifier(e,t,n){return n(e.body)+tx(e)},Subroutine({isRecursive:e,ref:t},n){if(!e)throw Error(`Unexpected non-recursive subroutine in transformed AST`);let r=n.recursionLimit;return t===0?`(?R=${r})`:$`\g<${t}&R=${r}>`}},Gb=new Set([`$`,`(`,`)`,`*`,`+`,`.`,`?`,`[`,`\\`,`]`,`^`,`{`,`|`,`}`]),Kb=new Set([`-`,`\\`,`]`,`^`,`[`]),qb=new Set("()-/[\\]^{|}!#$%&*+,.:;<=>?@`~".split(``)),Jb=new Map([[9,$`\t`],[10,$`\n`],[11,$`\v`],[12,$`\f`],[13,$`\r`],[8232,$`\u2028`],[8233,$`\u2029`],[65279,$`\uFEFF`]]),Yb=/^\p{Cased}$/u;function Xb(e){return Yb.test(e)}function Zb(e,t){let n=!!t?.firstOnly,r=e.min.value,i=e.max.value,a=[];if(r<65&&(i===65535||i>=131071)||r===65536&&i>=131071)return a;for(let e=r;e<=i;e++){let t=Yy(e);if(!Xb(t))continue;let o=cb(t).filter(e=>{let t=e.codePointAt(0);return t<r||t>i});if(o.length&&(a.push(...o),n))break}return a}function Qb(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(Jb.has(e))return Jb.get(e);if(e<32||e>126&&e<160||e>262143||t&&rx(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,`0`)}`;let i=n?r?qb:Kb:Gb,a=Yy(e);return(i.has(a)?`\\`:``)+a}function $b(e){let t=e.map(e=>e.codePointAt(0)).sort((e,t)=>e-t),n=[],r=null;for(let e=0;e<t.length;e++)t[e+1]===t[e]+1?r??=t[e]:r===null?n.push(t[e]):(n.push([r,t[e]]),r=null);return n}function ex(e,t,n){if(e)return`>`;let r=``;if(t&&n){let{enable:e,disable:n}=t;r=(e?.ignoreCase?`i`:``)+(e?.dotAll?`s`:``)+(n?`-`:``)+(n?.ignoreCase?`i`:``)+(n?.dotAll?`s`:``)}return`${r}:`}function tx({kind:e,max:t,min:n}){let r;return r=!n&&t===1?`?`:!n&&t===1/0?`*`:n===1&&t===1/0?`+`:n===t?`{${n}}`:`{${n},${t===1/0?``:t}}`,r+{greedy:``,lazy:`?`,possessive:`+`}[e]}function nx({type:e}){return e===`CapturingGroup`||e===`Group`||e===`LookaroundAssertion`}function rx(e){return e>47&&e<58}function ix({type:e,value:t}){return e===`Character`&&t===45}var ax=class e extends RegExp{#e=new Map;#t=null;#n;#r=null;#i=null;rawOptions={};get source(){return this.#n||`(?:)`}constructor(t,n,r){let i=!!r?.lazyCompile;if(t instanceof RegExp){if(r)throw Error(`Cannot provide options when copying a regexp`);let i=t;super(i,n),this.#n=i.source,i instanceof e&&(this.#e=i.#e,this.#r=i.#r,this.#i=i.#i,this.rawOptions=i.rawOptions)}else{let e={hiddenCaptures:[],strategy:null,transfers:[],...r};super(i?``:t,n),this.#n=t,this.#e=sx(e.hiddenCaptures,e.transfers),this.#i=e.strategy,this.rawOptions=r??{}}i||(this.#t=this)}exec(t){if(!this.#t){let{lazyCompile:t,...n}=this.rawOptions;this.#t=new e(this.#n,this.flags,n)}let n=this.global||this.sticky,r=this.lastIndex;if(this.#i===`clip_search`&&n&&r){this.lastIndex=0;let e=this.#a(t.slice(r));return e&&(ox(e,r,t,this.hasIndices),this.lastIndex+=r),e}return this.#a(t)}#a(e){this.#t.lastIndex=this.lastIndex;let t=super.exec.call(this.#t,e);if(this.lastIndex=this.#t.lastIndex,!t||!this.#e.size)return t;let n=[...t];t.length=1;let r;this.hasIndices&&(r=[...t.indices],t.indices.length=1);let i=[0];for(let e=1;e<n.length;e++){let{hidden:a,transferTo:o}=this.#e.get(e)??{};if(a?i.push(null):(i.push(t.length),t.push(n[e]),this.hasIndices&&t.indices.push(r[e])),o&&n[e]!==void 0){let a=i[o];if(!a)throw Error(`Invalid capture transfer to "${a}"`);if(t[a]=n[e],this.hasIndices&&(t.indices[a]=r[e]),t.groups){this.#r||=cx(this.source);let i=this.#r.get(o);i&&(t.groups[i]=n[e],this.hasIndices&&(t.indices.groups[i]=r[e]))}}}return t}};function ox(e,t,n,r){if(e.index+=t,e.input=n,r){let n=e.indices;for(let e=0;e<n.length;e++){let r=n[e];r&&(n[e]=[r[0]+t,r[1]+t])}let r=n.groups;r&&Object.keys(r).forEach(e=>{let n=r[e];n&&(r[e]=[n[0]+t,n[1]+t])})}}function sx(e,t){let n=new Map;for(let t of e)n.set(t,{hidden:!0});for(let[e,r]of t)for(let t of r)$y(n,t,{}).transferTo=e;return n}function cx(e){let t=/(?<capture>\((?:\?<(?![=!])(?<name>[^>]+)>|(?!\?)))|\\?./gsu,n=new Map,r=0,i=0,a;for(;a=t.exec(e);){let{0:e,groups:{capture:t,name:o}}=a;e===`[`?r++:r?e===`]`&&r--:t&&(i++,o&&n.set(i,o))}return n}function lx(e,t){let n=ux(e,t);return n.options?new ax(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function ux(e,t){let n=ib(t),r=vb(Iv(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:lb}),{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),i=Hb(r,n),a=Uy(i.pattern,{captureTransfers:i._captureTransfers,hiddenCaptures:i._hiddenCaptures,mode:`external`}),o=Ny(Iy(a.pattern).pattern,{captureTransfers:a.captureTransfers,hiddenCaptures:a.hiddenCaptures}),s={pattern:o.pattern,flags:`${n.hasIndices?`d`:``}${n.global?`g`:``}${i.flags}${i.options.disable.v?`u`:`v`}`};if(n.avoidSubclass){if(n.lazyCompileLength!==1/0)throw Error(`Lazy compilation requires subclass`)}else{let e=o.hiddenCaptures.sort((e,t)=>e-t),t=Array.from(o.captureTransfers),i=r._strategy,a=s.pattern.length>=n.lazyCompileLength;(e.length||t.length||i||a)&&(s.options={...e.length&&{hiddenCaptures:e},...t.length&&{transfers:t},...i&&{strategy:i},...a&&{lazyCompile:a}})}return s}function dx(e,t){return lx(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function fx(e={}){let t={target:`auto`,cache:new Map,...e};return t.regexConstructor||=e=>dx(e,{target:t.target}),{createScanner(e){return new B_(e,t)},createString:H_}}var px=t({highlightChunks:()=>wx,highlightLangChunks:()=>Tx,langForPath:()=>Cx}),mx={light:`github-light`,dark:`github-dark`},hx=400,gx={ts:`typescript`,mts:`typescript`,cts:`typescript`,js:`javascript`,mjs:`javascript`,cjs:`javascript`,jsx:`jsx`,tsx:`tsx`,json:`json`,jsonc:`jsonc`,json5:`json5`,map:`json`,md:`markdown`,mdx:`mdx`,markdown:`markdown`,css:`css`,pcss:`css`,postcss:`css`,sass:`sass`,scss:`scss`,less:`less`,styl:`stylus`,html:`html`,htm:`html`,vue:`vue`,svelte:`svelte`,astro:`astro`,py:`python`,pyi:`python`,rb:`ruby`,rake:`ruby`,rs:`rust`,go:`go`,java:`java`,kt:`kotlin`,kts:`kotlin`,c:`c`,h:`c`,cpp:`cpp`,cc:`cpp`,cxx:`cpp`,hpp:`cpp`,hh:`cpp`,cs:`csharp`,fs:`fsharp`,swift:`swift`,m:`objective-c`,php:`php`,scala:`scala`,groovy:`groovy`,dart:`dart`,sh:`shellscript`,bash:`shellscript`,zsh:`shellscript`,fish:`fish`,ps1:`powershell`,bat:`bat`,cmd:`bat`,yml:`yaml`,yaml:`yaml`,toml:`toml`,xml:`xml`,svg:`xml`,sql:`sql`,graphql:`graphql`,gql:`graphql`,prisma:`prisma`,lua:`lua`,pl:`perl`,pm:`perl`,r:`r`,jl:`julia`,ex:`elixir`,exs:`elixir`,erl:`erlang`,hs:`haskell`,clj:`clojure`,cljs:`clojure`,edn:`clojure`,vim:`vim`,zig:`zig`,nim:`nim`,sol:`solidity`,tf:`terraform`,tfvars:`terraform`,hcl:`hcl`,diff:`diff`,patch:`diff`,lock:`yaml`},_x={dockerfile:`dockerfile`,makefile:`makefile`,".gitignore":`ini`,".gitattributes":`ini`,".editorconfig":`ini`,".npmrc":`ini`,".nvmrc":`ini`,".env":`ini`,justfile:`justfile`,"cmakelists.txt":`cmake`},vx={astro:()=>J(()=>import(`./astro-BZ97kZFP.js`),__vite__mapDeps([0,1,2,3,4,5,6])),bat:()=>J(()=>import(`./bat-qdxAdBWQ.js`),[]),c:()=>J(()=>import(`./c-Cz4nF6n_.js`),__vite__mapDeps([7,8])),clojure:()=>J(()=>import(`./clojure-DqKBuwfJ.js`),[]),cmake:()=>J(()=>import(`./cmake-Bj61d0ZC.js`),[]),cpp:()=>J(()=>import(`./cpp-B6pWdJV2.js`),__vite__mapDeps([9,10,11,8])),csharp:()=>J(()=>import(`./csharp-dmMxLVLW.js`),[]),css:()=>J(()=>import(`./css-DgaLhXQH.js`),__vite__mapDeps([12,4])),dart:()=>J(()=>import(`./dart-CHZY9Xhz.js`),[]),diff:()=>J(()=>import(`./diff-woXpYk--.js`),[]),dockerfile:()=>J(()=>import(`./dockerfile-IyjqRm3v.js`),[]),elixir:()=>J(()=>import(`./elixir-raGDl1oO.js`),__vite__mapDeps([13,14,2,4])),erlang:()=>J(()=>import(`./erlang-D0CaQ5Pl.js`),__vite__mapDeps([15,16])),fish:()=>J(()=>import(`./fish-BJitypiv.js`),[]),fsharp:()=>J(()=>import(`./fsharp-PZeu-6rm.js`),__vite__mapDeps([17,16])),graphql:()=>J(()=>import(`./graphql-BZEhxNwM.js`),__vite__mapDeps([18,19,2,3,6,20])),groovy:()=>J(()=>import(`./groovy-CacY0gHj.js`),[]),hcl:()=>J(()=>import(`./hcl-Dh228itO.js`),[]),haskell:()=>J(()=>import(`./haskell-D8IpX4py.js`),[]),html:()=>J(()=>import(`./html-BCy9P6D2.js`),__vite__mapDeps([21,14,2,4])),ini:()=>J(()=>import(`./ini-B5eOa1yu.js`),[]),java:()=>J(()=>import(`./java-_ATy9zCa.js`),__vite__mapDeps([22,23])),javascript:()=>J(()=>import(`./javascript-CpIGwZ_Y.js`),__vite__mapDeps([24,2])),json:()=>J(()=>import(`./json-C3WlssX3.js`),__vite__mapDeps([25,1])),json5:()=>J(()=>import(`./json5-BR5RXkoi.js`),[]),jsonc:()=>J(()=>import(`./jsonc-CYpm1nAK.js`),[]),jsx:()=>J(()=>import(`./jsx-C4yDKi0A.js`),__vite__mapDeps([26,20])),julia:()=>J(()=>import(`./julia-DCfl8sf8.js`),__vite__mapDeps([27,2,10,11,8,28,29,30])),justfile:()=>J(()=>import(`./justfile-CKP9W7x6.js`),__vite__mapDeps([31,2,3,28,32,33,4,14,30,34,23,35,8,10,11,19,6,20,36,37])),kotlin:()=>J(()=>import(`./kotlin-DhhofPvG.js`),[]),less:()=>J(()=>import(`./less-DVTAwKKz.js`),[]),lua:()=>J(()=>import(`./lua-fPRBWD-V.js`),__vite__mapDeps([38,36,8])),makefile:()=>J(()=>import(`./makefile-Dixweg8N.js`),[]),markdown:()=>J(()=>import(`./markdown-CjQmuOi1.js`),__vite__mapDeps([39,16])),mdx:()=>J(()=>import(`./mdx-DQZ5AkYe.js`),[]),nim:()=>J(()=>import(`./nim-VAaFSKwL.js`),__vite__mapDeps([40,2,4,8,11,14,16,34,23])),"objective-c":()=>J(()=>import(`./objective-c-D1A_Heim.js`),[]),perl:()=>J(()=>import(`./perl-BTdIRyOQ.js`),__vite__mapDeps([41,33,2,4,14,30,34,23])),php:()=>J(()=>import(`./php-DPoYWQt_.js`),__vite__mapDeps([42,1,2,4,14,30,34,23])),postcss:()=>J(()=>import(`./postcss-DkKB82OS.js`),__vite__mapDeps([43,5])),powershell:()=>J(()=>import(`./powershell-QtSnmXcu.js`),[]),prisma:()=>J(()=>import(`./prisma-DMgNhnYS.js`),[]),python:()=>J(()=>import(`./python-C5TF47hQ.js`),__vite__mapDeps([44,28])),r:()=>J(()=>import(`./r-BXEss897.js`),__vite__mapDeps([45,29])),ruby:()=>J(()=>import(`./ruby-BdDtUACQ.js`),__vite__mapDeps([46,35,2,4,8,10,11,14,19,3,6,20,30,32,34,23,36,37])),rust:()=>J(()=>import(`./rust-DpiIf5JO.js`),[]),sass:()=>J(()=>import(`./sass-DXrisJhu.js`),[]),scala:()=>J(()=>import(`./scala-BiFt_7mu.js`),[]),scss:()=>J(()=>import(`./scss-8bKmll0B.js`),__vite__mapDeps([47,4])),shellscript:()=>J(()=>import(`./shellscript-CVTB3cr6.js`),__vite__mapDeps([48,32])),solidity:()=>J(()=>import(`./solidity-Bj7E1mRn.js`),[]),sql:()=>J(()=>import(`./sql-CfM2IJm3.js`),__vite__mapDeps([49,30])),svelte:()=>J(()=>import(`./svelte-CdeT-Ich.js`),__vite__mapDeps([50,2,3,4,5])),swift:()=>J(()=>import(`./swift-CyEgAFGc.js`),[]),terraform:()=>J(()=>import(`./terraform-DswuEJGm.js`),[]),toml:()=>J(()=>import(`./toml-CcmNWLt0.js`),[]),tsx:()=>J(()=>import(`./tsx-CGosfAUg.js`),__vite__mapDeps([51,6])),typescript:()=>J(()=>import(`./typescript-Bb1J8qyy.js`),__vite__mapDeps([52,3])),vim:()=>J(()=>import(`./viml-DvXPmvsu.js`),[]),vue:()=>J(()=>import(`./vue-BqdMUtqy.js`),__vite__mapDeps([53,1,2,3,4,14])),xml:()=>J(()=>import(`./xml-DuKfbPI6.js`),__vite__mapDeps([54,34,23])),yaml:()=>J(()=>import(`./yaml-DDA_XMNu.js`),__vite__mapDeps([55,37])),stylus:()=>J(()=>import(`./stylus-B6D30XZt.js`),[]),zig:()=>J(()=>import(`./zig-CMLA9XwU.js`),[])},yx=null;function bx(){return yx??=I_({themes:[J(()=>import(`./github-light-EUqPIrTm.js`),[]),J(()=>import(`./github-dark-C-LZuMrd.js`),[])],langs:[],engine:fx({forgiving:!0})}),yx}var xx=new Map;function Sx(e,t){let n=xx.get(t);if(!n){let r=vx[t];n=r?r().then(t=>e.loadLanguage(t)).then(()=>void 0):Promise.reject(Error(`no grammar loader for ${t}`)),n.catch(()=>xx.delete(t)),xx.set(t,n)}return n}function Cx(e){let t=(e.split(`/`).pop()??e).toLowerCase();return _x[t]?_x[t]:gx[t.includes(`.`)?t.slice(t.lastIndexOf(`.`)+1):``]??null}async function*wx(e,t){let n=Cx(e);n&&t.trim()&&vx[n]&&(yield*Tx(n,t))}async function*Tx(e,t){if(!e||!t.trim()||!vx[e])return;let n=await bx();await Sx(n,e);let r=t.split(`
176
176
  `),i;for(let t=0;t<r.length;t+=hx){let a=r.slice(t,t+hx).join(`
177
177
  `),o=n.codeToHast(a,{lang:e,themes:mx,defaultColor:!1,...i?{grammarState:i}:{}});i=n.getLastGrammarState(o)??void 0,yield P_(o)}}var Ex=/(?:^|\s)language-([\w+#.-]+)/,Dx=`hl`;function Ox(e){if(e)for(let t of e.querySelectorAll(`pre`)){if(t.dataset[Dx])continue;let e=t.querySelector(`code`);if(!e){t.dataset[Dx]=`skip`;continue}let n=Ex.exec(e.className)?.[1],r=n?Cx(`x.${n}`)??n:void 0,i=e.textContent??``;if(!r||!i.trim()){t.dataset[Dx]=`skip`;continue}let a=`${r}::${i.length}::${i}`;t.dataset[Dx]=`pending`;let o=jd(a);o===void 0?(async()=>{try{let{highlightLangChunks:e}=await J(async()=>{let{highlightLangChunks:e}=await Promise.resolve().then(()=>px);return{highlightLangChunks:e}},void 0),n=``;for await(let t of e(r,i))n+=t;if(!n){t.dataset[Dx]=`skip`;return}Md(a,n),t.isConnected&&kx(t,n)}catch{t.dataset[Dx]=`skip`}})():kx(t,o)}}function kx(e,t){let n=document.createElement(`div`);n.className=`shikiwrap`;let r=document.createElement(`div`);r.className=`shiki`,r.innerHTML=t,n.appendChild(r),e.replaceWith(n)}function Ax(e){let t=String(e??``).trim();if(!t)return null;if(t.startsWith(`[`)){let e=(()=>{try{return JSON.parse(t)}catch{try{return JSON.parse(t.replace(/'/g,`"`))}catch{return}}})();if(Array.isArray(e)&&e.length>=2)return`${String(e[0])}/${String(e[1])}`}for(let e of[`__`,`/`,`::`]){let n=t.lastIndexOf(e);if(!(n<=0))return`${t.slice(0,n).replace(/^mcp__/,``)}/${t.slice(n+e.length)}`}return t}var jx={prompt:{name:`you`,icon:`🟧`,color:`#faa81a`},user:{name:`you`,icon:`🟧`,color:`#faa81a`},message:{name:`agent`,icon:`🫖`,color:`#5865f2`},progress:{name:`progress`,icon:`📈`,color:`#3ba55d`},question:{name:`agent`,icon:`❓️`,color:`#5865f2`}},Mx={name:`harness`,icon:`📣`,color:`#3ba55d`},Nx={"#faa81a":`you`,"#5865f2":`agent`,"#3ba55d":`progress`,"#3ba0c9":`tool`},Px=e=>Nx[e]??`agent`,Fx=e=>{if(e.data?.actor)return{name:`@${String(e.data.actor)}`,icon:`🧩`,color:`#3ba0c9`};if(e.type===`tool_call`||e.type===`tool_result`){let t=String(e.data?.name??`tool`);if(t===`run_tool`){let t=Ax(e.data?.args?.tool_id);if(t)return{name:t,icon:`⚙️`,color:`#3ba0c9`}}let n=/^mcp__([^_]+(?:_[^_]+)*)__(.+)$/.exec(t);return n?{name:`${n[1]}/${n[2]}`,icon:`⚙️`,color:`#3ba0c9`}:{name:t,icon:`⚙️`,color:`#3ba0c9`}}if(e.type===`prompt`){let t=String(e.data?.source??`user`);return t===`user`?jx.prompt:t.startsWith(`scheduler:`)?{name:t.slice(10),icon:`📣`,color:`#3ba55d`}:Mx}return jx[e.type]??{name:e.type,icon:`•`,color:`#9298a5`}},Ix=e=>{let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`};function Lx(e){let t=e.data??{};return e.type===`prompt`?String(t.text??``):e.type===`message`?`${typeof t.reasoning==`string`&&t.reasoning.trim()?`<reasoning>\n${t.reasoning}\n</reasoning>\n\n`:``}${String(t.content??``)}`:(e.type,``)}function Rx(e){return e>=1e9?`${+(e/1e9).toFixed(1)}b`:e>=1e6?`${+(e/1e6).toFixed(1)}m`:e>=1e4?`${Math.round(e/1e3)}k`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function zx(e,t){return ft(e.replace(/\s+/g,` `).trim(),t)}function Bx(e){return e.type===`prompt`&&e.data?.source===`user`?`you`:e.type===`message`?`agent`:`harness`}function Vx(e){let t=e.data??{};if(e.data?.actor)return`sub:${String(e.data.actor)}`;if(e.type===`tool_call`||e.type===`tool_result`){let e=typeof t.name==`string`?t.name:``;return e===`load_skill`?`agent-skill`:`tool:${e}`}return e.type===`prompt`?`src:${String(t.source??`user`)}`:`type:${e.type}`}function Hx(e,t){return!(!e||t.data?.pending||e.data?.pending||t.data?.cancelled||Vx(e)!==Vx(t)||Bx(e)!==Bx(t)||t.session!==e.session||t.branch!==e.branch)}function Ux(e,t){let n=String(t??``);return/^TIMEOUT after\b/.test(n)?`timeout`:/^ABORTED\b/.test(n)?`aborted`:/^exit=\d+/.test(n)||e===!1?`exit`:n.trim()?`ok`:`empty`}function Wx(e){switch(e){case`timeout`:return` · TIMED OUT`;case`aborted`:return` · ABORTED`;case`exit`:return` · FAILED`;default:return``}}function Gx(e){let t=[];e.outcome!==`empty`&&t.push(e.fmtDur(e.durationMs)),e.timeoutMs&&t.push(`timeout ${Math.round(e.timeoutMs/1e3)}s`);let n=Wx(e.outcome).replace(/^\s*·\s*/,``);return n&&t.push(n),t.join(` · `)}function Kx(e){let t=e.trim();if(!t)return;let n=t[0];if(n===`{`||n===`[`||n===`"`)try{let e=JSON.parse(t);return typeof e==`object`&&e?`json`:void 0}catch{return}}function qx(e){if(Kx(e)!==`json`)return e;try{let t=JSON.parse(e.trim()),n=JSON.stringify(t,null,1);return e.trim().split(`
178
- `).length>1?e:n}catch{return e}}var Jx=12e4,Yx=6e5,Xx=e=>{let t=Number(e);return Math.min(Number.isFinite(t)&&t>0?t:Jx,Yx)},Zx=F(`<div class=qfree><input type=text><button>reply`),Qx=F(`<div class=meta>`),$x=F(`<div class=meta>waiting for output…`),eS=F(`<div class="meta bgjob-note">runs in background — poll with <b>bash_output(job_id=&quot;<!>&quot;)`),tS=F(`<b>action="kill"`),nS=F(`<div class=meta>writing…`),rS=F(`<pre class="mono toolbody del">`),iS=F(`<pre class="mono toolbody add">`),aS=F(`<div class=meta> · `),oS=F(`<div class=meta>applying…`),sS=F(`<pre class="mono toolbody patch">`),cS=F(`<div>`),lS=F(`<div class=meta>validating…`),uS=F(`<a target=_blank rel="noopener noreferrer"referrerpolicy=no-referrer>open ↗`),dS=F(`<span class=muted>`),fS=F(`<div class=content>`),pS=F(`<div class=meta>loading…`),mS=F(`<div class=meta>bundled: `),hS=F(`<div class=meta>saving…`),gS=F(`<div class=meta>found: `),_S=F(`<div class=meta>no matches`),vS=F(`<span class=actor>@`),yS=F(`<pre class="mono toolbody cmd">`),bS=F(`<details><summary><b></b><span class=meta></span><span class=toolcopy>`),xS=F(`<div class=divider-msg>⑂ forked from <!> → `),SS=F(`<div><div class=goalline-label>`),CS=F(`<div class="embed auditstep"><span class=meta>`),wS=F(`<span class="meta muted">`),TS=F(`<pre class="mono toolbody">`),ES=F(`<details class="embed auditstep"><summary><span class=meta>`),DS=F(`<div class=divider-msg>✅ tasks updated (<!>)`),OS=F(`<div> → `),kS=F(`<div class="embed fail"><div class=mono>🛑 runaway: <!> tool failures in a row (limit <!>)</div><div class=meta>last: <!> — `),AS=F(`<div class="embed warn-embed"title="a round-fatal API error occurred; auto-retry is waiting, then a fresh round starts (onError: retry)"><div class=mono>↻ API error — retrying (attempt <!>) in <!>s…`),jS=F(`<div class=divider-msg>🗜 compacted: <!> → <!> tok (<!>)`),MS=F(`<div class=divider-msg title="compaction is rewriting older history — the agent is not stuck">🗜 compacting: summarizing <!> earlier messages from <!> tok (<!>)…`),NS=F(`<span class=ts>`),PS=F(`<button class=editbtn title="withdraw this message — it has not reached the model yet; the text goes back to the input box">✕ cancel`),FS=F(`<button class=editbtn title="edit this prompt — forks the conversation here (later events are dropped or summarized)">✎ edit`),IS=F(`<div class=msg-head><span></span><span class=ts>`),LS=F(`<div><div></div><div class=msg-body>`),RS=F(`<span class=grouptime>`),zS=F(`<div class=promptimgs>`),BS=F(`<img class=promptimg alt="tool image"loading=lazy title="click to enlarge">`,!0,!1,!1),VS=F(`<img class=promptimg alt=attachment title="click to enlarge">`),HS=F(`<details class=reasoning><summary>💭 thinking</summary><div class=mono>`),US=F(`<div class=interrupted>⚠ interrupted — partial output kept`),WS=F(`<div class=msgfoot><span>copy summary`),GS=F(`<div class=meta>its call is no longer in the loaded events — the run itself finished`),KS=F(`<details><summary><span class=meta></span></summary><div class=mono></div><div class=meta>`),qS=F(`<div class="content muted">Rejected: `),JS=F(`<details class="embed decision"><summary><b>📌 <span class="content inline-md"></span></b><span class=meta>decision logged`),YS=F(`<div class="meta answerdone">✓ answered — continuing below`),XS=F(`<div class=qopts>`),ZS=F(`<div><div>❓️ <div class="content inline-md">`),QS=F(`<button class=qopt>`),$S=F(`<div class=progrow><b>goal</b><span>`),eC=F(`<div class=progrow><b>recent</b><span class="content inline-md">`),tC=F(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),nC=F(`<div class=progrow><b>next</b><span class="content inline-md">`),rC=F(`<div class="embed progembed"><div>📈 <div class="content inline-md">`),iC=F(`<div class="embed fail"><div class=mono>⚠ `),aC=F(`<div class="muted compactnote">the summary pass produced nothing, so the oldest messages were dropped instead — the session continues with the recent tail intact`),oC=F(`<div class="embed compaction"><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),sC=F(`<div class="vtitle compactkept">what the agent kept`),cC=F(`<details class="embed compaction"><summary><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),lC=F(`<div class="content muted">`);function uC(e){let[t,n]=y(``),r=()=>{let r=t().trim();r&&!e.answered&&(n(``),e.onOption?.(r))};return(()=>{var i=Zx(),a=i.firstChild,o=a.nextSibling;return a.$$keydown=e=>{e.key===`Enter`&&!e.isComposing&&(e.preventDefault(),r())},a.$$input=e=>n(e.currentTarget.value),o.$$click=r,b(n=>{var r=e.answered?`answered`:`or type your own answer…`,i=e.answered,s=e.answered||!t().trim();return r!==n.e&&I(a,`placeholder`,n.e=r),i!==n.t&&(a.disabled=n.t=i),s!==n.a&&(o.disabled=n.a=s),n},{e:void 0,t:void 0,a:void 0}),b(()=>a.value=t()),i})()}function dC(e){let t=e.e,n=Hx(e.prev,t),r=S(()=>e.res?.(),void 0,{equals:(e,t)=>e?.id===t?.id}),i=()=>r(),a=()=>!e.agentActive&&!i(),o=t.data??{},s=String(o.name??`tool`),c=()=>String(i()?.data?.result??``),l=e=>String(o.args?.[e]??``),u=()=>s===`bash`?l(`command`):l(`path`)||JSON.stringify(o.args??{},null,1),d=()=>s===`bash`?Xx(l(`timeout_ms`)):s===`wait_children`?Number(l(`timeout_ms`))||3e5:Number(l(`timeout_ms`))||void 0,f=(e,t,n)=>j(Jd,{text:e,lang:n}),p=e=>j(Jd,{get text(){return JSON.stringify(e??o.args??{},null,1)},lang:`json`}),m=()=>(()=>{let t=i();return t?[P(()=>P(()=>!!Od(c()))()?j(qd,{get text(){return c()}}):j(Jd,{get text(){return qx(c())},get lang(){return Kx(c())}})),(()=>{var e=Qx();return R(e,()=>dt(t.data?.durationMs),null),R(e,()=>s===`bash`?Wx(Ux(t.data?.ok,String(t.data?.result??``))):t.data?.ok===!1?` · FAILED`:``,null),R(e,j(yd,{get text(){return P(()=>!!Od(c()))()?Dd(c()):qx(c())}}),null),e})(),j(mC,{get data(){return t.data},get agentId(){return e.agentId}})]:$x()})(),h=S(()=>{i();let e=s,t=``,n=p(),r=(r,a,o)=>{let s=o??{},c=Object.keys(s);e=c.length?zx(JSON.stringify(s),120):`(no arguments)`,t=i()?dt(i().data?.durationMs):null,n=[P(()=>P(()=>!!c.length)()?p(s):null),P(m)]};try{switch(s){case`bash`:{let r=l(`command`),a=o.args?.background===!0,s=a?String(c()).match(/job (bg\d+)/)?.[1]??``:``;e=(a?`⏳ `:`$ `)+zx(r,96);let u=l(`timeout_ms`)?Number(l(`timeout_ms`)):void 0,d=i(),f=Ux(d?.data?.ok,d?String(d.data?.result??``):``);t=d?a?`background job${s?` ${s}`:``}${u?` · timeout ${Math.round(u/1e3)}s`:``}`:Gx({outcome:f,durationMs:d.data?.durationMs,timeoutMs:u,fmtDur:dt}):null,n=[a?(()=>{var e=eS(),t=e.firstChild.nextSibling,n=t.firstChild.nextSibling;return n.nextSibling,R(t,s||`?`,n),R(e,s?[` · kill with `,tS()]:null,null),e})():null,P(()=>P(()=>r!==e.slice(2))()?j(Jd,{text:r,lang:`shellscript`}):null),P(m)];break}case`read_file`:{let r=Array.isArray(o.args?.paths)?o.args.paths.map(String):[];e=l(`path`)||(r.length?r.length===1?r[0]:`${r[0]} +${r.length-1} more`:`(no path)`);let i=[];l(`pattern`)&&i.push(`grep /${zx(l(`pattern`),40)}/`),Number(o.args?.offset)<0?i.push(`last ${-Number(o.args.offset)} lines`):o.args?.offset&&i.push(`from L${o.args.offset}`),o.args?.limit&&i.push(`≤${o.args.limit} lines`),t=i.join(` · `),n=m();break}case`write_file`:{let r=String(o.args?.content??``);e=l(`path`)||`(no path)`,t=`${Rx(r.length)} bytes`,n=[P(()=>f(r)),P(()=>P(()=>!!i())()?(()=>{var e=Qx();return R(e,()=>zx(c(),160)),e})():nS())];break}case`edit_file`:e=l(`path`)||`(no path)`,t=o.args?.replace_all===!0?`replace all`:`unique spot`,n=[(()=>{var e=rS();return R(e,()=>`- `+l(`old_text`)),e})(),(()=>{var e=iS();return R(e,()=>`+ `+l(`new_text`)),e})(),P(()=>P(()=>!!i())()?(()=>{var e=aS(),t=e.firstChild;return R(e,()=>zx(c(),120),t),R(e,()=>dt(i().data?.durationMs),null),e})():oS())];break;case`apply_patch`:{let t=l(`patch`).split(`
178
+ `).length>1?e:n}catch{return e}}var Jx=12e4,Yx=6e5,Xx=e=>{let t=Number(e);return Math.min(Number.isFinite(t)&&t>0?t:Jx,Yx)},Zx=F(`<div class=qfree><input type=text><button>reply`),Qx=F(`<div class=meta>`),$x=F(`<div class=meta>waiting for output…`),eS=F(`<div class="meta bgjob-note">runs in background — poll with <b>bash_output(job_id=&quot;<!>&quot;)`),tS=F(`<b>action="kill"`),nS=F(`<div class=meta>writing…`),rS=F(`<pre class="mono toolbody del">`),iS=F(`<pre class="mono toolbody add">`),aS=F(`<div class=meta> · `),oS=F(`<div class=meta>applying…`),sS=F(`<pre class="mono toolbody patch">`),cS=F(`<div>`),lS=F(`<div class=meta>validating…`),uS=F(`<a target=_blank rel="noopener noreferrer"referrerpolicy=no-referrer>open ↗`),dS=F(`<span class=muted>`),fS=F(`<div class=content>`),pS=F(`<div class=meta>loading…`),mS=F(`<div class=meta>bundled: `),hS=F(`<div class=meta>saving…`),gS=F(`<div class=meta>found: `),_S=F(`<div class=meta>no matches`),vS=F(`<span class=toolcmd>`),yS=F(`<span class=actor>@`),bS=F(`<details><summary><b></b><span class=meta></span><span class=toolcopy>`),xS=F(`<div class=divider-msg>⑂ forked from <!> → `),SS=F(`<div><div class=goalline-label>`),CS=F(`<div class="embed auditstep"><span class=meta>`),wS=F(`<span class="meta muted">`),TS=F(`<pre class="mono toolbody">`),ES=F(`<details class="embed auditstep"><summary><span class=meta>`),DS=F(`<div class=divider-msg>✅ tasks updated (<!>)`),OS=F(`<div> → `),kS=F(`<div class="embed fail"><div class=mono>🛑 runaway: <!> tool failures in a row (limit <!>)</div><div class=meta>last: <!> — `),AS=F(`<div class="embed warn-embed"title="a round-fatal API error occurred; auto-retry is waiting, then a fresh round starts (onError: retry)"><div class=mono>↻ API error — retrying (attempt <!>) in <!>s…`),jS=F(`<div class=divider-msg>🗜 compacted: <!> → <!> tok (<!>)`),MS=F(`<div class=divider-msg title="compaction is rewriting older history — the agent is not stuck">🗜 compacting: summarizing <!> earlier messages from <!> tok (<!>)…`),NS=F(`<span class=ts>`),PS=F(`<button class=editbtn title="withdraw this message — it has not reached the model yet; the text goes back to the input box">✕ cancel`),FS=F(`<button class=editbtn title="edit this prompt — forks the conversation here (later events are dropped or summarized)">✎ edit`),IS=F(`<div class=msg-head><span></span><span class=ts>`),LS=F(`<div><div></div><div class=msg-body>`),RS=F(`<span class=grouptime>`),zS=F(`<div class=promptimgs>`),BS=F(`<img class=promptimg alt="tool image"loading=lazy title="click to enlarge">`,!0,!1,!1),VS=F(`<img class=promptimg alt=attachment title="click to enlarge">`),HS=F(`<details class=reasoning><summary>💭 thinking</summary><div class=mono>`),US=F(`<div class=interrupted>⚠ interrupted — partial output kept`),WS=F(`<div class=msgfoot><span>copy summary`),GS=F(`<div class=meta>its call is no longer in the loaded events — the run itself finished`),KS=F(`<details><summary><span class=meta></span></summary><div class=mono></div><div class=meta>`),qS=F(`<div class="content muted">Rejected: `),JS=F(`<details class="embed decision"><summary><b>📌 <span class="content inline-md"></span></b><span class=meta>decision logged`),YS=F(`<div class="meta answerdone">✓ answered — continuing below`),XS=F(`<div class=qopts>`),ZS=F(`<div><div>❓️ <div class="content inline-md">`),QS=F(`<button class=qopt>`),$S=F(`<div class=progrow><b>goal</b><span>`),eC=F(`<div class=progrow><b>recent</b><span class="content inline-md">`),tC=F(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),nC=F(`<div class=progrow><b>next</b><span class="content inline-md">`),rC=F(`<div class="embed progembed"><div>📈 <div class="content inline-md">`),iC=F(`<div class="embed fail"><div class=mono>⚠ `),aC=F(`<div class="muted compactnote">the summary pass produced nothing, so the oldest messages were dropped instead — the session continues with the recent tail intact`),oC=F(`<div class="embed compaction"><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),sC=F(`<div class="vtitle compactkept">what the agent kept`),cC=F(`<details class="embed compaction"><summary><b>🗜 context compacted</b><span class=meta> · <!> → <!> tok · `),lC=F(`<div class="content muted">`);function uC(e){let[t,n]=y(``),r=()=>{let r=t().trim();r&&!e.answered&&(n(``),e.onOption?.(r))};return(()=>{var i=Zx(),a=i.firstChild,o=a.nextSibling;return a.$$keydown=e=>{e.key===`Enter`&&!e.isComposing&&(e.preventDefault(),r())},a.$$input=e=>n(e.currentTarget.value),o.$$click=r,b(n=>{var r=e.answered?`answered`:`or type your own answer…`,i=e.answered,s=e.answered||!t().trim();return r!==n.e&&I(a,`placeholder`,n.e=r),i!==n.t&&(a.disabled=n.t=i),s!==n.a&&(o.disabled=n.a=s),n},{e:void 0,t:void 0,a:void 0}),b(()=>a.value=t()),i})()}function dC(e){let t=e.e,n=Hx(e.prev,t),r=S(()=>e.res?.(),void 0,{equals:(e,t)=>e?.id===t?.id}),i=()=>r(),a=()=>!e.agentActive&&!i(),o=t.data??{},s=String(o.name??`tool`),c=()=>String(i()?.data?.result??``),l=e=>String(o.args?.[e]??``),u=()=>s===`bash`?l(`command`):l(`path`)||JSON.stringify(o.args??{},null,1),d=()=>s===`bash`?Xx(l(`timeout_ms`)):s===`wait_children`?Number(l(`timeout_ms`))||3e5:Number(l(`timeout_ms`))||void 0,f=(e,t,n)=>j(Jd,{text:e,lang:n}),p=e=>j(Jd,{get text(){return JSON.stringify(e??o.args??{},null,1)},lang:`json`}),m=()=>(()=>{let t=i();return t?[P(()=>P(()=>!!Od(c()))()?j(qd,{get text(){return c()}}):j(Jd,{get text(){return qx(c())},get lang(){return Kx(c())}})),(()=>{var e=Qx();return R(e,()=>dt(t.data?.durationMs),null),R(e,()=>s===`bash`?Wx(Ux(t.data?.ok,String(t.data?.result??``))):t.data?.ok===!1?` · FAILED`:``,null),R(e,j(yd,{get text(){return P(()=>!!Od(c()))()?Dd(c()):qx(c())}}),null),e})(),j(mC,{get data(){return t.data},get agentId(){return e.agentId}})]:$x()})(),h=S(()=>{i();let e=s,t=``,n=p(),r=(r,a,o)=>{let s=o??{},c=Object.keys(s);e=c.length?zx(JSON.stringify(s),120):`(no arguments)`,t=i()?dt(i().data?.durationMs):null,n=[P(()=>P(()=>!!c.length)()?p(s):null),P(m)]};try{switch(s){case`bash`:{let r=l(`command`),a=o.args?.background===!0,s=a?String(c()).match(/job (bg\d+)/)?.[1]??``:``;e=a?`⏳`:`$`;let u=l(`timeout_ms`)?Number(l(`timeout_ms`)):void 0,d=i(),f=Ux(d?.data?.ok,d?String(d.data?.result??``):``);t=d?a?`background job${s?` ${s}`:``}${u?` · timeout ${Math.round(u/1e3)}s`:``}`:Gx({outcome:f,durationMs:d.data?.durationMs,timeoutMs:u,fmtDur:dt}):null,n=[a?(()=>{var e=eS(),t=e.firstChild.nextSibling,n=t.firstChild.nextSibling;return n.nextSibling,R(t,s||`?`,n),R(e,s?[` · kill with `,tS()]:null,null),e})():null,P(()=>P(()=>r!==e.slice(2))()?j(Jd,{text:r,lang:`shellscript`}):null),P(m)];break}case`read_file`:{let r=Array.isArray(o.args?.paths)?o.args.paths.map(String):[];e=l(`path`)||(r.length?r.length===1?r[0]:`${r[0]} +${r.length-1} more`:`(no path)`);let i=[];l(`pattern`)&&i.push(`grep /${zx(l(`pattern`),40)}/`),Number(o.args?.offset)<0?i.push(`last ${-Number(o.args.offset)} lines`):o.args?.offset&&i.push(`from L${o.args.offset}`),o.args?.limit&&i.push(`≤${o.args.limit} lines`),t=i.join(` · `),n=m();break}case`write_file`:{let r=String(o.args?.content??``);e=l(`path`)||`(no path)`,t=`${Rx(r.length)} bytes`,n=[P(()=>f(r)),P(()=>P(()=>!!i())()?(()=>{var e=Qx();return R(e,()=>zx(c(),160)),e})():nS())];break}case`edit_file`:e=l(`path`)||`(no path)`,t=o.args?.replace_all===!0?`replace all`:`unique spot`,n=[(()=>{var e=rS();return R(e,()=>`- `+l(`old_text`)),e})(),(()=>{var e=iS();return R(e,()=>`+ `+l(`new_text`)),e})(),P(()=>P(()=>!!i())()?(()=>{var e=aS(),t=e.firstChild;return R(e,()=>zx(c(),120),t),R(e,()=>dt(i().data?.durationMs),null),e})():oS())];break;case`apply_patch`:{let t=l(`patch`).split(`
179
179
  `).filter(e=>e&&!/^---$/.test(e.trim())),r=t.map(e=>e.match(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/)?.[1]).filter(Boolean);e=r.length?`${r.length} file${r.length>1?`s`:``}: ${zx(r.join(`, `),80)}`:`patch`,n=[(()=>{var e=sS();return R(e,()=>t.map(e=>{let t=e.startsWith(`+`)?` add`:e.startsWith(`-`)?` del`:/^\*\*\*|^@@/.test(e)?` meta`:``;return(()=>{var n=cS();return L(n,`pline`+t),R(n,e),n})()})),e})(),P(()=>P(()=>!!i())()?(()=>{var e=Qx();return R(e,()=>zx(c().split(`
180
- `)[0]??``,140),null),R(e,()=>i().data?.ok===!1?` · FAILED`:``,null),e})():lS())];break}case`list_dir`:e=l(`path`)||`.`,n=m();break;case`read_url`:{let r=l(`url`);try{let e=new URL(r);r=e.host+e.pathname}catch{}e=zx(r,70),t=`web`,n=[(()=>{var e=Qx();return R(e,j(N,{get when(){return/^https?:/i.test(l(`url`))},get fallback(){return(()=>{var e=dS();return R(e,()=>zx(l(`url`),80)),e})()},get children(){var e=uS();return b(()=>I(e,`href`,l(`url`))),e}})),e})(),P(m)];break}case`bash_output`:{let r=l(`action`)||`read`;e=`bash_output ${l(`job_id`)||`(?)`}`,t=r,n=m();break}case`load_skill`:{e=`skill: ${l(`name`)}`;let t=c().replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``);n=i()?[(()=>{var e=fS();return b(()=>e.innerHTML=Re(t)),e})(),(()=>{var e=Qx();return R(e,()=>dt(i().data?.durationMs)),e})()]:pS();break}case`save_skill`:{e=`skill: ${l(`name`)}`,t=zx(l(`description`),60);let r=Array.isArray(o.args?.files)?o.args.files.map(e=>e?.name).filter(Boolean):[];n=[P(()=>P(()=>!!r.length)()?(()=>{var e=mS();return e.firstChild,R(e,()=>r.join(`, `),null),e})():null),P(()=>P(()=>!!i())()?(()=>{var e=aS(),t=e.firstChild;return R(e,()=>zx(c(),160),t),R(e,()=>dt(i().data?.durationMs),null),e})():hS())];break}case`search_tools`:{e=`🔎 ${zx(l(`query`)||`(browse)`,60)}`;let r=(()=>{try{let e=JSON.parse(c());return{names:(e.tools??[]).map(e=>`${e.server??`?`}/${e.name??`?`}`),total:e.totalMatches??0}}catch{return{names:[],total:0}}})();t=i()?`${r.total} match${r.total===1?``:`es`}`:null,n=[P(p),P(()=>P(()=>!!i())()?P(()=>!!r.names.length)()?(()=>{var e=gS();return e.firstChild,R(e,()=>r.names.join(`, `),null),e})():_S():null),P(m)];break}case`run_tool`:{let a=Ax(l(`tool_id`)),s=a?.indexOf(`/`)??-1;a&&s>0?r(a.slice(0,s),a.slice(s+1),o.args?.arguments):(e=a||`(no tool_id)`,t=i()?dt(i().data?.durationMs):null,n=[P(p),P(m)]);break}default:{let a=/^mcp__([^_]+(?:_[^_]+)*)__(.+)$/.exec(s);if(a){r(a[1],a[2],o.args);break}e=s,t=i()?dt(i().data?.durationMs):null,n=[P(p),P(m)];break}}}catch{}return{label:e,hint:t,body:n,key:`${i()?.id??`none`}|${e}|${t??``}`}},void 0,{equals:(e,t)=>e.key===t.key});return(()=>{var r=bS(),o=r.firstChild,l=o.firstChild,f=l.nextSibling,p=f.nextSibling;return r.addEventListener(`toggle`,t=>{t.target.open&&e.onResize?.()}),R(l,()=>h().label),R(o,j(N,{get when(){return t.data?.actor},get children(){var e=vS();return e.firstChild,R(e,()=>String(t.data.actor),null),e}}),f),R(f,(()=>{var e=P(()=>!!i());return()=>e()?h().hint||``:P(()=>!!a())()?`(result missed)`:P(()=>!!(s===`bash`||d()))()?j(Gd,{get startedAt(){return t.ts},inline:!0,get timeoutMs(){return d()}}):`running…`})()),R(p,j(yd,{get text(){return u()},label:`⧉ cmd`,title:`copy the ${s} arguments`}),null),R(p,j(N,{get when(){return i()},get children(){return j(yd,{get text(){return P(()=>!!Od(c()))()?Dd(c()):c()},label:`⧉ out`,title:`copy this tool's full output (escapes removed)`})}}),null),R(r,j(N,{get when(){return s===`bash`&&String(t.data?.args?.command??``)!==``},get children(){var e=yS();return R(e,()=>`$ `+String(t.data?.args?.command??``)),e}}),null),R(r,()=>h().body,null),b(e=>{var t=`embed`+(n?` grouped`:``)+(i()?i().data?.ok===!1?` fail`:` done`:a()?` done`:` running`),o=`${s}${h().hint?` — `+h().hint:``}`;return t!==e.e&&L(r,e.e=t),o!==e.t&&I(r,`title`,e.t=o),e},{e:void 0,t:void 0}),r})()}function fC(e){let t;return x(()=>{e.html,queueMicrotask(()=>Ox(t))}),(()=>{var n=fS(),r=t;return typeof r==`function`?Ae(r,n):t=n,b(()=>n.innerHTML=e.html),n})()}function pC(e){let t=e.e,n=Fx(t),r=()=>Hx(e.prev?.(),t),i=()=>{let n=e.next?.();return!!n&&Hx(t,n)};if(t.type===`fork`){let e=t.data??{};return(()=>{var n=xS(),r=n.firstChild.nextSibling;return r.nextSibling,R(n,()=>String(e.fromBranch??`?`),r),R(n,()=>String(e.newBranch??t.branch),null),n})()}if(t.type===`goal`){let e=Jt(t.data??{});return(()=>{var t=SS(),n=t.firstChild;return R(n,()=>e.label),R(t,j(N,{get when(){return e.hasCard},get children(){return j($t,{get tone(){return P(()=>e.tone===`ok`)()?`ok`:e.tone===`warn`?`warn`:`tool`},get markdown(){return e.markdown},get body(){return e.detail}})}}),null),b(()=>L(t,`goalline `+(e.tone===`err`?`err`:e.tone===`warn`?`warn`:``))),t})()}if(t.type===`audit_step`){let e=String(t.data?.step??``),n=String(t.data?.name??``),r=e===`started`?`🔍️ auditor started`:e===`tool`?`🔍️ auditor → ${n}`:e===`tool_done`?`🔍️ auditor ← ${n} ${t.data?.ok===!1?`failed`:`${String(t.data?.chars??0)} chars`}`:e===`reply`?`🔍️ auditor replied`:`🔍️ auditor`;return e===`reply`&&t.data?.text||e===`tool`&&t.data?.args?(()=>{var n=ES(),i=n.firstChild,a=i.firstChild;return R(a,r),R(i,j(N,{get when(){return e===`tool`&&t.data?.args},get children(){var e=wS();return R(e,()=>ft(String(t.data?.args??``),120)),e}}),null),R(n,j(N,{get when(){return e===`reply`&&t.data?.text},get children(){var e=TS();return R(e,()=>String(t.data?.text??``)),e}}),null),R(n,j(N,{get when(){return e===`tool`&&t.data?.args},get children(){var e=TS();return R(e,()=>String(t.data?.args??``)),e}}),null),n})():(()=>{var e=CS(),t=e.firstChild;return R(t,r),e})()}if(t.type===`todo`)return(()=>{var e=DS(),n=e.firstChild.nextSibling;return n.nextSibling,R(e,()=>String(t.data?.by??`human`),n),e})();if(t.type===`state`)return t.data.from===t.data.to?null:(()=>{var e=OS(),n=e.firstChild;return R(e,()=>t.data.from,n),R(e,()=>t.data.to,null),R(e,(()=>{var e=P(()=>!!t.data.reason);return()=>e()?` — ${t.data.reason}`:``})(),null),b(()=>L(e,`divider-msg`+(t.data.to===`error`?` err`:``))),e})();if(t.type===`system_note`){let e=String(t.data?.event??``);if(e===`runaway-detected`)return(()=>{var e=kS(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;i.nextSibling;var a=n.nextSibling,o=a.firstChild.nextSibling;return o.nextSibling,R(n,()=>String(t.data?.failures),r),R(n,()=>String(t.data?.limit),i),R(a,()=>String(t.data?.lastTool),o),R(a,()=>String(t.data?.lastError??``).slice(0,200),null),b(()=>I(e,`title`,`${t.data?.failures} consecutive tool failures hit the configured limit (${t.data?.limit})`)),e})();if(e===`error-retry`)return(()=>{var e=AS(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(n,()=>String(t.data?.attempt),r),R(n,()=>Math.round(Number(t.data?.waitMs)/1e3),i),e})();if(e===`background-exit`){let e=t.data?.failed===!0,n=Math.round(Number(t.data?.durationMs??0)/1e3);return(()=>{var r=cS();return L(r,`divider-msg`+(e?` err`:``)),R(r,()=>(e?`⚠ background job `:`✓ background job `)+String(t.data?.jobId??`?`)+` `+(e?`FAILED (exit ${String(t.data?.code??`?`)})`:`finished (${n}s)`)),b(()=>I(r,`title`,String(t.data?.cmd??``))),r})()}return e===`context-compacted`?(()=>{var e=jS(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(e,()=>String(t.data?.tokensBefore??`?`),n),R(e,()=>String(t.data?.tokensAfter??`?`),r),R(e,()=>String(t.data?.mode??``),i),e})():e===`context-compaction-started`?(()=>{var e=MS(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(e,()=>String(t.data?.messages??`?`),n),R(e,()=>String(t.data?.tokensBefore??`?`),r),R(e,()=>String(t.data?.reason??`auto`),i),e})():null}return(()=>{var a=LS(),o=a.firstChild,s=o.nextSibling;return R(o,(()=>{var e=P(()=>!!r());return()=>e()?``:n.icon})()),R(s,(()=>{var e=P(()=>!!r());return()=>e()&&(()=>{var e=RS();return b(()=>I(e,`title`,`${Ix(t.ts)} · ${t.branch}`)),e})()})(),null),R(s,j(N,{get when(){return!r()},get children(){var r=IS(),i=r.firstChild,a=i.nextSibling;return R(i,()=>n.name),R(r,j(N,{get when(){return t.data?.actor},get children(){var e=vS();return e.firstChild,R(e,()=>String(t.data.actor),null),e}}),a),R(a,(()=>{var e=P(()=>!!t.data?.pending);return()=>e()?`queued…`:P(()=>!!t.data?.cancelled)()?`withdrawn`:Ix(t.ts)})()),R(r,j(N,{get when(){return e.showBranch},get children(){var e=NS();return R(e,()=>t.branch),e}}),null),R(r,j(N,{get when(){return e.onCancel},get children(){var t=PS();return t.$$click=t=>{t.stopPropagation(),e.onCancel()},t}}),null),R(r,j(N,{get when(){return t.type!==`tool_call`},get children(){return j(yd,{get text(){return Lx(t)},label:`⧉ copy`,title:`copy the RAW text of this message (no markdown rendering)`})}}),null),R(r,j(N,{get when(){return e.onEdit},get children(){var t=FS();return t.$$click=t=>{t.stopPropagation(),e.onEdit()},t}}),null),b(()=>L(i,`author tone-${Px(n.color)}`)),r}}),null),R(s,j(hC,{e:t,get prev(){return e.prev?.()},get res(){return e.res},get orphan(){return e.orphan},get onOption(){return e.onOption},get answeredIds(){return e.answeredIds},get onAnswered(){return e.onAnswered},get agentActive(){return e.agentActive},get onResize(){return e.onResize},get agentId(){return e.agentId}}),null),b(e=>{var s=`msg`+(r()?` grouped`:``)+(i()?` next-grouped`:``)+(t.data?.pending?` pending`:``)+(t.data?.cancelled?` withdrawn`:``),c=t.id,l=String(t.session??``),u=`avatar avghost tone-${Px(n.color)}`+(r()?` ghosted`:``),d=r()?`${Ix(t.ts)} · ${t.branch}`:void 0;return s!==e.e&&L(a,e.e=s),c!==e.t&&I(a,`data-eid`,e.t=c),l!==e.a&&I(a,`data-session`,e.a=l),u!==e.o&&L(o,e.o=u),d!==e.i&&I(o,`title`,e.i=d),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),a})()}function mC(e){let t=()=>(Array.isArray(e.data?.images)?e.data.images:[]).map(e=>typeof e==`string`?e:e?.url).filter(e=>typeof e==`string`&&e.length>0).map(t=>xf(e.agentId,t));return j(N,{get when(){return t().length},get children(){var e=zS();return R(e,j(M,{get each(){return t()},children:e=>(()=>{var t=BS();return t.$$click=()=>nt(e),I(t,`src`,e),t})()})),e}})}function hC(e){let t=e.e;switch(t.type){case`prompt`:{let n=(t.data?.images??[]).map(e=>typeof e==`string`?e:e?.url).filter(e=>typeof e==`string`&&e.length>0).map(t=>xf(e.agentId,t));return[j(fC,{get html(){return ut(String(t.data.text??``))}}),j(N,{get when(){return n.length},get children(){var e=zS();return R(e,j(M,{each:n,children:e=>(()=>{var t=VS();return t.$$click=()=>nt(e),I(t,`src`,e),t})()})),e}})]}case`message`:return[j(N,{get when(){return P(()=>typeof t.data.reasoning==`string`)()&&t.data.reasoning.trim()},get children(){var e=HS(),n=e.firstChild.nextSibling;return R(n,()=>String(t.data.reasoning)),e}}),j(fC,{get html(){return ut(String(t.data.content??``))}}),j(N,{get when(){return t.data.interrupted},get children(){return US()}}),j(N,{get when(){return t.data.final},get children(){var e=WS(),n=e.firstChild;return R(e,j(yd,{get text(){return String(t.data.content??``)}}),n),e}})];case`tool_call`:return j(dC,{e:t,get prev(){return e.prev},get res(){return e.res},get orphan(){return e.orphan},get agentActive(){return e.agentActive},get onResize(){return e.onResize},get agentId(){return e.agentId}});case`tool_result`:{let n=String(t.data.result??``),r=String(t.data.name??`tool`),i=t.data.ok!==!1;return(()=>{var a=KS(),o=a.firstChild,s=o.firstChild,c=o.nextSibling,l=c.nextSibling;return L(a,`embed `+(i?``:`fail`)),R(s,r===`bash`?`$ (bash, call evicted)`:r),R(o,j(yd,{text:n}),null),R(c,n),R(l,()=>dt(t.data.durationMs),null),R(l,()=>r===`bash`?Wx(Ux(t.data.ok,n)):i?``:` · FAILED`,null),R(a,j(N,{get when(){return e.orphan},get children(){return GS()}}),null),b(()=>a.open=e.orphan),a})()}case`decision`:{let e=Array.isArray(t.data?.alternatives)?t.data.alternatives:[];return(()=>{var n=JS(),r=n.firstChild.firstChild.firstChild.nextSibling;return R(n,j(fC,{get html(){return ut(String(t.data?.rationale??``))}}),null),R(n,j(N,{get when(){return e.length},get children(){var t=qS();return t.firstChild,R(t,()=>e.join(` / `),null),t}}),null),b(()=>r.innerHTML=ut(String(t.data?.decision??``))),n})()}case`question`:{let n=Array.isArray(t.data?.options)?t.data.options:[],r=t.data?.callId?String(t.data.callId):``,i=()=>e.answeredIds?.().has(r)??!1;return(()=>{var a=ZS(),o=a.firstChild.firstChild.nextSibling;return R(a,j(N,{get when(){return i()},get children(){return YS()}}),null),R(a,j(N,{get when(){return n.length>0},get children(){var a=XS();return R(a,j(M,{each:n,children:n=>(()=>{var a=QS();return a.$$click=()=>{e.onAnswered?.(r);let i=t.data?.actor;i?Y(`/api/agents/${encodeURIComponent(String(i))}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:n,start:!0})}).then(()=>bf(`→ answered @${String(t.data.actor)}`)).catch(()=>bf(`answer failed`)):e.onOption?.(n)},R(a,n),b(()=>a.disabled=i()),a})()})),a}}),null),R(a,j(uC,{get answered(){return i()},get onOption(){return e.onOption}}),null),b(e=>{var n=`embed question`+(i()?` answered`:``),r=ut(String(t.data?.question??``));return n!==e.e&&L(a,e.e=n),r!==e.t&&(o.innerHTML=e.t=r),e},{e:void 0,t:void 0}),a})()}case`progress`:return(()=>{var e=rC(),n=e.firstChild.firstChild.nextSibling;return R(e,j(N,{get when(){return t.data.goalStatus},get children(){var e=$S(),n=e.firstChild.nextSibling;return R(n,()=>String(t.data.goalStatus)),e}}),null),R(e,j(N,{get when(){return t.data.recent},get children(){var e=eC(),n=e.firstChild.nextSibling;return b(()=>n.innerHTML=ut(String(t.data.recent))),e}}),null),R(e,j(N,{get when(){return t.data.problems},get children(){var e=tC(),n=e.firstChild.nextSibling;return b(()=>n.innerHTML=ut(String(t.data.problems))),e}}),null),R(e,j(N,{get when(){return t.data.next},get children(){var e=nC(),n=e.firstChild.nextSibling;return b(()=>n.innerHTML=ut(String(t.data.next))),e}}),null),b(()=>n.innerHTML=ut(String(t.data.doing??``))),e})();case`error`:return(()=>{var e=iC(),n=e.firstChild;return n.firstChild,R(n,()=>String(t.data.message??``),null),e})();case`compaction`:return t.data.summary?(()=>{var e=cC(),n=e.firstChild.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,R(n,()=>String(t.data.mode??``),r),R(n,()=>Rx(Number(t.data.tokensBefore??0)),i),R(n,()=>Rx(Number(t.data.tokensAfter??0)),a),R(n,(()=>{var e=P(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),R(e,j(N,{get when(){return t.data.summary},get children(){return[sC(),j(fC,{get html(){return ut(String(t.data.summary))}})]}}),null),e})():(()=>{var e=oC(),n=e.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,R(n,()=>String(t.data.mode??``),r),R(n,()=>Rx(Number(t.data.tokensBefore??0)),i),R(n,()=>Rx(Number(t.data.tokensAfter??0)),a),R(n,(()=>{var e=P(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),R(n,()=>String(t.data.mode??``)===`truncate`?` · older history dropped`:``,null),R(e,j(N,{get when(){return String(t.data.mode??``)===`truncate`},get children(){return aC()}}),null),e})();default:return(()=>{var e=lC();return R(e,()=>ft(JSON.stringify(t.data),200)),e})()}}Ee([`input`,`keydown`,`click`]);var gC=(e,t)=>{let n=String(t??``).trim();return!n||/^\d+$/.test(n)?null:e?.[n]??null},_C=[{key:`openrouter`,label:`OpenRouter`,url:`https://openrouter.ai/api/v1`,model:``,hint:`400+ models behind one key — teapot sends app-attribution headers automatically`},{key:`orcarouter`,label:`OrcaRouter`,url:`https://api.orcarouter.ai/v1`,model:``,hint:`zero-markup routing gateway — 'orcarouter/auto' grades each prompt and picks the model`},{key:`openai`,label:`OpenAI`,url:`https://api.openai.com/v1`,model:``,hint:`your account's models — pick from the list once the endpoint answers`},{key:`opencode-go`,label:`OpenCode Go`,url:`https://opencode.ai/zen/go/v1`,model:``,hint:`OpenCode's open-model subscription — teapot sends the required x-opencode-session header; choose a chat/completions model`},{key:`llamacpp`,label:`llama.cpp server`,url:`http://localhost:8080/v1`,model:``,hint:`free & local — start it with: llama-server -m ./model.gguf (any model name works)`}];function vC(e,t){return e?t===`dark`?{slot:`dark`,key:`teapot.theme.dark`}:{slot:`light`,key:`teapot.theme.light`}:{slot:`fixed`,key:`teapot.theme`}}var yC=F(`<div class=themeeditor><h4 class=cfgsub>your themes</h4><div class=btnrow><button type=button title="copy the theme you are using into a new editable one — presets themselves are never modified">+ duplicate current`),bC=F(`<div class=muted style="margin:6px 0">`),xC=F(`<b>+ duplicate current`),SC=F(`<div class=cfggrid style=margin-top:8px><label class=trow>name<input type=text maxlength=40 placeholder="theme name"></label><label class=trow>appearance<select><option value=dark>dark</option><option value=light>light`),CC=F(`<div class=paletterows>`),wC=F(`<div class=btnrow><button type=button title="put every colour back to the palette this theme was created from">↺ reset palette</button><button type=button title="delete this custom theme">🗑 delete`),TC=F(`<h4 class=cfgsub>background image`),EC=F(`<img sizes=260px alt="current background"decoding=async loading=lazy>`,!0,!1,!1),DC=F(`<span class=bgpick-hint>🖼 replace…`),OC=F(`<div class=bgpreview><span class=muted title="this image is served from the server; the theme stores only its URL">✓ image set</span><div class=btnrow><label class=trow title="how much the image is dimmed so text stays readable">dim<input type=range min=0 max=0.9 step=0.01><span class="muted mono">%</span></label><label title="how much of the background shows through code blocks and tool cards — lower is more transparent">surfaces<input type=range min=0.35 max=1 step=0.01><span class="muted mono">%</span></label><button type=button>✕ remove`),kC=F(`<div class=cfggrid><button type=button></button><input type=file accept=image/* style=display:none>`),AC=F(`<div class=muted style=margin-top:6px;font-size:var(--text-xs)>the image is uploaded to the server and sits behind the panels, dimmed so text stays readable. No size limit — it is a file now, not browser storage.`),jC=F(`<label class=paletterow><input type=color><span class=paletterow-label></span><input class="mono paletterow-hex">`),MC=F(`<span class=bgpick-empty>🖼 choose a background image…`),NC=F(`<div class=muted style=font-size:11.5px;margin-top:4px>⚠ configured default provider <code></code> has no provider row here<!> Add a provider named <code></code> or pick a default below; otherwise agents fall back to the first provider.`),PC=F(`<div class=cfggrid style=margin-top:8px><label class=trow>dark theme →<select class=w100></select></label><label class=trow>light theme →<select class=w100>`),FC=F(`<div class=skilllist>`),IC=F(`<span style=color:var(--err);font-size:13px>`),LC=F(`<form style=display:flex;flex-direction:column;gap:12px;min-height:0><div class=cfgbody><nav class=cfgmenu aria-label="settings sections"></nav><div class=cfgpanel><fieldset><legend>providers</legend><button type=button>+ add custom</button><div style=display:flex;gap:6px;flex-wrap:wrap;margin-top:6px><span class=muted style=font-size:11.5px>quick-add:</span></div><div><label title="agents without an explicit provider use this one"style=display:flex;align-items:center;gap:6px;margin-top:6px>default provider<select><option value>(none — first provider wins)</option></select></label></div></fieldset><fieldset><legend>appearance</legend><div class=cfggrid><label class=trow>follow the system<input type=checkbox></label></div><h4 class=cfgsub>themes</h4></fieldset><fieldset><legend>agent runtime</legend><div class=cfgrow><label style=flex:1>API password<input type=password class=w100></label><span class=muted style=font-size:11.5px;max-width:34ch>bearer token for /api. empty = loopback only.</span></div><div class=cfggrid><label title="auto-compact threshold in k tokens. Leave EMPTY to derive per model (75% of its context window) — recommended, since models differ wildly in window size. Set only to force an absolute cap across all models.">compact budget (k tok)<input type=number min=0 placeholder="(derive: 75% of window)"></label></div><label class=cfgtoggle title="prune old tool output early (at 60% of the budget) instead of waiting for the window to fill. Meant for small-window models — on a large window it throws away context you had room for."><input type=checkbox>short-context mode</label></fieldset><fieldset><legend>MCP servers — external tools, shared by every agent</legend><div class=muted style=font-size:11.5px;margin-bottom:8px>each tool becomes <code class=mono>mcp__server__tool</code> for every agent. saving connects them; the status shown here is live.</div><button type=button>+ add MCP server</button></fieldset><fieldset><legend>scheduled tasks</legend><button type=button>+ add task</button></fieldset><fieldset><legend>archived agents — restore, or delete for good</legend></fieldset><fieldset><legend>agents (read-only — edit config file or use +)</legend></fieldset><fieldset><legend>live update</legend><div class=cfgrow><span class=muted>current version: </span><button type=button class=primarybtn>update & restart</button><span class=muted style=margin-left:8px;font-size:12px>gracefully stops all agents, spawns new process, then reloads this page</span></div></fieldset><fieldset><legend>skills</legend></fieldset><fieldset><legend>help</legend><div class=helpsec><h4 class=cfgsub>this host</h4><div class=featgrid><div class=featrow><b>image downscaling</b><span class=muted></span></div><div class=featrow><b>terminal pty</b><span class=muted></span></div></div></div><div class=helpsec><h4 class=cfgsub>keyboard</h4><div class=helprow><kbd>enter</kbd><span>send (shift+enter for a newline)</span></div><div class=helprow><span class=kbdgroup><kbd>↑</kbd><kbd>↓</kbd></span><span>move between sessions</span></div><div class=helprow><kbd>/</kbd><span>command palette — commands and focus</span></div><div class=helprow><kbd>t</kbd><span>open the terminal panel</span></div><div class=helprow><kbd>d</kbd><span>toggle the details panel</span></div><div class=helprow><kbd>esc</kbd><span>interrupt the running turn</span></div></div><div class=helpsec><h4 class=cfgsub>what the toggles do</h4><div class=helprow><b>auto-continue</b><span>fires after a round only when all hold: the toggle is on, a goal is set and its status is <code>active</code>, and the round ended cleanly (not an error, not stopped). It stops when the goal is marked done, or when you press ■ stop. Sending any prompt starts an idle agent regardless.</span></div><div class=helprow><b>auto-compact</b><span>when the live context passes the budget shown under 📊 runtime, older turns are summarized into notes and the recent stretch is kept verbatim, so work continues without losing the thread. Off means you compact by hand (<code>/compact</code>).</span></div><div class=helprow><b>messages while it works</b><span>anything you send queues up and is handed to the model at its next turn boundary — the timeline shows it as "pending (queued)…" until then. Withdraw it with ✕ cancel while it is still queued.</span></div><div class=helprow><b>👻 ghost sessions</b><span>a session whose workspace directory no longer exists on disk. The session log is intact — recreate the directory and it stops being a ghost.</span></div></div></fieldset></div></div><div class=cfgfoot><button type=submit class=cfgsave>`),RC=F(`<button type=button><span class=cfgmenu-label>`),zC=F(`<div class=cfgrow><input class=cfgname placeholder=name><input placeholder=https://…/v1><input placeholder="default model"><button type=button class=danger title="remove provider">✕</button><div class=cfgkeys><button type=button title="add another key for this provider — they are rotated round-robin, and a rate-limited key is skipped for a minute">+ key`),BC=F(`<button type=button title="remove this key">−`),VC=F(`<div class=cfgkeyrow><input type=password>`),HC=F(`<button type=button>+ `),UC=F(`<option>`),WC=F(`<div class=cfgsub style=margin-bottom:var(--space-1)>`),GC=F(`<div class=themepick>`),KC=F(`<button type=button><span class=themecard-preview></span><span class=themecard-label> ★`),qC=F(`<button type=button><span class=themecard-preview></span><span class=themecard-label>`),JC=F(`<div class=muted style=font-size:12.5px>no MCP servers. add one below — a remote url, or a local command for stdio.`),YC=F(`<input placeholder="command (e.g. npx)">`),XC=F(`<input placeholder="args, space separated">`),ZC=F(`<input type=password placeholder="paste the token"title="sent as Authorization: Bearer <token>"style=flex:1>`),QC=F(`<input placeholder="header name"style="flex:0 1 150px">`),$C=F(`<input type=password placeholder=value style=flex:1>`),ew=F(`<div class=cfgrow><textarea class=mono rows=2 placeholder="{&quot;Authorization&quot;: &quot;Bearer …&quot;, &quot;X-Team&quot;: &quot;infra&quot;}"title="static headers for every request. Use the bearer option unless the server needs something unusual."style=flex:1>`),tw=F(`<button type=button class=mcpauthorize title="start the OAuth flow: a browser tab opens, and the tools appear when you finish">🔑 authorize`),nw=F(`<span class="mcpstate connected"title="an OAuth access token is usable — disconnect it under the server's details">🔑 authorized`),rw=F(`<span>`),iw=F(`<div class=muted style=font-size:11px;color:var(--warn)>`),aw=F(`<div class="cfgcol mcpcard"><div class=cfgrow><input class=cfgname placeholder=name title="the name that appears inside mcp__<name>__ in tool names"><input placeholder="https://example.com/mcp (or leave empty for a stdio command)"><label style=display:flex;gap:3px;align-items:center;white-space:nowrap;color:var(--dim);font-size:11px><input type=checkbox>on</label><button type=button class=danger>✕</button></div><div class=cfgrow><input placeholder="what this server is for — e.g. reverse engineering: decompile, disassemble"title="shown to the model when the MCP catalog is too large to send, so it can search for the right tool instead of guessing keywords"></div><div class=cfgrow><select title="streamable HTTP is the current spec; legacy SSE is the 2024-11-05 handshake; stdio spawns a local process"><option value=http>streamable http</option><option value=sse>legacy http+sse</option><option value=stdio>stdio (local command)</option></select></div><div class=cfgrow><select title="how this server authenticates"><option value=none>no auth</option><option value=bearer>bearer token</option><option value=header>custom header</option><option value=json>headers as JSON (advanced)</option></select></div><div class=cfgrow><button type=button title="connect now and list the tools — nothing is saved">test`),ow=F(`<option value=oauth selected>`),sw=F(`<span class=muted> · needs a grant (🔑 authorize)`),cw=F(`<details class=mcptools-wrap><summary>show <!> tool</summary><ul class=mcptools>`),lw=F(`<div class=mcpdanger><span class=muted>OAuth grant</span><button type=button class=mcpdisconnect title="forget the stored grant (the refresh token is deleted, so authorizing again needs a browser)">disconnect`),uw=F(`<div><div class=mcpresult-head><b>`),dw=F(`<span class=mcptool-desc>`),fw=F(`<li><code class=mono>`),pw=F(`<div class=cfgcol><div class=cfgrow><input placeholder=id><input placeholder="agent id"><input placeholder="every 30m / cron"><label style=display:flex;gap:3px;align-items:center;white-space:nowrap;color:var(--dim);font-size:11px><input type=checkbox>fork</label><button type=button class=danger>✕</button></div><textarea rows=2 placeholder="prompt to send">`),mw=F(`<div class=muted style=font-size:12.5px>nothing archived. 🗄 archive in the controls panel puts an agent away without losing its history.`),hw=F(`<div class="cfgrow archrow"><div class=archmain><b></b><span class=muted> session</span><span class="muted mono ellip"></span></div><button type=button class=archrestore title="bring it back and start it again — its history was never touched">↩ restore</button><button type=button class=danger title="erase the config entry AND every session directory — irreversible">🗑 delete`),gw=F(`<span class=muted>🧩 sub of @`),_w=F(`<div class=cfgrow><b></b><span class=muted>`),vw=F(`<div class=muted>`),yw=F(`<div class=skillbody>`),bw=F(`<div class=skillrow><button type=button class=skillhead title="show the playbook"><span class=skillcaret></span><b class=mono></b><span class=muted>`),xw=F(`<div class="muted skillbody">`);function Sw(e){let[t,n]=y(e.themes().some(t=>t.id===e.paintedId)?e.paintedId:e.themes()[0]?.id??``),r=()=>ur(e.themes(),e.paintedId,t()),[i,a]=y({}),o,s=t=>{let n=r()?.id;if(!n)return;let i=e.themes().map(e=>e.id===n?t(e):e);e.onChange(i)},c=(e,t)=>{let n=cr(t);n&&s(t=>({...t,palette:{...t.palette,[e]:n}}))},l=()=>{let t=e.themes().find(t=>t.id===e.paintedId),r=Yd.find(t=>t.key===e.paintedId),i=t??r??Yd[0],a=getComputedStyle(document.documentElement),o={...Qn};for(let{key:e,cssVar:t}of Xn){let n=cr(a.getPropertyValue(t));n&&(o[e]=n)}let s=ar(e.themes().map(e=>e.id).concat(Yd.map(e=>e.key))),c={id:s,label:`${i.label}${t?``:` copy`}`.slice(0,40),mode:i.mode,palette:o,...t?.backgroundImage?{backgroundImage:t.backgroundImage,backgroundDim:t.backgroundDim,surfaceAlpha:t.surfaceAlpha}:{}};e.onChange([...e.themes(),c]),n(s),e.onPick(s)},u=async t=>{if(t){if(!/^image\//.test(t.type))bf(`that file is ${JSON.stringify(t.type||`unknown`)} — pick an image`);else{bf(`uploading ${t.name} (${Math.round(t.size/1024)}KB)…`);try{let n=await fetch(`/api/assets`,{method:`POST`,headers:{"content-type":t.type},body:t}).then(async e=>({ok:e.ok,body:await e.json().catch(()=>null)}));if(!n.ok||!n.body?.url){bf(n.body?.error??`upload failed`);return}s(e=>({...e,backgroundImage:n.body.url,backgroundImageBytes:n.body.bytes}));let i=r()?.id;i&&e.onPick(i),bf(`background image set`)}catch(e){bf(`upload failed: ${e.message}`)}}}};return(()=>{var t=yC(),d=t.firstChild.nextSibling.firstChild;return d.$$click=l,R(t,j(N,{get when(){return P(()=>!!(r()&&e.themes().some(t=>t.id===e.paintedId)))()?r():null},get fallback(){return(()=>{var t=bC();return R(t,(()=>{var t=P(()=>e.themes().length===0);return()=>t()?[`no custom themes yet — press `,xC(),` to start from the palette you are using.`]:[`the editor shows when one of your themes is the one on screen — pick one under "your themes" above (or press `,xC(),`).`]})()),t})()},children:t=>[(()=>{var e=SC(),t=e.firstChild,n=t.firstChild.nextSibling,i=t.nextSibling.firstChild.nextSibling;return n.$$input=e=>s(t=>({...t,label:e.currentTarget.value})),i.addEventListener(`change`,e=>s(t=>({...t,mode:e.currentTarget.value}))),b(()=>n.value=r().label),b(()=>i.value=r().mode),e})(),(()=>{var e=CC();return R(e,j(M,{each:Xn,children:e=>(()=>{var t=jC(),n=t.firstChild,o=n.nextSibling,s=o.nextSibling;return n.$$input=t=>c(e.key,t.currentTarget.value),R(o,()=>e.label),s.addEventListener(`blur`,()=>a(t=>{let n={...t};return delete n[e.key],n})),s.$$input=t=>{let n=t.currentTarget.value;a(t=>({...t,[e.key]:n})),c(e.key,n)},I(s,`spellcheck`,!1),b(()=>I(t,`title`,e.cssVar)),b(()=>n.value=cr(r().palette[e.key])??`#000000`),b(()=>s.value=i()[e.key]??r().palette[e.key]),t})()})),e})(),(()=>{var t=wC(),i=t.firstChild,a=i.nextSibling;return i.$$click=()=>s(e=>({...e,palette:{...Qn}})),a.$$click=()=>{let t=r()?.id;t&&(e.onChange(e.themes().filter(e=>e.id!==t)),n(e.themes().find(e=>e.id!==t)?.id??``))},t})(),TC(),(()=>{var e=kC(),t=e.firstChild,n=t.nextSibling;t.$$click=()=>o?.click(),R(t,j(N,{get when(){return r().backgroundImage},get fallback(){return MC()},get children(){return[(()=>{var e=EC();return b(t=>{var n=cn(r().backgroundImage),i=sn(r().backgroundImage);return n!==t.e&&I(e,`src`,t.e=n),i!==t.t&&I(e,`srcset`,t.t=i),t},{e:void 0,t:void 0}),e})(),DC()]}})),n.addEventListener(`change`,e=>{e.stopPropagation(),u(e.currentTarget.files?.[0]),e.currentTarget.value=``}),n.$$input=e=>e.stopPropagation();var i=o;return typeof i==`function`?Ae(i,n):o=n,R(e,j(N,{get when(){return r().backgroundImage},get children(){var e=OC(),t=e.firstChild;t.firstChild;var n=t.nextSibling.firstChild,i=n.firstChild.nextSibling,a=i.nextSibling,o=a.firstChild,c=n.nextSibling,l=c.firstChild.nextSibling,u=l.nextSibling,d=u.firstChild,f=c.nextSibling;return R(t,()=>{let e=r()?.backgroundImageBytes;return e?` — ${Math.max(1,Math.round(e/1024))} KB`:``},null),i.$$input=e=>s(t=>({...t,backgroundDim:Number(e.currentTarget.value)})),R(a,()=>Math.round((r().backgroundDim??.55)*100),o),l.$$input=e=>s(t=>({...t,surfaceAlpha:Number(e.currentTarget.value)})),R(u,()=>Math.round((r().surfaceAlpha??.82)*100),d),f.$$click=()=>s(e=>({...e,backgroundImage:void 0})),b(()=>i.value=r().backgroundDim??.55),b(()=>l.value=r().surfaceAlpha??.82),e}}),null),b(e=>{var n=`bgpick`+(r().backgroundImage?` has`:``),i=r().backgroundImage?`click to replace this background image (PNG/JPG/WebP)`:`choose a background image (PNG/JPG/WebP)`;return n!==e.e&&L(t,e.e=n),i!==e.t&&I(t,`title`,e.t=i),e},{e:void 0,t:void 0}),e})(),AC()]}),null),t})()}function Cw(e){let t=(e,t)=>{let n=Array.isArray(t?.apiKeys)&&t.apiKeys.length?t.apiKeys.filter(e=>typeof e==`string`&&e.trim()):t?.apiKey?[String(t.apiKey)]:[``];return{name:e,baseUrl:t?.baseUrl??``,apiKeys:n.length?n:[``],model:t?.model??``}},[n,r]=y(Object.entries(e.cfg.providers??{}).map(([e,n])=>t(e,n))),[i,a]=y(e.cfg.defaultProvider??``),o=()=>e.cfg.defaultProvider??``,s=()=>{let e=[...new Set(n().map(e=>e.name.trim()).filter(Boolean))],t=i();return t&&!e.includes(t)&&e.push(t),e},c=()=>{let e=i();return e?n().some(t=>t.name.trim()===e)?``:e:``},[l,u]=y(Math.round((e.cfg.progressIntervalMs??6e5)/6e4)),[d,f]=y(e.cfg.progressMinChars??4e3),[p,m]=y(e.cfg.contextTokenBudget==null?null:Math.round(e.cfg.contextTokenBudget/1e3)),[h,g]=y(e.cfg.contextWindowTokens?Math.round(e.cfg.contextWindowTokens/1e3):0),[_,v]=y(e.cfg.maxSpawnDepth??3),[ee,S]=y(!!e.cfg.shortContext),[C,w]=y(``),[T,E]=y(!1),[D,O]=y((e.cfg.tasks??[]).map(e=>({...e}))),[te,ne]=y((e.cfg.mcpServers??[]).map(e=>({...e}))),[re,k]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>[t,e.headers?JSON.stringify(e.headers):``]))),[ie,ae]=y({}),[oe,se]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=e.headers??{},r=Object.keys(n);if(!r.length)return[t,`none`];let i=r.length===1?r[0]:``;return i===`Authorization`&&/^Bearer /i.test(n[i]??``)?[t,`bearer`]:[t,r.length===1?`header`:`json`]}))),[ce,le]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=e.headers??{},r=Object.keys(n);if(r.length!==1)return[t,``];let i=r[0];return[t,i===`Authorization`?(n[i]??``).replace(/^Bearer /i,``):n[i]??``]}))),[ue,de]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=Object.keys(e.headers??{}),r=n.length===1?n[0]:``;return[t,r&&r!==`Authorization`?r:``]}))),[fe,A]=y({}),pe={},me=async(e,t)=>{if(!te()[e])return;let n=await Y(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}).catch(()=>null);te()[e]&&n&&A(t=>({...t,[e]:n.ok?{kind:`ok`,text:`${n.tools?.length??0} tools`}:{kind:`err`,text:n.needsOAuth?`needs authorization — press 🔑`:n.error??`no response`,...n.needsOAuth?{needsOAuth:!0}:{}}}))},[he,ge]=y({}),[_e,ve]=y({}),ye=e=>{let t=gC(_e(),e);return t&&(t.required||t.authorized)?t:null},be=async()=>{let e=await Y(`/api/mcp`).catch(()=>null);ge(Object.fromEntries((e?.states??[]).map(e=>[e.name,e])))},xe=async e=>{let t=String(e??``).trim();if(!t)return;let n=await Y(`/api/mcp/oauth/status?name=${encodeURIComponent(t)}`).catch(()=>null);n&&!n.error&&ve(e=>({...e,[t]:n}))},Ce=async(t,n)=>{if(!n.name){A(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}A(e=>({...e,[t]:{kind:`testing`,text:`discovering the authorization server…`}}));let r=await Y(`/api/mcp/oauth/start`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:n.name,url:n.url})}).catch(()=>null);if(r?.alreadyAuthorized){A(e=>({...e,[t]:{kind:`ok`,text:`already authorized`}})),await xe(n.name),await be();return}if(!r?.ok||!r.url){A(e=>({...e,[t]:{kind:`err`,text:r?.error??`no response`}})),await xe(n.name);return}window.open(r.url,`_blank`,`noopener`),A(e=>({...e,[t]:{kind:`testing`,text:`waiting for you to finish in the browser…`}}));let i=Date.now()+3e5;for(;Date.now()<i;){await new Promise(e=>setTimeout(e,1e3));let r=await Y(`/api/mcp/oauth/status?name=${encodeURIComponent(n.name)}`).catch(()=>null);if(r&&!r.error){if(ve(e=>({...e,[n.name]:r})),r.authorized){A(e=>({...e,[t]:{kind:`ok`,text:`authorized — the tools are available now`}})),await be(),e.onSaved();return}if(r.flow?.phase===`error`){A(e=>({...e,[t]:{kind:`err`,text:r.flow.message??r.lastError??`authorization failed`}}));return}}}A(e=>({...e,[t]:{kind:`err`,text:`authorization timed out`}}))};x(()=>{F()===`mcp`&&(be(),te().forEach((e,t)=>{e.name&&xe(e.name)}))});let[we,Te]=y(``),[F,Ee]=y(`providers`),De=(t,n)=>{let{slot:r}=vC(e.theme.auto(),n);r===`dark`?Ge(t):r===`light`?qe(t):Ve(t)},Oe=t=>e.theme.auto()?t===e.theme.dark()||t===e.theme.light():t===e.theme.activeId(),[ke,Ae]=y([]),je=async()=>{let e=await Y(`/api/archived`).catch(()=>null);Ae(e?.agents??[])},Me=()=>ke().filter(e=>!e.parent);x(()=>{F()===`archive`&&je()});let Ne=[{key:`providers`,label:`🧦 providers`,hint:`endpoints, API keys, default models`},{key:`appearance`,label:`🎨 appearance`,hint:`theme, custom palettes, background image`},{key:`runtime`,label:`⚙️ runtime`,hint:`context budget, retries, spawn depth`},{key:`tasks`,label:`⏰ scheduled tasks`,hint:`cron prompts run against an agent`},{key:`mcp`,label:`🔌 MCP servers`,hint:`external tool servers exposed to every agent`},{key:`archive`,label:`🗄 archive`,hint:`agents you put away — restore or delete for good`},{key:`agents`,label:`👥 agents`,hint:`what exists (read-only)`},{key:`update`,label:`⬆️ live update`,hint:`restart onto a newer build`},{key:`skills`,label:`🧠 skills`,hint:`reusable playbooks available to the selected session`},{key:`help`,label:`❔️ help`,hint:`keyboard shortcuts and what each toggle does`}],Pe=()=>(e.cfg.agents??[]).map(e=>e.id),Fe=()=>e.theme.themes(),Ie=()=>e.theme.activeId(),Le={auto:localStorage.getItem(`teapot.theme.auto`)===`1`,dark:localStorage.getItem(`teapot.theme.dark`)??`dark`,light:localStorage.getItem(`teapot.theme.light`)??`light`,fixed:localStorage.getItem(`teapot.theme`)??`dark`},Re=y(Le),ze=Re[0],Be=t=>{let n={...ze(),...t};Re[1](n),e.theme.setAuto(n.auto),e.theme.setDark(n.dark),e.theme.setLight(n.light),e.theme.setActive(n.fixed);let r=t.dark??t.light??t.fixed;r&&e.theme.preview(r)},Ve=e=>Be({fixed:e}),He=()=>ze().auto,Ue=e=>Be({auto:e}),We=()=>ze().dark,Ge=e=>Be({dark:e}),Ke=()=>ze().light,qe=e=>Be({light:e}),Je=t=>e.theme.setThemes(t),Ye=()=>{let t=Le;e.theme.setAuto(t.auto),e.theme.setDark(t.dark),e.theme.setLight(t.light),e.theme.setActive(t.fixed),e.theme.preview(null)},Xe=e=>$n[e]??Qn,Ze=()=>{let e={};for(let t of n()){if(!t.name.trim())return Te(`provider name is required`),null;if(t.baseUrl&&!/^https?:\/\//.test(t.baseUrl))return Te(`provider ${t.name}: baseUrl must start with http(s)://`),null;let n=t.apiKeys.map(e=>e.trim()).filter(Boolean);e[t.name.trim()]={baseUrl:t.baseUrl,...n.length?{apiKeys:n,apiKey:n[0]}:{},...t.model?{model:t.model}:{}}}return e},[Qe,$e]=y(`idle`),et=e=>{Te(e),$e(e=>e===`saving`?`idle`:e)},tt=async t=>{t.preventDefault(),Te(``),$e(`saving`);let n=Ze();if(!n)return $e(`idle`);let r=D().filter(e=>e.id?.trim()||e.prompt?.trim()).map((e,t)=>({id:e.id?.trim()||`task-${t+1}`,agent:e.agent,schedule:e.schedule,prompt:e.prompt,...e.forked?{forked:!0}:{}}));for(let e of r){if(!e.agent)return et(`task "${e.id}": agent is required`);if(!e.schedule?.trim())return et(`task "${e.id}": schedule is required`)}let a=[],o=new Set;for(let e of te()){let t=String(e.name??``).trim(),n=String(e.url??``).trim(),r=e.transport??`http`,i=String(e.command??``).trim();if(t||n||i){if(!t)return et(`MCP: a server needs a name`);if(o.has(t))return et(`MCP: two servers are named "${t}"`);if(o.add(t),r===`stdio`?!i:!n)return et(`MCP "${t}": ${r===`stdio`?`a command is`:`a url is`} required`);a.push({name:t,transport:r,enabled:e.enabled!==!1,...String(e.description??``).trim()?{description:String(e.description).trim()}:{},...n?{url:n}:{},...r===`stdio`?{command:i,...e.args?.length?{args:e.args}:{}}:{},...e.headers&&Object.keys(e.headers).length?{headers:e.headers}:{}})}}try{await Y(`/api/config`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({providers:n,defaultProvider:i()||void 0,progressIntervalMs:Math.max(1,l())*6e4,progressMinChars:Math.max(100,d()),...p()==null?{}:{contextTokenBudget:Math.max(1,p())*1e3},...h()>0?{contextWindowTokens:h()*1e3}:{},maxSpawnDepth:Math.max(0,_()),shortContext:ee(),...T()?{password:C()}:{},tasks:r,mcpServers:a})}),await be(),await Promise.all(a.map((e,t)=>e.name?xe(e.name):Promise.resolve())),setTimeout(()=>{be(),a.forEach((e,t)=>{e.name&&xe(e.name)})},1200),e.onSaved();let t=new Set(a.map(e=>e.name).filter(Boolean)),o=te().filter(e=>{let n=String(e.name??``).trim();return t.has(n)&&_e()[n]?.required&&!_e()[n]?.authorized}).filter(t=>!e.announcedOAuth.has(String(t.name??``)));if(o.length>0){for(let t of o)e.announcedOAuth.add(String(t.name??``));bf(`${o.map(e=>String(e.name??``).trim()).filter(Boolean).join(`, `)||`a saved MCP server`} needs authorization — 🔑 authorize in MCP servers`)}e.theme.commitAppearance(ze()),e.theme.preview(null),$e(`saved`),Object.assign(Le,ze()),setTimeout(()=>{$e(`idle`),e.onClose()},400)}catch(e){Te(e.message),$e(`error`),setTimeout(()=>$e(`idle`),1600)}};return j(bd,{title:`settings`,onClose:()=>{Ye(),e.onClose()},get children(){var t=LC(),x=t.firstChild,T=x.firstChild,ge=T.nextSibling.firstChild,ve=ge.firstChild.nextSibling,be=ve.nextSibling;be.firstChild;var ke=be.nextSibling.firstChild.firstChild.nextSibling;ke.firstChild;var Ae=ge.nextSibling,Le=Ae.firstChild.nextSibling,Re=Le.firstChild.firstChild.nextSibling,ze=Le.nextSibling,Be=Ae.nextSibling,Ye=Be.firstChild.nextSibling,Ze=Ye.firstChild.firstChild.nextSibling,$e=Ye.nextSibling,et=$e.firstChild,nt=et.firstChild.nextSibling,rt=$e.nextSibling.firstChild,it=Be.nextSibling,at=it.firstChild.nextSibling.nextSibling,ot=it.nextSibling,st=ot.firstChild.nextSibling,ct=ot.nextSibling;ct.firstChild;var lt=ct.nextSibling;lt.firstChild;var dt=lt.nextSibling,ft=dt.firstChild.nextSibling.firstChild;ft.firstChild;var mt=ft.nextSibling,ht=dt.nextSibling;ht.firstChild;var gt=ht.nextSibling,_t=gt.firstChild.nextSibling.firstChild.nextSibling.firstChild,vt=_t.firstChild.nextSibling,yt=_t.nextSibling.firstChild.nextSibling,bt=x.nextSibling,xt=bt.firstChild;return t.addEventListener(`submit`,tt),R(T,j(M,{each:Ne,children:e=>(()=>{var t=RC(),n=t.firstChild;return t.$$click=()=>Ee(e.key),R(n,()=>e.label),b(n=>{var r=`cfgmenu-item`+(F()===e.key?` on`:``),i=e.hint,a=F()===e.key?`page`:void 0;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-current`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})),R(ge,j(Se,{get each(){return n()},children:(e,t)=>(()=>{var i=zC(),a=i.firstChild,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.firstChild;return a.$$input=e=>r(n().map((n,r)=>r===t?{...n,name:e.currentTarget.value}:n)),o.$$input=e=>r(n().map((n,r)=>r===t?{...n,baseUrl:e.currentTarget.value}:n)),s.$$input=e=>r(n().map((n,r)=>r===t?{...n,model:e.currentTarget.value}:n)),c.$$click=()=>r(n().filter((e,n)=>n!==t)),R(l,j(M,{get each(){return e().apiKeys},children:(i,a)=>(()=>{var o=VC(),s=o.firstChild;return s.$$input=e=>r(n().map((n,r)=>r===t?{...n,apiKeys:n.apiKeys.map((t,n)=>n===a()?e.currentTarget.value:t)}:n)),s.value=i,R(o,j(N,{get when(){return e().apiKeys.length>1},get children(){var e=BC();return e.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:e.apiKeys.filter((e,t)=>t!==a())}:e)),e}}),null),b(()=>I(s,`placeholder`,a()===0?`api key`:`api key (backup)`)),o})()}),u),u.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:[...e.apiKeys,``]}:e)),b(()=>a.value=e().name),b(()=>o.value=e().baseUrl),b(()=>s.value=e().model),i})()}),ve),ve.$$click=()=>r([...n(),{name:``,baseUrl:``,apiKeys:[``],model:``}]),R(be,j(M,{each:_C,children:e=>(()=>{var t=HC();return t.firstChild,t.$$click=()=>{let t=n().filter(t=>t.name!==e.key);r([...t,{name:e.key,baseUrl:e.url,apiKeys:[``],model:e.model}]),i()||a(e.key)},R(t,()=>e.label,null),b(()=>I(t,`title`,`fill a ${e.label} row — ${e.url}${e.model?` (model: ${e.model})`:``}`)),t})()}),null),ke.addEventListener(`change`,e=>a(e.currentTarget.value)),R(ke,j(M,{get each(){return s()},children:e=>(()=>{var t=UC();return t.value=e,R(t,e),t})()}),null),R(ge,j(N,{get when(){return c()},get children(){var e=NC(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling,r=n.nextSibling.nextSibling;return R(t,c),R(e,()=>c()===o()?` — the dropdown above cannot show it.`:` — it was replaced by your selection.`,n),R(r,c),e}}),null),Re.addEventListener(`change`,e=>{Ue(e.currentTarget.checked)}),R(Ae,j(N,{get when(){return He()},get children(){var e=PC(),t=e.firstChild,n=t.firstChild.nextSibling,r=t.nextSibling.firstChild.nextSibling;return n.addEventListener(`change`,e=>{Ge(e.currentTarget.value)}),R(n,j(M,{get each(){return Fe().filter(e=>e.mode===`dark`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat(Yd.filter(e=>e.mode===`dark`))},children:e=>(()=>{var t=UC();return R(t,()=>e.label),b(()=>t.value=e.key),t})()})),r.addEventListener(`change`,e=>{qe(e.currentTarget.value)}),R(r,j(M,{get each(){return Fe().filter(e=>e.mode===`light`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat(Yd.filter(e=>e.mode===`light`))},children:e=>(()=>{var t=UC();return R(t,()=>e.label),b(()=>t.value=e.key),t})()})),b(()=>n.value=We()),b(()=>r.value=Ke()),e}}),ze),R(Ae,j(M,{each:[{mode:`dark`,title:`dark themes`},{mode:`light`,title:`light themes`}],children:e=>j(N,{get when(){return[...Fe(),...Yd].some(t=>t.mode===e.mode)},get children(){return[(()=>{var t=WC();return R(t,()=>e.title),t})(),(()=>{var t=GC();return R(t,j(M,{get each(){return Fe().filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=KC(),n=t.firstChild,r=n.nextSibling,i=r.firstChild;return t.$$click=()=>De(e.id,e.mode),R(n,j(gf,{get palette(){return e.palette},get backgroundImage(){return e.backgroundImage},get surfaceAlpha(){return e.surfaceAlpha},get backgroundDim(){return e.backgroundDim}})),R(r,()=>e.label,i),b(n=>{var r=`themecard`+(Oe(e.id)?` on`:``),i=`${e.label} (custom)${e.backgroundImage?` · with a background image`:``}`,a=Oe(e.id);return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),R(t,j(M,{get each(){return Yd.filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=qC(),n=t.firstChild,r=n.nextSibling;return t.$$click=()=>De(e.key,e.mode),R(n,j(gf,{get palette(){return Xe(e.key)}})),R(r,()=>e.label),b(n=>{var r=`themecard`+(Oe(e.key)?` on`:``),i=`${e.label} (${e.mode})`,a=Oe(e.key);return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),t})()]}})}),null),R(Ae,j(Sw,{themes:Fe,get paintedId(){return e.theme.paintedId()},onChange:e=>{let t=rr(e),n=e;if(!t.ok){let t=e.map(e=>e.backgroundImage?{...e,backgroundImage:void 0,backgroundDim:void 0,surfaceAlpha:void 0,backgroundImageBytes:void 0}:e),r=rr(t);if(r.ok)n=t,bf(`storage was full — saved without the background image(s)`);else{bf(r.error??`could not save theme`);return}}Je(n);let r=e=>n.some(t=>t.id===e)||Yd.some(t=>t.key===e);r(Ie())||(Ve(`dark`),localStorage.setItem(`teapot.theme`,`dark`)),r(We())||(Ge(`dark`),localStorage.setItem(`teapot.theme.dark`,`dark`)),r(Ke())||(qe(`light`),localStorage.setItem(`teapot.theme.light`,`light`))},onPick:e=>{let t=Fe().find(t=>t.id===e)?.mode??Yd.find(t=>t.key===e)?.mode??`dark`,n=vC(He(),t);n.slot===`dark`?Ge(e):n.slot===`light`?qe(e):Ve(e)}}),null),Ze.$$input=e=>{w(e.currentTarget.value),E(!0)},R($e,j(hf,{label:`progress interval (min)`,get value(){return l()},onValue:e=>u(e),hint:`how often the harness asks for a progress report`}),et),R($e,j(hf,{label:`progress min chars`,get value(){return d()},onValue:e=>f(e),hint:`progress prompts wait for this much real output`}),et),nt.$$input=e=>m(e.currentTarget.value===``?null:Number(e.currentTarget.value)),R($e,j(hf,{label:`context window (k tok)`,get value(){return h()},onValue:e=>g(e),hint:`model's real window — 0/blank hides the % gauge`}),null),R($e,j(hf,{label:`max spawn depth`,get value(){return _()},onValue:e=>v(e),hint:`sub-agent nesting limit (0 = no spawning)`}),null),rt.addEventListener(`change`,e=>S(e.currentTarget.checked)),R(it,j(N,{get when(){return te().length>0},get fallback(){return JC()},get children(){return j(Se,{get each(){return te()},children:(e,t)=>{let n=()=>he()[e().name],r=e=>ne(te().map((n,r)=>r===t?{...n,...e}:n));return(()=>{var i=aw(),a=i.firstChild,o=a.firstChild,s=o.nextSibling,c=s.nextSibling,l=c.firstChild,u=c.nextSibling,d=a.nextSibling,f=d.firstChild,p=d.nextSibling,m=p.firstChild,h=p.nextSibling,g=h.firstChild,_=g.firstChild,v=h.nextSibling,ee=v.firstChild;return o.$$input=e=>r({name:e.currentTarget.value}),s.$$input=e=>{r({url:e.currentTarget.value});let n=e.currentTarget.value.trim();clearTimeout(pe[t]),/^https?:\/\//.test(n)&&(pe[t]=setTimeout(()=>{me(t,{...te()[t],url:n})},700))},l.addEventListener(`change`,e=>r({enabled:e.currentTarget.checked})),u.$$click=()=>ne(te().filter((e,n)=>n!==t)),f.$$input=e=>r({description:e.currentTarget.value}),m.addEventListener(`change`,e=>r({transport:e.currentTarget.value})),R(p,j(N,{get when(){return e().transport===`stdio`},get children(){return[(()=>{var t=YC();return t.$$input=e=>r({command:e.currentTarget.value}),b(()=>t.value=e().command??``),t})(),(()=>{var t=XC();return t.$$input=e=>r({args:e.currentTarget.value.split(` `).filter(Boolean)}),b(()=>t.value=(e().args??[]).join(` `)),t})()]}}),null),g.addEventListener(`change`,e=>{let n=e.currentTarget.value;if(se(e=>({...e,[t]:n})),n===`none`)r({headers:void 0});else if(n===`bearer`){let e=ce()[t]??``;r({headers:e?{Authorization:`Bearer ${e}`}:void 0})}else if(n===`header`){let e=ue()[t]??``,n=ce()[t]??``;r({headers:e&&n?{[e]:n}:void 0})}}),R(g,j(N,{get when(){return ye(String(e().name??``))},children:e=>(()=>{var t=ow();return R(t,()=>e().authorized?`OAuth — authorized`:`OAuth — authorization needed`),t})()}),_),R(h,j(N,{get when(){return oe()[t]===`bearer`},get children(){var e=ZC();return e.$$input=e=>{let n=e.currentTarget.value;le(e=>({...e,[t]:n})),r({headers:n?{Authorization:`Bearer ${n}`}:void 0})},b(()=>e.value=ce()[t]??``),e}}),null),R(h,j(N,{get when(){return oe()[t]===`header`},get children(){return[(()=>{var e=QC();return e.$$input=e=>{let n=e.currentTarget.value;de(e=>({...e,[t]:n}));let i=ce()[t]??``;r({headers:n&&i?{[n]:i}:void 0})},b(()=>e.value=ue()[t]??``),e})(),(()=>{var e=$C();return e.$$input=e=>{let n=e.currentTarget.value;le(e=>({...e,[t]:n}));let i=ue()[t]??``;r({headers:i&&n?{[i]:n}:void 0})},b(()=>e.value=ce()[t]??``),e})()]}}),null),R(i,j(N,{get when(){return oe()[t]===`json`},get children(){var e=ew(),n=e.firstChild;return n.$$input=e=>{let n=e.currentTarget.value;if(k(e=>({...e,[t]:n})),!n.trim())r({headers:void 0});else try{let e=JSON.parse(n);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`not an object`);r({headers:e}),ae(e=>({...e,[t]:``}))}catch{ae(e=>({...e,[t]:`must be a JSON object — not applied`}))}},b(()=>n.value=re()[t]??``),e}}),v),ee.$$click=async()=>{let e=te()[t];if(!e.name){A(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}A(e=>({...e,[t]:{kind:`testing`,text:`connecting…`}}));let n=await Y(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}).catch(()=>null);A(e=>({...e,[t]:n?.ok?{kind:`ok`,text:`${n.tools?.length??0} tool${n.tools?.length===1?``:`s`}`,tools:n.tools??[]}:{kind:`err`,text:n?.error??`no response`,...n?.needsOAuth?{needsOAuth:!0}:{}}})),n?.ok||await xe(e.name)},R(v,j(N,{get when(){return P(()=>!!gC(_e(),String(e().name??``))?.required)()&&!gC(_e(),String(e().name??``))?.authorized},get children(){var n=tw();return n.$$click=()=>void Ce(t,e()),n}}),null),R(v,j(N,{get when(){return gC(_e(),String(e().name??``))?.authorized},get children(){return nw()}}),null),R(v,j(N,{get when(){return n()},get children(){var e=rw();return R(e,(()=>{var e=P(()=>n()?.status===`connected`);return()=>e()?`● ${n()?.tools} tools`:P(()=>n()?.status===`error`)()?`● error`:n()?.status===`disabled`?`● off`:`● idle`})()),b(t=>{var r=`mcpstate `+(n()?.status??``),i=n()?.lastError??``;return r!==t.e&&L(e,t.e=r),i!==t.t&&I(e,`title`,t.t=i),t},{e:void 0,t:void 0}),e}}),null),R(i,j(N,{get when(){return ie()[t]},get children(){var e=iw();return R(e,()=>ie()[t]),e}}),null),R(i,j(N,{get when(){return fe()[t]},children:n=>(()=>{var r=uw(),i=r.firstChild,a=i.firstChild;return R(a,()=>n().text),R(i,j(N,{get when(){return n().needsOAuth},get children(){return sw()}}),null),R(r,j(N,{get when(){return(n().tools?.length??0)>0},get children(){var e=cw(),t=e.firstChild,r=t.firstChild.nextSibling;r.nextSibling;var i=t.nextSibling;return R(t,()=>n().tools?.length,r),R(t,()=>n().tools?.length===1?``:`s`,null),R(i,j(M,{get each(){return n().tools??[]},children:e=>(()=>{var t=fw(),n=t.firstChild;return R(n,()=>e.name),R(t,j(N,{get when(){return e.description},get children(){var t=dw();return R(t,()=>e.description),t}}),null),b(()=>I(t,`title`,e.description??``)),t})()})),e}}),null),R(r,j(N,{get when(){return gC(_e(),String(e().name??``))?.authorized},get children(){var n=lw(),r=n.firstChild.nextSibling;return r.$$click=async()=>{confirm(`Disconnect ${e().name}?\n\nThe stored OAuth grant is deleted and you will have to authorize again in a browser.`)&&(await Y(`/api/mcp/oauth/disconnect`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:e().name})}).catch(()=>{}),await xe(e().name),A(e=>({...e,[t]:{kind:`ok`,text:`disconnected`}})))},n}}),null),b(()=>L(r,`mcpresult `+(n().kind===`err`?`err`:`ok`))),r})()}),null),b(()=>o.value=e().name),b(()=>s.value=e().url??``),b(()=>l.checked=e().enabled!==!1),b(()=>f.value=e().description??``),b(()=>m.value=e().transport??`http`),b(()=>g.value=ye(String(e().name??``))?`oauth`:oe()[t]??`none`),i})()}})}}),at),at.$$click=()=>ne([...te(),{name:``,url:``,transport:`http`,enabled:!0}]),R(ot,j(N,{get when(){return D().length>0},get children(){return j(Se,{get each(){return D()},children:(e,t)=>(()=>{var n=pw(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,c=s.firstChild,l=s.nextSibling,u=r.nextSibling;return i.$$input=e=>O(D().map((n,r)=>r===t?{...n,id:e.currentTarget.value}:n)),a.$$input=e=>O(D().map((n,r)=>r===t?{...n,agent:e.currentTarget.value}:n)),o.$$input=e=>O(D().map((n,r)=>r===t?{...n,schedule:e.currentTarget.value}:n)),c.addEventListener(`change`,e=>O(D().map((n,r)=>r===t?{...n,forked:e.currentTarget.checked}:n))),l.$$click=()=>O(D().filter((e,n)=>n!==t)),u.$$input=e=>O(D().map((n,r)=>r===t?{...n,prompt:e.currentTarget.value}:n)),b(()=>i.value=e().id),b(()=>a.value=e().agent),b(()=>o.value=e().schedule),b(()=>c.checked=!!e().forked),b(()=>u.value=e().prompt),n})()})}}),st),st.$$click=()=>O([...D(),{id:``,agent:Pe()[0]??``,schedule:`every 30m`,prompt:``}]),R(ct,j(N,{get when(){return Me().length>0},get fallback(){return mw()},get children(){return j(M,{get each(){return Me()},children:t=>(()=>{var n=hw(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=a.nextSibling,c=r.nextSibling,l=c.nextSibling;return R(i,()=>t.id),R(a,()=>t.sessions,o),R(a,()=>t.sessions===1?``:`s`,null),R(a,(()=>{var e=P(()=>(t.subs??0)>0);return()=>e()?` · +${t.subs} sub-agent${t.subs===1?``:`s`} (restored together)`:``})(),null),R(a,(()=>{var e=P(()=>!!t.archivedAt);return()=>e()?` · archived ${pt(new Date(t.archivedAt).toISOString())}`:``})(),null),R(s,()=>t.workspace),c.$$click=async()=>{let n=await Y(`/api/agents/${t.id}/restore`,{method:`POST`}).catch(()=>null);await je(),e.onSaved();let r=(n?.ids?.length??1)-1;bf((n?.live===!1?`restored ${t.id} — it could not be started (check its provider)`:`restored ${t.id}`)+(r>0?` + ${r} sub-agent${r===1?``:`s`}`:``))},l.$$click=async()=>{confirm(`PERMANENTLY DELETE ${t.id}?\n\n${t.sessions} session${t.sessions===1?``:`s`} of history will be erased from disk along with the config entry. This cannot be undone — archiving was the reversible option.`)&&(await Y(`/api/agents/${t.id}/purge`,{method:`DELETE`}).catch(()=>{}),await je(),e.onSaved(),bf(`deleted ${t.id} for good`))},b(()=>I(s,`title`,t.workspace)),n})()})}}),null),R(lt,j(M,{get each(){return e.cfg.agents??[]},children:e=>(()=>{var t=_w(),n=t.firstChild,r=n.nextSibling;return R(n,()=>e.id),R(r,()=>e.workspace),R(t,j(N,{get when(){return e.parent},get children(){var t=gw();return t.firstChild,R(t,()=>e.parent,null),t}}),null),t})()}),null),R(ft,()=>e.cfg.version??`unknown`,null),mt.$$click=async e=>{try{Te(``);let t=e.currentTarget;t.disabled=!0,t.textContent=`updating…`;let n=await Y(`/api/update/restart`,{method:`POST`});if(!n.ok)throw Error((await n.json()).error??`restart failed`);t.textContent=`restarting…`;let r=null,i=!1;for(let e=0;e<120&&!i;e++){await new Promise(e=>setTimeout(e,1e3));try{let e=await Y(`/api/version`);if(!e.version)continue;r===null&&(r=e.uptimeSeconds??null),(e.version!==`0.37.148`||typeof e.uptimeSeconds==`number`&&r!==null&&e.uptimeSeconds<r)&&(i=!0,window.location.reload())}catch{}}if(!i)throw Error(`restart timeout — new server did not come up`)}catch(e){Te(e.message)}finally{e.currentTarget.disabled=!1,e.currentTarget.textContent=`update & restart`}},R(ht,j(N,{get when(){return e.skills.length>0},get fallback(){return(()=>{var t=vw();return R(t,()=>e.hasSelection?`this session has no skills yet — the agent saves them with save_skill once a procedure proves itself`:`select a session to see the skills available to it`),t})()},get children(){var t=FC();return R(t,j(M,{get each(){return e.skills},children:t=>{let[n,r]=y(!1),[i,a]=y(null),[o,s]=y(``),c=async()=>{if(n())return r(!1);if(r(!0),i()===null&&e.agentId)try{let n=await Y(`/api/agents/${e.agentId}/skills/${encodeURIComponent(t.name)}`);a(String(n.text??``))}catch(e){s(e.message)}};return(()=>{var e=bw(),r=e.firstChild,a=r.firstChild,s=a.nextSibling,l=s.nextSibling;return r.$$click=c,R(a,()=>n()?`▾`:`▸`),R(s,()=>t.name),R(l,()=>t.description),R(e,j(N,{get when(){return n()},get children(){return j(N,{get when(){return i()!==null},get fallback(){return(()=>{var e=xw();return R(e,()=>o()||`loading…`),e})()},get children(){var e=yw();return b(()=>e.innerHTML=ut(String(i()??``))),e}})}}),null),b(()=>e.classList.toggle(`open`,!!n())),e})()}})),t}}),null),R(vt,(()=>{var t=P(()=>!!e.features);return()=>t()?P(()=>!!e.features.imageResize.available)()?`on — ${e.features.imageResize.tool}, long edge ≤ ${e.features.imageResize.maxEdge}px`:`off — no ffmpeg / ImageMagick found; uploads are served as-is`:`checking…`})()),R(yt,(()=>{var t=P(()=>!!e.features);return()=>t()?P(()=>!!e.features.pty.available)()?`on — ${e.features.pty.provider}`:`off — no pty provider; terminals run on plain pipes (no resize)`:`checking…`})()),R(bt,j(N,{get when(){return we()},get children(){var e=IC();return R(e,we),e}}),xt),R(xt,(()=>{var e=P(()=>Qe()===`saving`);return()=>e()?`saving…`:P(()=>Qe()===`saved`)()?`✓ saved`:Qe()===`error`?`✕ failed`:`save settings`})()),b(t=>{var n=F()!==`providers`,r=F()!==`appearance`,i=F()!==`runtime`,a=e.cfg.hasPassword?`(unchanged — type to replace)`:`(none — loopback only)`,o=F()!==`mcp`,s=F()!==`tasks`,c=F()!==`archive`,l=F()!==`agents`,u=F()!==`update`,d=F()!==`skills`,f=F()!==`help`,p=Qe()===`saved`,m=Qe()===`error`,h=Qe()===`saving`;return n!==t.e&&ge.classList.toggle(`hide`,t.e=n),r!==t.t&&Ae.classList.toggle(`hide`,t.t=r),i!==t.a&&Be.classList.toggle(`hide`,t.a=i),a!==t.o&&I(Ze,`placeholder`,t.o=a),o!==t.i&&it.classList.toggle(`hide`,t.i=o),s!==t.n&&ot.classList.toggle(`hide`,t.n=s),c!==t.s&&ct.classList.toggle(`hide`,t.s=c),l!==t.h&&lt.classList.toggle(`hide`,t.h=l),u!==t.r&&dt.classList.toggle(`hide`,t.r=u),d!==t.d&&ht.classList.toggle(`hide`,t.d=d),f!==t.l&&gt.classList.toggle(`hide`,t.l=f),p!==t.u&&xt.classList.toggle(`saved`,t.u=p),m!==t.c&&xt.classList.toggle(`error`,t.c=m),h!==t.w&&(xt.disabled=t.w=h),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0}),b(()=>ke.value=i()),b(()=>Re.checked=He()),b(()=>Ze.value=C()),b(()=>nt.value=p()??``),b(()=>rt.checked=ee()),t}})}Ee([`click`,`input`]);var ww=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`bmp`,`ico`,`avif`]),Tw=new Set([`mp4`,`webm`,`mov`,`mkv`,`avi`,`m4v`]),Ew=new Set([`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`]);function Dw(e){let t=e.split(`.`).pop()?.toLowerCase()??``,n=Ow(e);return n===`image`?`🖼`:n===`video`?`🎬️`:n===`audio`?`🎵`:[`ts`,`tsx`,`mts`,`cts`].includes(t)?`🟦`:[`js`,`mjs`,`cjs`,`jsx`].includes(t)?`🟨`:t===`json`||t===`jsonc`?`🧾`:t===`md`||t===`mdx`||t===`markdown`?`📝`:t===`css`||t===`scss`||t===`less`?`🎨`:t===`html`||t===`htm`||t===`svg`?`🌐️`:[`py`,`pyi`].includes(t)?`🐍`:t===`rs`?`🦀`:t===`go`?`🐹`:t===`java`||t===`kt`||t===`kts`?`☕️`:t===`rb`?`💎`:t===`php`?`🐘`:t===`c`||t===`h`||t===`cpp`||t===`hpp`||t===`cc`?`🧩`:t===`sh`||t===`bash`||t===`zsh`||t===`fish`?`🐚`:t===`sql`?`🗄`:t===`yml`||t===`yaml`||t===`toml`||t===`ini`||t===`conf`?`⚙️`:t===`lock`?`🔒️`:e===`Dockerfile`||t===`dockerfile`?`🐳`:t===`zip`||t===`gz`||t===`tar`||t===`tgz`||t===`bz2`?`📦`:t===`pdf`?`📕`:t===`txt`||t===`log`?`📄`:`·`}function Ow(e){let t=e.split(`.`).pop()?.toLowerCase()??``;return ww.has(t)?`image`:Tw.has(t)?`video`:Ew.has(t)?`audio`:null}var kw=new Map,Aw=e=>{let t=kw.get(e);return t||(t={expanded:new Set,preview:null,media:null,viewMode:`code`},kw.set(e,t)),t},jw=F(`<span class=fsize>`),Mw=F(`<div><span class=ficon></span><span class=fname>`),Nw=F(`<h3 title="the agent's workspace — lazy-loaded, dotfiles hidden; click a folder to expand, a file to preview"style=display:flex;align-items:center;gap:6px>🗂 files <span class=muted style=text-transform:none;letter-spacing:0>· `),Pw=F(`<div class=filebox>`),Fw=F(`<div class=muted style=padding:6px>`),Iw=F(`<img>`),Lw=F(`<div class=mediapreview><div class="meta muted"> preview`),Rw=F(`<button title="rendered markdown">👁 preview`),zw=F(`<button title="edit and save back to the workspace">✎ edit`),Bw=F(`<div class=filetoolbar><button title="syntax-highlighted source">&lt;/> code`),Vw=F(`<div class=fileeditor><textarea class=mono></textarea><div class=filerow-actions><span class=muted> bytes</span><button class=savebtn>`),Hw=F(`<div class=mono style=margin:0;color:var(--dim)>(binary file — inspect it from the terminal)`),Uw=F(`<div class="content mdpreview shikiwrap">`),Ww=F(`<video controls>`),Gw=F(`<audio controls>`);function Kw(e){let t=Aw(e.agentId),[n,r]=y(new Map),[i,a]=y(t.expanded),[o,s]=y(t.preview),c=e=>{t.preview=e,s(e)},l=e=>{t.expanded=e,a(e)},[u,d]=y(t.media),f=e=>{t.media=e,d(e)},[p,m]=y(t.viewMode),h=e=>{t.viewMode=e,m(e)},[g,_]=y(``),[v,ee]=y(localStorage.getItem(`teapot.ignoreMode`)??`dim`),S=()=>{let e=[`dim`,`hide`,`show`],t=e[(e.indexOf(v())+1)%3];ee(t),localStorage.setItem(`teapot.ignoreMode`,t)},C=e=>v()!==`hide`||!e.ignored,[w,E]=y(localStorage.getItem(`teapot.showHidden`)===`1`),D=()=>{let e=!w(),t=[``,...i()];Promise.all(t.map(async t=>({p:t,rows:await ne(t,e)}))).then(t=>{E(e),localStorage.setItem(`teapot.showHidden`,e?`1`:`0`);for(let{p:e,rows:n}of t)n&&re(e,n)})},O=(e,t)=>t.map(t=>({name:String(t.name),path:e?`${e}/${t.name}`:String(t.name),dir:!!t.dir,...typeof t.size==`number`?{size:t.size}:{},...t.ignored?{ignored:!0}:{}}));async function te(e){return ne(e,w())}async function ne(t,n){try{let r=new URLSearchParams;t&&r.set(`path`,t),n&&r.set(`hidden`,`1`);let i=await Y(`/api/agents/${e.agentId}/tree?${r.toString()}`);return O(t,i.entries??[])}catch(e){return _(e.message),null}}let re=(e,n)=>r(r=>{let i=r.get(e);if(!i)return new Map(r).set(e,n);let a=new Map(i.map(e=>[e.path,e])),o=n.map(e=>{let t=a.get(e.path);return t&&t.dir===e.dir&&t.size===e.size&&t.ignored===e.ignored&&t.name===e.name?t:e}).filter(e=>n.some(t=>t.path===e.path)||t.preview?.path===e.path),s=new Map(r);return s.set(e,o),s}),k=``;x(()=>{let t=e.agentId;t!==k&&(k=t,l(new Set),c(null),f(null),r(new Map),te(``).then(e=>{e&&k===t&&r(new Map([[``,e]]))}))});let ie=async e=>{let t=new Set(i());if(t.has(e.path))t.delete(e.path),l(t);else if(t.add(e.path),l(t),!n().has(e.path)){let t=await te(e.path);t&&re(e.path,t)}},[ae,oe]=y(``),[se,ce]=y(!1),[le,ue]=y(``),[de,fe]=y(!1),A=e=>/\.(md|markdown|mdx)$/i.test(e),pe=0,me=async e=>{let t=++pe;oe(``),ce(!0);try{let{highlightChunks:n}=await J(async()=>{let{highlightChunks:e}=await Promise.resolve().then(()=>px);return{highlightChunks:e}},void 0);for await(let r of n(e.path,e.content)){if(pe!==t)return;oe(e=>e+r)}}catch{pe===t&&oe(``)}finally{pe===t&&ce(!1)}};T(()=>{pe++});let he=async(t,n)=>{let r=Ow(t.path);if(r)c({path:t.path,content:``,binary:!0}),f({path:t.path,kind:r}),h(`media`);else try{let r=await Y(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`);f(null),c({path:t.path,content:r.content??``,binary:r.binary,truncated:r.truncated}),ue(r.content??``),h(r.binary?`code`:n),!r.binary&&n!==`md`&&me({path:t.path,content:r.content??``,truncated:r.truncated})}catch(e){bf(`open failed: ${e.message}`)}},ge=async()=>{let t=o();if(t&&!de()){fe(!0);try{await Y(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({content:le(),baseContent:t.content})}),c({...t,content:le()}),bf(`saved ${t.path}`)}catch(e){let n=e.payload,r=n&&typeof n==`object`&&n.error===`file changed on disk`?n:null;r?.current===void 0?bf(`save failed: ${e.message}`):confirm(`This file changed on disk since you opened it.
180
+ `)[0]??``,140),null),R(e,()=>i().data?.ok===!1?` · FAILED`:``,null),e})():lS())];break}case`list_dir`:e=l(`path`)||`.`,n=m();break;case`read_url`:{let r=l(`url`);try{let e=new URL(r);r=e.host+e.pathname}catch{}e=zx(r,70),t=`web`,n=[(()=>{var e=Qx();return R(e,j(N,{get when(){return/^https?:/i.test(l(`url`))},get fallback(){return(()=>{var e=dS();return R(e,()=>zx(l(`url`),80)),e})()},get children(){var e=uS();return b(()=>I(e,`href`,l(`url`))),e}})),e})(),P(m)];break}case`bash_output`:{let r=l(`action`)||`read`;e=`bash_output ${l(`job_id`)||`(?)`}`,t=r,n=m();break}case`load_skill`:{e=`skill: ${l(`name`)}`;let t=c().replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``);n=i()?[(()=>{var e=fS();return b(()=>e.innerHTML=Re(t)),e})(),(()=>{var e=Qx();return R(e,()=>dt(i().data?.durationMs)),e})()]:pS();break}case`save_skill`:{e=`skill: ${l(`name`)}`,t=zx(l(`description`),60);let r=Array.isArray(o.args?.files)?o.args.files.map(e=>e?.name).filter(Boolean):[];n=[P(()=>P(()=>!!r.length)()?(()=>{var e=mS();return e.firstChild,R(e,()=>r.join(`, `),null),e})():null),P(()=>P(()=>!!i())()?(()=>{var e=aS(),t=e.firstChild;return R(e,()=>zx(c(),160),t),R(e,()=>dt(i().data?.durationMs),null),e})():hS())];break}case`search_tools`:{e=`🔎 ${zx(l(`query`)||`(browse)`,60)}`;let r=(()=>{try{let e=JSON.parse(c());return{names:(e.tools??[]).map(e=>`${e.server??`?`}/${e.name??`?`}`),total:e.totalMatches??0}}catch{return{names:[],total:0}}})();t=i()?`${r.total} match${r.total===1?``:`es`}`:null,n=[P(p),P(()=>P(()=>!!i())()?P(()=>!!r.names.length)()?(()=>{var e=gS();return e.firstChild,R(e,()=>r.names.join(`, `),null),e})():_S():null),P(m)];break}case`run_tool`:{let a=Ax(l(`tool_id`)),s=a?.indexOf(`/`)??-1;a&&s>0?r(a.slice(0,s),a.slice(s+1),o.args?.arguments):(e=a||`(no tool_id)`,t=i()?dt(i().data?.durationMs):null,n=[P(p),P(m)]);break}default:{let a=/^mcp__([^_]+(?:_[^_]+)*)__(.+)$/.exec(s);if(a){r(a[1],a[2],o.args);break}e=s,t=i()?dt(i().data?.durationMs):null,n=[P(p),P(m)];break}}}catch{}return{label:e,hint:t,body:n,key:`${i()?.id??`none`}|${e}|${t??``}`}},void 0,{equals:(e,t)=>e.key===t.key});return(()=>{var r=bS(),o=r.firstChild,l=o.firstChild,f=l.nextSibling,p=f.nextSibling;return r.addEventListener(`toggle`,t=>{t.target.open&&e.onResize?.()}),R(l,()=>h().label),R(o,j(N,{get when(){return s===`bash`&&String(t.data?.args?.command??``)!==``},get children(){var e=vS();return R(e,()=>String(t.data?.args?.command??``)),e}}),f),R(o,j(N,{get when(){return t.data?.actor},get children(){var e=yS();return e.firstChild,R(e,()=>String(t.data.actor),null),e}}),f),R(f,(()=>{var e=P(()=>!!i());return()=>e()?h().hint||``:P(()=>!!a())()?`(result missed)`:P(()=>!!(s===`bash`||d()))()?j(Gd,{get startedAt(){return t.ts},inline:!0,get timeoutMs(){return d()}}):`running…`})()),R(p,j(yd,{get text(){return u()},label:`⧉ cmd`,title:`copy the ${s} arguments`}),null),R(p,j(N,{get when(){return i()},get children(){return j(yd,{get text(){return P(()=>!!Od(c()))()?Dd(c()):c()},label:`⧉ out`,title:`copy this tool's full output (escapes removed)`})}}),null),R(r,()=>h().body,null),b(e=>{var t=`embed`+(n?` grouped`:``)+(i()?i().data?.ok===!1?` fail`:` done`:a()?` done`:` running`),o=`${s}${h().hint?` — `+h().hint:``}`;return t!==e.e&&L(r,e.e=t),o!==e.t&&I(r,`title`,e.t=o),e},{e:void 0,t:void 0}),r})()}function fC(e){let t;return x(()=>{e.html,queueMicrotask(()=>Ox(t))}),(()=>{var n=fS(),r=t;return typeof r==`function`?Ae(r,n):t=n,b(()=>n.innerHTML=e.html),n})()}function pC(e){let t=e.e,n=Fx(t),r=()=>Hx(e.prev?.(),t),i=()=>{let n=e.next?.();return!!n&&Hx(t,n)};if(t.type===`fork`){let e=t.data??{};return(()=>{var n=xS(),r=n.firstChild.nextSibling;return r.nextSibling,R(n,()=>String(e.fromBranch??`?`),r),R(n,()=>String(e.newBranch??t.branch),null),n})()}if(t.type===`goal`){let e=Jt(t.data??{});return(()=>{var t=SS(),n=t.firstChild;return R(n,()=>e.label),R(t,j(N,{get when(){return e.hasCard},get children(){return j($t,{get tone(){return P(()=>e.tone===`ok`)()?`ok`:e.tone===`warn`?`warn`:`tool`},get markdown(){return e.markdown},get body(){return e.detail}})}}),null),b(()=>L(t,`goalline `+(e.tone===`err`?`err`:e.tone===`warn`?`warn`:``))),t})()}if(t.type===`audit_step`){let e=String(t.data?.step??``),n=String(t.data?.name??``),r=e===`started`?`🔍️ auditor started`:e===`tool`?`🔍️ auditor → ${n}`:e===`tool_done`?`🔍️ auditor ← ${n} ${t.data?.ok===!1?`failed`:`${String(t.data?.chars??0)} chars`}`:e===`reply`?`🔍️ auditor replied`:`🔍️ auditor`;return e===`reply`&&t.data?.text||e===`tool`&&t.data?.args?(()=>{var n=ES(),i=n.firstChild,a=i.firstChild;return R(a,r),R(i,j(N,{get when(){return e===`tool`&&t.data?.args},get children(){var e=wS();return R(e,()=>ft(String(t.data?.args??``),120)),e}}),null),R(n,j(N,{get when(){return e===`reply`&&t.data?.text},get children(){var e=TS();return R(e,()=>String(t.data?.text??``)),e}}),null),R(n,j(N,{get when(){return e===`tool`&&t.data?.args},get children(){var e=TS();return R(e,()=>String(t.data?.args??``)),e}}),null),n})():(()=>{var e=CS(),t=e.firstChild;return R(t,r),e})()}if(t.type===`todo`)return(()=>{var e=DS(),n=e.firstChild.nextSibling;return n.nextSibling,R(e,()=>String(t.data?.by??`human`),n),e})();if(t.type===`state`)return t.data.from===t.data.to?null:(()=>{var e=OS(),n=e.firstChild;return R(e,()=>t.data.from,n),R(e,()=>t.data.to,null),R(e,(()=>{var e=P(()=>!!t.data.reason);return()=>e()?` — ${t.data.reason}`:``})(),null),b(()=>L(e,`divider-msg`+(t.data.to===`error`?` err`:``))),e})();if(t.type===`system_note`){let e=String(t.data?.event??``);if(e===`runaway-detected`)return(()=>{var e=kS(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;i.nextSibling;var a=n.nextSibling,o=a.firstChild.nextSibling;return o.nextSibling,R(n,()=>String(t.data?.failures),r),R(n,()=>String(t.data?.limit),i),R(a,()=>String(t.data?.lastTool),o),R(a,()=>String(t.data?.lastError??``).slice(0,200),null),b(()=>I(e,`title`,`${t.data?.failures} consecutive tool failures hit the configured limit (${t.data?.limit})`)),e})();if(e===`error-retry`)return(()=>{var e=AS(),n=e.firstChild,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(n,()=>String(t.data?.attempt),r),R(n,()=>Math.round(Number(t.data?.waitMs)/1e3),i),e})();if(e===`background-exit`){let e=t.data?.failed===!0,n=Math.round(Number(t.data?.durationMs??0)/1e3);return(()=>{var r=cS();return L(r,`divider-msg`+(e?` err`:``)),R(r,()=>(e?`⚠ background job `:`✓ background job `)+String(t.data?.jobId??`?`)+` `+(e?`FAILED (exit ${String(t.data?.code??`?`)})`:`finished (${n}s)`)),b(()=>I(r,`title`,String(t.data?.cmd??``))),r})()}return e===`context-compacted`?(()=>{var e=jS(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(e,()=>String(t.data?.tokensBefore??`?`),n),R(e,()=>String(t.data?.tokensAfter??`?`),r),R(e,()=>String(t.data?.mode??``),i),e})():e===`context-compaction-started`?(()=>{var e=MS(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,R(e,()=>String(t.data?.messages??`?`),n),R(e,()=>String(t.data?.tokensBefore??`?`),r),R(e,()=>String(t.data?.reason??`auto`),i),e})():null}return(()=>{var a=LS(),o=a.firstChild,s=o.nextSibling;return R(o,(()=>{var e=P(()=>!!r());return()=>e()?``:n.icon})()),R(s,(()=>{var e=P(()=>!!r());return()=>e()&&(()=>{var e=RS();return b(()=>I(e,`title`,`${Ix(t.ts)} · ${t.branch}`)),e})()})(),null),R(s,j(N,{get when(){return!r()},get children(){var r=IS(),i=r.firstChild,a=i.nextSibling;return R(i,()=>n.name),R(r,j(N,{get when(){return t.data?.actor},get children(){var e=yS();return e.firstChild,R(e,()=>String(t.data.actor),null),e}}),a),R(a,(()=>{var e=P(()=>!!t.data?.pending);return()=>e()?`queued…`:P(()=>!!t.data?.cancelled)()?`withdrawn`:Ix(t.ts)})()),R(r,j(N,{get when(){return e.showBranch},get children(){var e=NS();return R(e,()=>t.branch),e}}),null),R(r,j(N,{get when(){return e.onCancel},get children(){var t=PS();return t.$$click=t=>{t.stopPropagation(),e.onCancel()},t}}),null),R(r,j(N,{get when(){return t.type!==`tool_call`},get children(){return j(yd,{get text(){return Lx(t)},label:`⧉ copy`,title:`copy the RAW text of this message (no markdown rendering)`})}}),null),R(r,j(N,{get when(){return e.onEdit},get children(){var t=FS();return t.$$click=t=>{t.stopPropagation(),e.onEdit()},t}}),null),b(()=>L(i,`author tone-${Px(n.color)}`)),r}}),null),R(s,j(hC,{e:t,get prev(){return e.prev?.()},get res(){return e.res},get orphan(){return e.orphan},get onOption(){return e.onOption},get answeredIds(){return e.answeredIds},get onAnswered(){return e.onAnswered},get agentActive(){return e.agentActive},get onResize(){return e.onResize},get agentId(){return e.agentId}}),null),b(e=>{var s=`msg`+(r()?` grouped`:``)+(i()?` next-grouped`:``)+(t.data?.pending?` pending`:``)+(t.data?.cancelled?` withdrawn`:``),c=t.id,l=String(t.session??``),u=`avatar avghost tone-${Px(n.color)}`+(r()?` ghosted`:``),d=r()?`${Ix(t.ts)} · ${t.branch}`:void 0;return s!==e.e&&L(a,e.e=s),c!==e.t&&I(a,`data-eid`,e.t=c),l!==e.a&&I(a,`data-session`,e.a=l),u!==e.o&&L(o,e.o=u),d!==e.i&&I(o,`title`,e.i=d),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),a})()}function mC(e){let t=()=>(Array.isArray(e.data?.images)?e.data.images:[]).map(e=>typeof e==`string`?e:e?.url).filter(e=>typeof e==`string`&&e.length>0).map(t=>xf(e.agentId,t));return j(N,{get when(){return t().length},get children(){var e=zS();return R(e,j(M,{get each(){return t()},children:e=>(()=>{var t=BS();return t.$$click=()=>nt(e),I(t,`src`,e),t})()})),e}})}function hC(e){let t=e.e;switch(t.type){case`prompt`:{let n=(t.data?.images??[]).map(e=>typeof e==`string`?e:e?.url).filter(e=>typeof e==`string`&&e.length>0).map(t=>xf(e.agentId,t));return[j(fC,{get html(){return ut(String(t.data.text??``))}}),j(N,{get when(){return n.length},get children(){var e=zS();return R(e,j(M,{each:n,children:e=>(()=>{var t=VS();return t.$$click=()=>nt(e),I(t,`src`,e),t})()})),e}})]}case`message`:return[j(N,{get when(){return P(()=>typeof t.data.reasoning==`string`)()&&t.data.reasoning.trim()},get children(){var e=HS(),n=e.firstChild.nextSibling;return R(n,()=>String(t.data.reasoning)),e}}),j(fC,{get html(){return ut(String(t.data.content??``))}}),j(N,{get when(){return t.data.interrupted},get children(){return US()}}),j(N,{get when(){return t.data.final},get children(){var e=WS(),n=e.firstChild;return R(e,j(yd,{get text(){return String(t.data.content??``)}}),n),e}})];case`tool_call`:return j(dC,{e:t,get prev(){return e.prev},get res(){return e.res},get orphan(){return e.orphan},get agentActive(){return e.agentActive},get onResize(){return e.onResize},get agentId(){return e.agentId}});case`tool_result`:{let n=String(t.data.result??``),r=String(t.data.name??`tool`),i=t.data.ok!==!1;return(()=>{var a=KS(),o=a.firstChild,s=o.firstChild,c=o.nextSibling,l=c.nextSibling;return L(a,`embed `+(i?``:`fail`)),R(s,r===`bash`?`$ (bash, call evicted)`:r),R(o,j(yd,{text:n}),null),R(c,n),R(l,()=>dt(t.data.durationMs),null),R(l,()=>r===`bash`?Wx(Ux(t.data.ok,n)):i?``:` · FAILED`,null),R(a,j(N,{get when(){return e.orphan},get children(){return GS()}}),null),b(()=>a.open=e.orphan),a})()}case`decision`:{let e=Array.isArray(t.data?.alternatives)?t.data.alternatives:[];return(()=>{var n=JS(),r=n.firstChild.firstChild.firstChild.nextSibling;return R(n,j(fC,{get html(){return ut(String(t.data?.rationale??``))}}),null),R(n,j(N,{get when(){return e.length},get children(){var t=qS();return t.firstChild,R(t,()=>e.join(` / `),null),t}}),null),b(()=>r.innerHTML=ut(String(t.data?.decision??``))),n})()}case`question`:{let n=Array.isArray(t.data?.options)?t.data.options:[],r=t.data?.callId?String(t.data.callId):``,i=()=>e.answeredIds?.().has(r)??!1;return(()=>{var a=ZS(),o=a.firstChild.firstChild.nextSibling;return R(a,j(N,{get when(){return i()},get children(){return YS()}}),null),R(a,j(N,{get when(){return n.length>0},get children(){var a=XS();return R(a,j(M,{each:n,children:n=>(()=>{var a=QS();return a.$$click=()=>{e.onAnswered?.(r);let i=t.data?.actor;i?Y(`/api/agents/${encodeURIComponent(String(i))}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:n,start:!0})}).then(()=>bf(`→ answered @${String(t.data.actor)}`)).catch(()=>bf(`answer failed`)):e.onOption?.(n)},R(a,n),b(()=>a.disabled=i()),a})()})),a}}),null),R(a,j(uC,{get answered(){return i()},get onOption(){return e.onOption}}),null),b(e=>{var n=`embed question`+(i()?` answered`:``),r=ut(String(t.data?.question??``));return n!==e.e&&L(a,e.e=n),r!==e.t&&(o.innerHTML=e.t=r),e},{e:void 0,t:void 0}),a})()}case`progress`:return(()=>{var e=rC(),n=e.firstChild.firstChild.nextSibling;return R(e,j(N,{get when(){return t.data.goalStatus},get children(){var e=$S(),n=e.firstChild.nextSibling;return R(n,()=>String(t.data.goalStatus)),e}}),null),R(e,j(N,{get when(){return t.data.recent},get children(){var e=eC(),n=e.firstChild.nextSibling;return b(()=>n.innerHTML=ut(String(t.data.recent))),e}}),null),R(e,j(N,{get when(){return t.data.problems},get children(){var e=tC(),n=e.firstChild.nextSibling;return b(()=>n.innerHTML=ut(String(t.data.problems))),e}}),null),R(e,j(N,{get when(){return t.data.next},get children(){var e=nC(),n=e.firstChild.nextSibling;return b(()=>n.innerHTML=ut(String(t.data.next))),e}}),null),b(()=>n.innerHTML=ut(String(t.data.doing??``))),e})();case`error`:return(()=>{var e=iC(),n=e.firstChild;return n.firstChild,R(n,()=>String(t.data.message??``),null),e})();case`compaction`:return t.data.summary?(()=>{var e=cC(),n=e.firstChild.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,R(n,()=>String(t.data.mode??``),r),R(n,()=>Rx(Number(t.data.tokensBefore??0)),i),R(n,()=>Rx(Number(t.data.tokensAfter??0)),a),R(n,(()=>{var e=P(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),R(e,j(N,{get when(){return t.data.summary},get children(){return[sC(),j(fC,{get html(){return ut(String(t.data.summary))}})]}}),null),e})():(()=>{var e=oC(),n=e.firstChild.nextSibling,r=n.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,R(n,()=>String(t.data.mode??``),r),R(n,()=>Rx(Number(t.data.tokensBefore??0)),i),R(n,()=>Rx(Number(t.data.tokensAfter??0)),a),R(n,(()=>{var e=P(()=>!!t.data.summarized);return()=>e()?`${t.data.summarized} summarized`:`${t.data.dropped} dropped`})(),null),R(n,()=>String(t.data.mode??``)===`truncate`?` · older history dropped`:``,null),R(e,j(N,{get when(){return String(t.data.mode??``)===`truncate`},get children(){return aC()}}),null),e})();default:return(()=>{var e=lC();return R(e,()=>ft(JSON.stringify(t.data),200)),e})()}}Ee([`input`,`keydown`,`click`]);var gC=(e,t)=>{let n=String(t??``).trim();return!n||/^\d+$/.test(n)?null:e?.[n]??null},_C=[{key:`openrouter`,label:`OpenRouter`,url:`https://openrouter.ai/api/v1`,model:``,hint:`400+ models behind one key — teapot sends app-attribution headers automatically`},{key:`orcarouter`,label:`OrcaRouter`,url:`https://api.orcarouter.ai/v1`,model:``,hint:`zero-markup routing gateway — 'orcarouter/auto' grades each prompt and picks the model`},{key:`openai`,label:`OpenAI`,url:`https://api.openai.com/v1`,model:``,hint:`your account's models — pick from the list once the endpoint answers`},{key:`opencode-go`,label:`OpenCode Go`,url:`https://opencode.ai/zen/go/v1`,model:``,hint:`OpenCode's open-model subscription — teapot sends the required x-opencode-session header; choose a chat/completions model`},{key:`llamacpp`,label:`llama.cpp server`,url:`http://localhost:8080/v1`,model:``,hint:`free & local — start it with: llama-server -m ./model.gguf (any model name works)`}];function vC(e,t){return e?t===`dark`?{slot:`dark`,key:`teapot.theme.dark`}:{slot:`light`,key:`teapot.theme.light`}:{slot:`fixed`,key:`teapot.theme`}}var yC=F(`<div class=themeeditor><h4 class=cfgsub>your themes</h4><div class=btnrow><button type=button title="copy the theme you are using into a new editable one — presets themselves are never modified">+ duplicate current`),bC=F(`<div class=muted style="margin:6px 0">`),xC=F(`<b>+ duplicate current`),SC=F(`<div class=cfggrid style=margin-top:8px><label class=trow>name<input type=text maxlength=40 placeholder="theme name"></label><label class=trow>appearance<select><option value=dark>dark</option><option value=light>light`),CC=F(`<div class=paletterows>`),wC=F(`<div class=btnrow><button type=button title="put every colour back to the palette this theme was created from">↺ reset palette</button><button type=button title="delete this custom theme">🗑 delete`),TC=F(`<h4 class=cfgsub>background image`),EC=F(`<img sizes=260px alt="current background"decoding=async loading=lazy>`,!0,!1,!1),DC=F(`<span class=bgpick-hint>🖼 replace…`),OC=F(`<div class=bgpreview><span class=muted title="this image is served from the server; the theme stores only its URL">✓ image set</span><div class=btnrow><label class=trow title="how much the image is dimmed so text stays readable">dim<input type=range min=0 max=0.9 step=0.01><span class="muted mono">%</span></label><label title="how much of the background shows through code blocks and tool cards — lower is more transparent">surfaces<input type=range min=0.35 max=1 step=0.01><span class="muted mono">%</span></label><button type=button>✕ remove`),kC=F(`<div class=cfggrid><button type=button></button><input type=file accept=image/* style=display:none>`),AC=F(`<div class=muted style=margin-top:6px;font-size:var(--text-xs)>the image is uploaded to the server and sits behind the panels, dimmed so text stays readable. No size limit — it is a file now, not browser storage.`),jC=F(`<label class=paletterow><input type=color><span class=paletterow-label></span><input class="mono paletterow-hex">`),MC=F(`<span class=bgpick-empty>🖼 choose a background image…`),NC=F(`<div class=muted style=font-size:11.5px;margin-top:4px>⚠ configured default provider <code></code> has no provider row here<!> Add a provider named <code></code> or pick a default below; otherwise agents fall back to the first provider.`),PC=F(`<div class=cfggrid style=margin-top:8px><label class=trow>dark theme →<select class=w100></select></label><label class=trow>light theme →<select class=w100>`),FC=F(`<div class=skilllist>`),IC=F(`<span style=color:var(--err);font-size:13px>`),LC=F(`<form style=display:flex;flex-direction:column;gap:12px;min-height:0><div class=cfgbody><nav class=cfgmenu aria-label="settings sections"></nav><div class=cfgpanel><fieldset><legend>providers</legend><button type=button>+ add custom</button><div style=display:flex;gap:6px;flex-wrap:wrap;margin-top:6px><span class=muted style=font-size:11.5px>quick-add:</span></div><div><label title="agents without an explicit provider use this one"style=display:flex;align-items:center;gap:6px;margin-top:6px>default provider<select><option value>(none — first provider wins)</option></select></label></div></fieldset><fieldset><legend>appearance</legend><div class=cfggrid><label class=trow>follow the system<input type=checkbox></label></div><h4 class=cfgsub>themes</h4></fieldset><fieldset><legend>agent runtime</legend><div class=cfgrow><label style=flex:1>API password<input type=password class=w100></label><span class=muted style=font-size:11.5px;max-width:34ch>bearer token for /api. empty = loopback only.</span></div><div class=cfggrid><label title="auto-compact threshold in k tokens. Leave EMPTY to derive per model (75% of its context window) — recommended, since models differ wildly in window size. Set only to force an absolute cap across all models.">compact budget (k tok)<input type=number min=0 placeholder="(derive: 75% of window)"></label></div><label class=cfgtoggle title="prune old tool output early (at 60% of the budget) instead of waiting for the window to fill. Meant for small-window models — on a large window it throws away context you had room for."><input type=checkbox>short-context mode</label></fieldset><fieldset><legend>MCP servers — external tools, shared by every agent</legend><div class=muted style=font-size:11.5px;margin-bottom:8px>each tool becomes <code class=mono>mcp__server__tool</code> for every agent. saving connects them; the status shown here is live.</div><button type=button>+ add MCP server</button></fieldset><fieldset><legend>scheduled tasks</legend><button type=button>+ add task</button></fieldset><fieldset><legend>archived agents — restore, or delete for good</legend></fieldset><fieldset><legend>agents (read-only — edit config file or use +)</legend></fieldset><fieldset><legend>live update</legend><div class=cfgrow><span class=muted>current version: </span><button type=button class=primarybtn>update & restart</button><span class=muted style=margin-left:8px;font-size:12px>gracefully stops all agents, spawns new process, then reloads this page</span></div></fieldset><fieldset><legend>skills</legend></fieldset><fieldset><legend>help</legend><div class=helpsec><h4 class=cfgsub>this host</h4><div class=featgrid><div class=featrow><b>image downscaling</b><span class=muted></span></div><div class=featrow><b>terminal pty</b><span class=muted></span></div></div></div><div class=helpsec><h4 class=cfgsub>keyboard</h4><div class=helprow><kbd>enter</kbd><span>send (shift+enter for a newline)</span></div><div class=helprow><span class=kbdgroup><kbd>↑</kbd><kbd>↓</kbd></span><span>move between sessions</span></div><div class=helprow><kbd>/</kbd><span>command palette — commands and focus</span></div><div class=helprow><kbd>t</kbd><span>open the terminal panel</span></div><div class=helprow><kbd>d</kbd><span>toggle the details panel</span></div><div class=helprow><kbd>esc</kbd><span>interrupt the running turn</span></div></div><div class=helpsec><h4 class=cfgsub>what the toggles do</h4><div class=helprow><b>auto-continue</b><span>fires after a round only when all hold: the toggle is on, a goal is set and its status is <code>active</code>, and the round ended cleanly (not an error, not stopped). It stops when the goal is marked done, or when you press ■ stop. Sending any prompt starts an idle agent regardless.</span></div><div class=helprow><b>auto-compact</b><span>when the live context passes the budget shown under 📊 runtime, older turns are summarized into notes and the recent stretch is kept verbatim, so work continues without losing the thread. Off means you compact by hand (<code>/compact</code>).</span></div><div class=helprow><b>messages while it works</b><span>anything you send queues up and is handed to the model at its next turn boundary — the timeline shows it as "pending (queued)…" until then. Withdraw it with ✕ cancel while it is still queued.</span></div><div class=helprow><b>👻 ghost sessions</b><span>a session whose workspace directory no longer exists on disk. The session log is intact — recreate the directory and it stops being a ghost.</span></div></div></fieldset></div></div><div class=cfgfoot><button type=submit class=cfgsave>`),RC=F(`<button type=button><span class=cfgmenu-label>`),zC=F(`<div class=cfgrow><input class=cfgname placeholder=name><input placeholder=https://…/v1><input placeholder="default model"><button type=button class=danger title="remove provider">✕</button><div class=cfgkeys><button type=button title="add another key for this provider — they are rotated round-robin, and a rate-limited key is skipped for a minute">+ key`),BC=F(`<button type=button title="remove this key">−`),VC=F(`<div class=cfgkeyrow><input type=password>`),HC=F(`<button type=button>+ `),UC=F(`<option>`),WC=F(`<div class=cfgsub style=margin-bottom:var(--space-1)>`),GC=F(`<div class=themepick>`),KC=F(`<button type=button><span class=themecard-preview></span><span class=themecard-label> ★`),qC=F(`<button type=button><span class=themecard-preview></span><span class=themecard-label>`),JC=F(`<div class=muted style=font-size:12.5px>no MCP servers. add one below — a remote url, or a local command for stdio.`),YC=F(`<input placeholder="command (e.g. npx)">`),XC=F(`<input placeholder="args, space separated">`),ZC=F(`<input type=password placeholder="paste the token"title="sent as Authorization: Bearer <token>"style=flex:1>`),QC=F(`<input placeholder="header name"style="flex:0 1 150px">`),$C=F(`<input type=password placeholder=value style=flex:1>`),ew=F(`<div class=cfgrow><textarea class=mono rows=2 placeholder="{&quot;Authorization&quot;: &quot;Bearer …&quot;, &quot;X-Team&quot;: &quot;infra&quot;}"title="static headers for every request. Use the bearer option unless the server needs something unusual."style=flex:1>`),tw=F(`<button type=button class=mcpauthorize title="start the OAuth flow: a browser tab opens, and the tools appear when you finish">🔑 authorize`),nw=F(`<span class="mcpstate connected"title="an OAuth access token is usable — disconnect it under the server's details">🔑 authorized`),rw=F(`<span>`),iw=F(`<div class=muted style=font-size:11px;color:var(--warn)>`),aw=F(`<div class="cfgcol mcpcard"><div class=cfgrow><input class=cfgname placeholder=name title="the name that appears inside mcp__<name>__ in tool names"><input placeholder="https://example.com/mcp (or leave empty for a stdio command)"><label style=display:flex;gap:3px;align-items:center;white-space:nowrap;color:var(--dim);font-size:11px><input type=checkbox>on</label><button type=button class=danger>✕</button></div><div class=cfgrow><input placeholder="what this server is for — e.g. reverse engineering: decompile, disassemble"title="shown to the model when the MCP catalog is too large to send, so it can search for the right tool instead of guessing keywords"></div><div class=cfgrow><select title="streamable HTTP is the current spec; legacy SSE is the 2024-11-05 handshake; stdio spawns a local process"><option value=http>streamable http</option><option value=sse>legacy http+sse</option><option value=stdio>stdio (local command)</option></select></div><div class=cfgrow><select title="how this server authenticates"><option value=none>no auth</option><option value=bearer>bearer token</option><option value=header>custom header</option><option value=json>headers as JSON (advanced)</option></select></div><div class=cfgrow><button type=button title="connect now and list the tools — nothing is saved">test`),ow=F(`<option value=oauth selected>`),sw=F(`<span class=muted> · needs a grant (🔑 authorize)`),cw=F(`<details class=mcptools-wrap><summary>show <!> tool</summary><ul class=mcptools>`),lw=F(`<div class=mcpdanger><span class=muted>OAuth grant</span><button type=button class=mcpdisconnect title="forget the stored grant (the refresh token is deleted, so authorizing again needs a browser)">disconnect`),uw=F(`<div><div class=mcpresult-head><b>`),dw=F(`<span class=mcptool-desc>`),fw=F(`<li><code class=mono>`),pw=F(`<div class=cfgcol><div class=cfgrow><input placeholder=id><input placeholder="agent id"><input placeholder="every 30m / cron"><label style=display:flex;gap:3px;align-items:center;white-space:nowrap;color:var(--dim);font-size:11px><input type=checkbox>fork</label><button type=button class=danger>✕</button></div><textarea rows=2 placeholder="prompt to send">`),mw=F(`<div class=muted style=font-size:12.5px>nothing archived. 🗄 archive in the controls panel puts an agent away without losing its history.`),hw=F(`<div class="cfgrow archrow"><div class=archmain><b></b><span class=muted> session</span><span class="muted mono ellip"></span></div><button type=button class=archrestore title="bring it back and start it again — its history was never touched">↩ restore</button><button type=button class=danger title="erase the config entry AND every session directory — irreversible">🗑 delete`),gw=F(`<span class=muted>🧩 sub of @`),_w=F(`<div class=cfgrow><b></b><span class=muted>`),vw=F(`<div class=muted>`),yw=F(`<div class=skillbody>`),bw=F(`<div class=skillrow><button type=button class=skillhead title="show the playbook"><span class=skillcaret></span><b class=mono></b><span class=muted>`),xw=F(`<div class="muted skillbody">`);function Sw(e){let[t,n]=y(e.themes().some(t=>t.id===e.paintedId)?e.paintedId:e.themes()[0]?.id??``),r=()=>ur(e.themes(),e.paintedId,t()),[i,a]=y({}),o,s=t=>{let n=r()?.id;if(!n)return;let i=e.themes().map(e=>e.id===n?t(e):e);e.onChange(i)},c=(e,t)=>{let n=cr(t);n&&s(t=>({...t,palette:{...t.palette,[e]:n}}))},l=()=>{let t=e.themes().find(t=>t.id===e.paintedId),r=Yd.find(t=>t.key===e.paintedId),i=t??r??Yd[0],a=getComputedStyle(document.documentElement),o={...Qn};for(let{key:e,cssVar:t}of Xn){let n=cr(a.getPropertyValue(t));n&&(o[e]=n)}let s=ar(e.themes().map(e=>e.id).concat(Yd.map(e=>e.key))),c={id:s,label:`${i.label}${t?``:` copy`}`.slice(0,40),mode:i.mode,palette:o,...t?.backgroundImage?{backgroundImage:t.backgroundImage,backgroundDim:t.backgroundDim,surfaceAlpha:t.surfaceAlpha}:{}};e.onChange([...e.themes(),c]),n(s),e.onPick(s)},u=async t=>{if(t){if(!/^image\//.test(t.type))bf(`that file is ${JSON.stringify(t.type||`unknown`)} — pick an image`);else{bf(`uploading ${t.name} (${Math.round(t.size/1024)}KB)…`);try{let n=await fetch(`/api/assets`,{method:`POST`,headers:{"content-type":t.type},body:t}).then(async e=>({ok:e.ok,body:await e.json().catch(()=>null)}));if(!n.ok||!n.body?.url){bf(n.body?.error??`upload failed`);return}s(e=>({...e,backgroundImage:n.body.url,backgroundImageBytes:n.body.bytes}));let i=r()?.id;i&&e.onPick(i),bf(`background image set`)}catch(e){bf(`upload failed: ${e.message}`)}}}};return(()=>{var t=yC(),d=t.firstChild.nextSibling.firstChild;return d.$$click=l,R(t,j(N,{get when(){return P(()=>!!(r()&&e.themes().some(t=>t.id===e.paintedId)))()?r():null},get fallback(){return(()=>{var t=bC();return R(t,(()=>{var t=P(()=>e.themes().length===0);return()=>t()?[`no custom themes yet — press `,xC(),` to start from the palette you are using.`]:[`the editor shows when one of your themes is the one on screen — pick one under "your themes" above (or press `,xC(),`).`]})()),t})()},children:t=>[(()=>{var e=SC(),t=e.firstChild,n=t.firstChild.nextSibling,i=t.nextSibling.firstChild.nextSibling;return n.$$input=e=>s(t=>({...t,label:e.currentTarget.value})),i.addEventListener(`change`,e=>s(t=>({...t,mode:e.currentTarget.value}))),b(()=>n.value=r().label),b(()=>i.value=r().mode),e})(),(()=>{var e=CC();return R(e,j(M,{each:Xn,children:e=>(()=>{var t=jC(),n=t.firstChild,o=n.nextSibling,s=o.nextSibling;return n.$$input=t=>c(e.key,t.currentTarget.value),R(o,()=>e.label),s.addEventListener(`blur`,()=>a(t=>{let n={...t};return delete n[e.key],n})),s.$$input=t=>{let n=t.currentTarget.value;a(t=>({...t,[e.key]:n})),c(e.key,n)},I(s,`spellcheck`,!1),b(()=>I(t,`title`,e.cssVar)),b(()=>n.value=cr(r().palette[e.key])??`#000000`),b(()=>s.value=i()[e.key]??r().palette[e.key]),t})()})),e})(),(()=>{var t=wC(),i=t.firstChild,a=i.nextSibling;return i.$$click=()=>s(e=>({...e,palette:{...Qn}})),a.$$click=()=>{let t=r()?.id;t&&(e.onChange(e.themes().filter(e=>e.id!==t)),n(e.themes().find(e=>e.id!==t)?.id??``))},t})(),TC(),(()=>{var e=kC(),t=e.firstChild,n=t.nextSibling;t.$$click=()=>o?.click(),R(t,j(N,{get when(){return r().backgroundImage},get fallback(){return MC()},get children(){return[(()=>{var e=EC();return b(t=>{var n=cn(r().backgroundImage),i=sn(r().backgroundImage);return n!==t.e&&I(e,`src`,t.e=n),i!==t.t&&I(e,`srcset`,t.t=i),t},{e:void 0,t:void 0}),e})(),DC()]}})),n.addEventListener(`change`,e=>{e.stopPropagation(),u(e.currentTarget.files?.[0]),e.currentTarget.value=``}),n.$$input=e=>e.stopPropagation();var i=o;return typeof i==`function`?Ae(i,n):o=n,R(e,j(N,{get when(){return r().backgroundImage},get children(){var e=OC(),t=e.firstChild;t.firstChild;var n=t.nextSibling.firstChild,i=n.firstChild.nextSibling,a=i.nextSibling,o=a.firstChild,c=n.nextSibling,l=c.firstChild.nextSibling,u=l.nextSibling,d=u.firstChild,f=c.nextSibling;return R(t,()=>{let e=r()?.backgroundImageBytes;return e?` — ${Math.max(1,Math.round(e/1024))} KB`:``},null),i.$$input=e=>s(t=>({...t,backgroundDim:Number(e.currentTarget.value)})),R(a,()=>Math.round((r().backgroundDim??.55)*100),o),l.$$input=e=>s(t=>({...t,surfaceAlpha:Number(e.currentTarget.value)})),R(u,()=>Math.round((r().surfaceAlpha??.82)*100),d),f.$$click=()=>s(e=>({...e,backgroundImage:void 0})),b(()=>i.value=r().backgroundDim??.55),b(()=>l.value=r().surfaceAlpha??.82),e}}),null),b(e=>{var n=`bgpick`+(r().backgroundImage?` has`:``),i=r().backgroundImage?`click to replace this background image (PNG/JPG/WebP)`:`choose a background image (PNG/JPG/WebP)`;return n!==e.e&&L(t,e.e=n),i!==e.t&&I(t,`title`,e.t=i),e},{e:void 0,t:void 0}),e})(),AC()]}),null),t})()}function Cw(e){let t=(e,t)=>{let n=Array.isArray(t?.apiKeys)&&t.apiKeys.length?t.apiKeys.filter(e=>typeof e==`string`&&e.trim()):t?.apiKey?[String(t.apiKey)]:[``];return{name:e,baseUrl:t?.baseUrl??``,apiKeys:n.length?n:[``],model:t?.model??``}},[n,r]=y(Object.entries(e.cfg.providers??{}).map(([e,n])=>t(e,n))),[i,a]=y(e.cfg.defaultProvider??``),o=()=>e.cfg.defaultProvider??``,s=()=>{let e=[...new Set(n().map(e=>e.name.trim()).filter(Boolean))],t=i();return t&&!e.includes(t)&&e.push(t),e},c=()=>{let e=i();return e?n().some(t=>t.name.trim()===e)?``:e:``},[l,u]=y(Math.round((e.cfg.progressIntervalMs??6e5)/6e4)),[d,f]=y(e.cfg.progressMinChars??4e3),[p,m]=y(e.cfg.contextTokenBudget==null?null:Math.round(e.cfg.contextTokenBudget/1e3)),[h,g]=y(e.cfg.contextWindowTokens?Math.round(e.cfg.contextWindowTokens/1e3):0),[_,v]=y(e.cfg.maxSpawnDepth??3),[ee,S]=y(!!e.cfg.shortContext),[C,w]=y(``),[T,E]=y(!1),[D,O]=y((e.cfg.tasks??[]).map(e=>({...e}))),[te,ne]=y((e.cfg.mcpServers??[]).map(e=>({...e}))),[re,k]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>[t,e.headers?JSON.stringify(e.headers):``]))),[ie,ae]=y({}),[oe,se]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=e.headers??{},r=Object.keys(n);if(!r.length)return[t,`none`];let i=r.length===1?r[0]:``;return i===`Authorization`&&/^Bearer /i.test(n[i]??``)?[t,`bearer`]:[t,r.length===1?`header`:`json`]}))),[ce,le]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=e.headers??{},r=Object.keys(n);if(r.length!==1)return[t,``];let i=r[0];return[t,i===`Authorization`?(n[i]??``).replace(/^Bearer /i,``):n[i]??``]}))),[ue,de]=y(Object.fromEntries((e.cfg.mcpServers??[]).map((e,t)=>{let n=Object.keys(e.headers??{}),r=n.length===1?n[0]:``;return[t,r&&r!==`Authorization`?r:``]}))),[fe,A]=y({}),pe={},me=async(e,t)=>{if(!te()[e])return;let n=await Y(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}).catch(()=>null);te()[e]&&n&&A(t=>({...t,[e]:n.ok?{kind:`ok`,text:`${n.tools?.length??0} tools`}:{kind:`err`,text:n.needsOAuth?`needs authorization — press 🔑`:n.error??`no response`,...n.needsOAuth?{needsOAuth:!0}:{}}}))},[he,ge]=y({}),[_e,ve]=y({}),ye=e=>{let t=gC(_e(),e);return t&&(t.required||t.authorized)?t:null},be=async()=>{let e=await Y(`/api/mcp`).catch(()=>null);ge(Object.fromEntries((e?.states??[]).map(e=>[e.name,e])))},xe=async e=>{let t=String(e??``).trim();if(!t)return;let n=await Y(`/api/mcp/oauth/status?name=${encodeURIComponent(t)}`).catch(()=>null);n&&!n.error&&ve(e=>({...e,[t]:n}))},Ce=async(t,n)=>{if(!n.name){A(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}A(e=>({...e,[t]:{kind:`testing`,text:`discovering the authorization server…`}}));let r=await Y(`/api/mcp/oauth/start`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:n.name,url:n.url})}).catch(()=>null);if(r?.alreadyAuthorized){A(e=>({...e,[t]:{kind:`ok`,text:`already authorized`}})),await xe(n.name),await be();return}if(!r?.ok||!r.url){A(e=>({...e,[t]:{kind:`err`,text:r?.error??`no response`}})),await xe(n.name);return}window.open(r.url,`_blank`,`noopener`),A(e=>({...e,[t]:{kind:`testing`,text:`waiting for you to finish in the browser…`}}));let i=Date.now()+3e5;for(;Date.now()<i;){await new Promise(e=>setTimeout(e,1e3));let r=await Y(`/api/mcp/oauth/status?name=${encodeURIComponent(n.name)}`).catch(()=>null);if(r&&!r.error){if(ve(e=>({...e,[n.name]:r})),r.authorized){A(e=>({...e,[t]:{kind:`ok`,text:`authorized — the tools are available now`}})),await be(),e.onSaved();return}if(r.flow?.phase===`error`){A(e=>({...e,[t]:{kind:`err`,text:r.flow.message??r.lastError??`authorization failed`}}));return}}}A(e=>({...e,[t]:{kind:`err`,text:`authorization timed out`}}))};x(()=>{F()===`mcp`&&(be(),te().forEach((e,t)=>{e.name&&xe(e.name)}))});let[we,Te]=y(``),[F,Ee]=y(`providers`),De=(t,n)=>{let{slot:r}=vC(e.theme.auto(),n);r===`dark`?Ge(t):r===`light`?qe(t):Ve(t)},Oe=t=>e.theme.auto()?t===e.theme.dark()||t===e.theme.light():t===e.theme.activeId(),[ke,Ae]=y([]),je=async()=>{let e=await Y(`/api/archived`).catch(()=>null);Ae(e?.agents??[])},Me=()=>ke().filter(e=>!e.parent);x(()=>{F()===`archive`&&je()});let Ne=[{key:`providers`,label:`🧦 providers`,hint:`endpoints, API keys, default models`},{key:`appearance`,label:`🎨 appearance`,hint:`theme, custom palettes, background image`},{key:`runtime`,label:`⚙️ runtime`,hint:`context budget, retries, spawn depth`},{key:`tasks`,label:`⏰ scheduled tasks`,hint:`cron prompts run against an agent`},{key:`mcp`,label:`🔌 MCP servers`,hint:`external tool servers exposed to every agent`},{key:`archive`,label:`🗄 archive`,hint:`agents you put away — restore or delete for good`},{key:`agents`,label:`👥 agents`,hint:`what exists (read-only)`},{key:`update`,label:`⬆️ live update`,hint:`restart onto a newer build`},{key:`skills`,label:`🧠 skills`,hint:`reusable playbooks available to the selected session`},{key:`help`,label:`❔️ help`,hint:`keyboard shortcuts and what each toggle does`}],Pe=()=>(e.cfg.agents??[]).map(e=>e.id),Fe=()=>e.theme.themes(),Ie=()=>e.theme.activeId(),Le={auto:localStorage.getItem(`teapot.theme.auto`)===`1`,dark:localStorage.getItem(`teapot.theme.dark`)??`dark`,light:localStorage.getItem(`teapot.theme.light`)??`light`,fixed:localStorage.getItem(`teapot.theme`)??`dark`},Re=y(Le),ze=Re[0],Be=t=>{let n={...ze(),...t};Re[1](n),e.theme.setAuto(n.auto),e.theme.setDark(n.dark),e.theme.setLight(n.light),e.theme.setActive(n.fixed);let r=t.dark??t.light??t.fixed;r&&e.theme.preview(r)},Ve=e=>Be({fixed:e}),He=()=>ze().auto,Ue=e=>Be({auto:e}),We=()=>ze().dark,Ge=e=>Be({dark:e}),Ke=()=>ze().light,qe=e=>Be({light:e}),Je=t=>e.theme.setThemes(t),Ye=()=>{let t=Le;e.theme.setAuto(t.auto),e.theme.setDark(t.dark),e.theme.setLight(t.light),e.theme.setActive(t.fixed),e.theme.preview(null)},Xe=e=>$n[e]??Qn,Ze=()=>{let e={};for(let t of n()){if(!t.name.trim())return Te(`provider name is required`),null;if(t.baseUrl&&!/^https?:\/\//.test(t.baseUrl))return Te(`provider ${t.name}: baseUrl must start with http(s)://`),null;let n=t.apiKeys.map(e=>e.trim()).filter(Boolean);e[t.name.trim()]={baseUrl:t.baseUrl,...n.length?{apiKeys:n,apiKey:n[0]}:{},...t.model?{model:t.model}:{}}}return e},[Qe,$e]=y(`idle`),et=e=>{Te(e),$e(e=>e===`saving`?`idle`:e)},tt=async t=>{t.preventDefault(),Te(``),$e(`saving`);let n=Ze();if(!n)return $e(`idle`);let r=D().filter(e=>e.id?.trim()||e.prompt?.trim()).map((e,t)=>({id:e.id?.trim()||`task-${t+1}`,agent:e.agent,schedule:e.schedule,prompt:e.prompt,...e.forked?{forked:!0}:{}}));for(let e of r){if(!e.agent)return et(`task "${e.id}": agent is required`);if(!e.schedule?.trim())return et(`task "${e.id}": schedule is required`)}let a=[],o=new Set;for(let e of te()){let t=String(e.name??``).trim(),n=String(e.url??``).trim(),r=e.transport??`http`,i=String(e.command??``).trim();if(t||n||i){if(!t)return et(`MCP: a server needs a name`);if(o.has(t))return et(`MCP: two servers are named "${t}"`);if(o.add(t),r===`stdio`?!i:!n)return et(`MCP "${t}": ${r===`stdio`?`a command is`:`a url is`} required`);a.push({name:t,transport:r,enabled:e.enabled!==!1,...String(e.description??``).trim()?{description:String(e.description).trim()}:{},...n?{url:n}:{},...r===`stdio`?{command:i,...e.args?.length?{args:e.args}:{}}:{},...e.headers&&Object.keys(e.headers).length?{headers:e.headers}:{}})}}try{await Y(`/api/config`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({providers:n,defaultProvider:i()||void 0,progressIntervalMs:Math.max(1,l())*6e4,progressMinChars:Math.max(100,d()),...p()==null?{}:{contextTokenBudget:Math.max(1,p())*1e3},...h()>0?{contextWindowTokens:h()*1e3}:{},maxSpawnDepth:Math.max(0,_()),shortContext:ee(),...T()?{password:C()}:{},tasks:r,mcpServers:a})}),await be(),await Promise.all(a.map((e,t)=>e.name?xe(e.name):Promise.resolve())),setTimeout(()=>{be(),a.forEach((e,t)=>{e.name&&xe(e.name)})},1200),e.onSaved();let t=new Set(a.map(e=>e.name).filter(Boolean)),o=te().filter(e=>{let n=String(e.name??``).trim();return t.has(n)&&_e()[n]?.required&&!_e()[n]?.authorized}).filter(t=>!e.announcedOAuth.has(String(t.name??``)));if(o.length>0){for(let t of o)e.announcedOAuth.add(String(t.name??``));bf(`${o.map(e=>String(e.name??``).trim()).filter(Boolean).join(`, `)||`a saved MCP server`} needs authorization — 🔑 authorize in MCP servers`)}e.theme.commitAppearance(ze()),e.theme.preview(null),$e(`saved`),Object.assign(Le,ze()),setTimeout(()=>{$e(`idle`),e.onClose()},400)}catch(e){Te(e.message),$e(`error`),setTimeout(()=>$e(`idle`),1600)}};return j(bd,{title:`settings`,onClose:()=>{Ye(),e.onClose()},get children(){var t=LC(),x=t.firstChild,T=x.firstChild,ge=T.nextSibling.firstChild,ve=ge.firstChild.nextSibling,be=ve.nextSibling;be.firstChild;var ke=be.nextSibling.firstChild.firstChild.nextSibling;ke.firstChild;var Ae=ge.nextSibling,Le=Ae.firstChild.nextSibling,Re=Le.firstChild.firstChild.nextSibling,ze=Le.nextSibling,Be=Ae.nextSibling,Ye=Be.firstChild.nextSibling,Ze=Ye.firstChild.firstChild.nextSibling,$e=Ye.nextSibling,et=$e.firstChild,nt=et.firstChild.nextSibling,rt=$e.nextSibling.firstChild,it=Be.nextSibling,at=it.firstChild.nextSibling.nextSibling,ot=it.nextSibling,st=ot.firstChild.nextSibling,ct=ot.nextSibling;ct.firstChild;var lt=ct.nextSibling;lt.firstChild;var dt=lt.nextSibling,ft=dt.firstChild.nextSibling.firstChild;ft.firstChild;var mt=ft.nextSibling,ht=dt.nextSibling;ht.firstChild;var gt=ht.nextSibling,_t=gt.firstChild.nextSibling.firstChild.nextSibling.firstChild,vt=_t.firstChild.nextSibling,yt=_t.nextSibling.firstChild.nextSibling,bt=x.nextSibling,xt=bt.firstChild;return t.addEventListener(`submit`,tt),R(T,j(M,{each:Ne,children:e=>(()=>{var t=RC(),n=t.firstChild;return t.$$click=()=>Ee(e.key),R(n,()=>e.label),b(n=>{var r=`cfgmenu-item`+(F()===e.key?` on`:``),i=e.hint,a=F()===e.key?`page`:void 0;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-current`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})),R(ge,j(Se,{get each(){return n()},children:(e,t)=>(()=>{var i=zC(),a=i.firstChild,o=a.nextSibling,s=o.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.firstChild;return a.$$input=e=>r(n().map((n,r)=>r===t?{...n,name:e.currentTarget.value}:n)),o.$$input=e=>r(n().map((n,r)=>r===t?{...n,baseUrl:e.currentTarget.value}:n)),s.$$input=e=>r(n().map((n,r)=>r===t?{...n,model:e.currentTarget.value}:n)),c.$$click=()=>r(n().filter((e,n)=>n!==t)),R(l,j(M,{get each(){return e().apiKeys},children:(i,a)=>(()=>{var o=VC(),s=o.firstChild;return s.$$input=e=>r(n().map((n,r)=>r===t?{...n,apiKeys:n.apiKeys.map((t,n)=>n===a()?e.currentTarget.value:t)}:n)),s.value=i,R(o,j(N,{get when(){return e().apiKeys.length>1},get children(){var e=BC();return e.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:e.apiKeys.filter((e,t)=>t!==a())}:e)),e}}),null),b(()=>I(s,`placeholder`,a()===0?`api key`:`api key (backup)`)),o})()}),u),u.$$click=()=>r(n().map((e,n)=>n===t?{...e,apiKeys:[...e.apiKeys,``]}:e)),b(()=>a.value=e().name),b(()=>o.value=e().baseUrl),b(()=>s.value=e().model),i})()}),ve),ve.$$click=()=>r([...n(),{name:``,baseUrl:``,apiKeys:[``],model:``}]),R(be,j(M,{each:_C,children:e=>(()=>{var t=HC();return t.firstChild,t.$$click=()=>{let t=n().filter(t=>t.name!==e.key);r([...t,{name:e.key,baseUrl:e.url,apiKeys:[``],model:e.model}]),i()||a(e.key)},R(t,()=>e.label,null),b(()=>I(t,`title`,`fill a ${e.label} row — ${e.url}${e.model?` (model: ${e.model})`:``}`)),t})()}),null),ke.addEventListener(`change`,e=>a(e.currentTarget.value)),R(ke,j(M,{get each(){return s()},children:e=>(()=>{var t=UC();return t.value=e,R(t,e),t})()}),null),R(ge,j(N,{get when(){return c()},get children(){var e=NC(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling,r=n.nextSibling.nextSibling;return R(t,c),R(e,()=>c()===o()?` — the dropdown above cannot show it.`:` — it was replaced by your selection.`,n),R(r,c),e}}),null),Re.addEventListener(`change`,e=>{Ue(e.currentTarget.checked)}),R(Ae,j(N,{get when(){return He()},get children(){var e=PC(),t=e.firstChild,n=t.firstChild.nextSibling,r=t.nextSibling.firstChild.nextSibling;return n.addEventListener(`change`,e=>{Ge(e.currentTarget.value)}),R(n,j(M,{get each(){return Fe().filter(e=>e.mode===`dark`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat(Yd.filter(e=>e.mode===`dark`))},children:e=>(()=>{var t=UC();return R(t,()=>e.label),b(()=>t.value=e.key),t})()})),r.addEventListener(`change`,e=>{qe(e.currentTarget.value)}),R(r,j(M,{get each(){return Fe().filter(e=>e.mode===`light`).map(e=>({key:e.id,label:`${e.label} (custom)`})).concat(Yd.filter(e=>e.mode===`light`))},children:e=>(()=>{var t=UC();return R(t,()=>e.label),b(()=>t.value=e.key),t})()})),b(()=>n.value=We()),b(()=>r.value=Ke()),e}}),ze),R(Ae,j(M,{each:[{mode:`dark`,title:`dark themes`},{mode:`light`,title:`light themes`}],children:e=>j(N,{get when(){return[...Fe(),...Yd].some(t=>t.mode===e.mode)},get children(){return[(()=>{var t=WC();return R(t,()=>e.title),t})(),(()=>{var t=GC();return R(t,j(M,{get each(){return Fe().filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=KC(),n=t.firstChild,r=n.nextSibling,i=r.firstChild;return t.$$click=()=>De(e.id,e.mode),R(n,j(gf,{get palette(){return e.palette},get backgroundImage(){return e.backgroundImage},get surfaceAlpha(){return e.surfaceAlpha},get backgroundDim(){return e.backgroundDim}})),R(r,()=>e.label,i),b(n=>{var r=`themecard`+(Oe(e.id)?` on`:``),i=`${e.label} (custom)${e.backgroundImage?` · with a background image`:``}`,a=Oe(e.id);return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),R(t,j(M,{get each(){return Yd.filter(t=>t.mode===e.mode)},children:e=>(()=>{var t=qC(),n=t.firstChild,r=n.nextSibling;return t.$$click=()=>De(e.key,e.mode),R(n,j(gf,{get palette(){return Xe(e.key)}})),R(r,()=>e.label),b(n=>{var r=`themecard`+(Oe(e.key)?` on`:``),i=`${e.label} (${e.mode})`,a=Oe(e.key);return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),a!==n.a&&I(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),t})()]}})}),null),R(Ae,j(Sw,{themes:Fe,get paintedId(){return e.theme.paintedId()},onChange:e=>{let t=rr(e),n=e;if(!t.ok){let t=e.map(e=>e.backgroundImage?{...e,backgroundImage:void 0,backgroundDim:void 0,surfaceAlpha:void 0,backgroundImageBytes:void 0}:e),r=rr(t);if(r.ok)n=t,bf(`storage was full — saved without the background image(s)`);else{bf(r.error??`could not save theme`);return}}Je(n);let r=e=>n.some(t=>t.id===e)||Yd.some(t=>t.key===e);r(Ie())||(Ve(`dark`),localStorage.setItem(`teapot.theme`,`dark`)),r(We())||(Ge(`dark`),localStorage.setItem(`teapot.theme.dark`,`dark`)),r(Ke())||(qe(`light`),localStorage.setItem(`teapot.theme.light`,`light`))},onPick:e=>{let t=Fe().find(t=>t.id===e)?.mode??Yd.find(t=>t.key===e)?.mode??`dark`,n=vC(He(),t);n.slot===`dark`?Ge(e):n.slot===`light`?qe(e):Ve(e)}}),null),Ze.$$input=e=>{w(e.currentTarget.value),E(!0)},R($e,j(hf,{label:`progress interval (min)`,get value(){return l()},onValue:e=>u(e),hint:`how often the harness asks for a progress report`}),et),R($e,j(hf,{label:`progress min chars`,get value(){return d()},onValue:e=>f(e),hint:`progress prompts wait for this much real output`}),et),nt.$$input=e=>m(e.currentTarget.value===``?null:Number(e.currentTarget.value)),R($e,j(hf,{label:`context window (k tok)`,get value(){return h()},onValue:e=>g(e),hint:`model's real window — 0/blank hides the % gauge`}),null),R($e,j(hf,{label:`max spawn depth`,get value(){return _()},onValue:e=>v(e),hint:`sub-agent nesting limit (0 = no spawning)`}),null),rt.addEventListener(`change`,e=>S(e.currentTarget.checked)),R(it,j(N,{get when(){return te().length>0},get fallback(){return JC()},get children(){return j(Se,{get each(){return te()},children:(e,t)=>{let n=()=>he()[e().name],r=e=>ne(te().map((n,r)=>r===t?{...n,...e}:n));return(()=>{var i=aw(),a=i.firstChild,o=a.firstChild,s=o.nextSibling,c=s.nextSibling,l=c.firstChild,u=c.nextSibling,d=a.nextSibling,f=d.firstChild,p=d.nextSibling,m=p.firstChild,h=p.nextSibling,g=h.firstChild,_=g.firstChild,v=h.nextSibling,ee=v.firstChild;return o.$$input=e=>r({name:e.currentTarget.value}),s.$$input=e=>{r({url:e.currentTarget.value});let n=e.currentTarget.value.trim();clearTimeout(pe[t]),/^https?:\/\//.test(n)&&(pe[t]=setTimeout(()=>{me(t,{...te()[t],url:n})},700))},l.addEventListener(`change`,e=>r({enabled:e.currentTarget.checked})),u.$$click=()=>ne(te().filter((e,n)=>n!==t)),f.$$input=e=>r({description:e.currentTarget.value}),m.addEventListener(`change`,e=>r({transport:e.currentTarget.value})),R(p,j(N,{get when(){return e().transport===`stdio`},get children(){return[(()=>{var t=YC();return t.$$input=e=>r({command:e.currentTarget.value}),b(()=>t.value=e().command??``),t})(),(()=>{var t=XC();return t.$$input=e=>r({args:e.currentTarget.value.split(` `).filter(Boolean)}),b(()=>t.value=(e().args??[]).join(` `)),t})()]}}),null),g.addEventListener(`change`,e=>{let n=e.currentTarget.value;if(se(e=>({...e,[t]:n})),n===`none`)r({headers:void 0});else if(n===`bearer`){let e=ce()[t]??``;r({headers:e?{Authorization:`Bearer ${e}`}:void 0})}else if(n===`header`){let e=ue()[t]??``,n=ce()[t]??``;r({headers:e&&n?{[e]:n}:void 0})}}),R(g,j(N,{get when(){return ye(String(e().name??``))},children:e=>(()=>{var t=ow();return R(t,()=>e().authorized?`OAuth — authorized`:`OAuth — authorization needed`),t})()}),_),R(h,j(N,{get when(){return oe()[t]===`bearer`},get children(){var e=ZC();return e.$$input=e=>{let n=e.currentTarget.value;le(e=>({...e,[t]:n})),r({headers:n?{Authorization:`Bearer ${n}`}:void 0})},b(()=>e.value=ce()[t]??``),e}}),null),R(h,j(N,{get when(){return oe()[t]===`header`},get children(){return[(()=>{var e=QC();return e.$$input=e=>{let n=e.currentTarget.value;de(e=>({...e,[t]:n}));let i=ce()[t]??``;r({headers:n&&i?{[n]:i}:void 0})},b(()=>e.value=ue()[t]??``),e})(),(()=>{var e=$C();return e.$$input=e=>{let n=e.currentTarget.value;le(e=>({...e,[t]:n}));let i=ue()[t]??``;r({headers:i&&n?{[i]:n}:void 0})},b(()=>e.value=ce()[t]??``),e})()]}}),null),R(i,j(N,{get when(){return oe()[t]===`json`},get children(){var e=ew(),n=e.firstChild;return n.$$input=e=>{let n=e.currentTarget.value;if(k(e=>({...e,[t]:n})),!n.trim())r({headers:void 0});else try{let e=JSON.parse(n);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`not an object`);r({headers:e}),ae(e=>({...e,[t]:``}))}catch{ae(e=>({...e,[t]:`must be a JSON object — not applied`}))}},b(()=>n.value=re()[t]??``),e}}),v),ee.$$click=async()=>{let e=te()[t];if(!e.name){A(e=>({...e,[t]:{kind:`err`,text:`give it a name first`}}));return}A(e=>({...e,[t]:{kind:`testing`,text:`connecting…`}}));let n=await Y(`/api/mcp/test`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}).catch(()=>null);A(e=>({...e,[t]:n?.ok?{kind:`ok`,text:`${n.tools?.length??0} tool${n.tools?.length===1?``:`s`}`,tools:n.tools??[]}:{kind:`err`,text:n?.error??`no response`,...n?.needsOAuth?{needsOAuth:!0}:{}}})),n?.ok||await xe(e.name)},R(v,j(N,{get when(){return P(()=>!!gC(_e(),String(e().name??``))?.required)()&&!gC(_e(),String(e().name??``))?.authorized},get children(){var n=tw();return n.$$click=()=>void Ce(t,e()),n}}),null),R(v,j(N,{get when(){return gC(_e(),String(e().name??``))?.authorized},get children(){return nw()}}),null),R(v,j(N,{get when(){return n()},get children(){var e=rw();return R(e,(()=>{var e=P(()=>n()?.status===`connected`);return()=>e()?`● ${n()?.tools} tools`:P(()=>n()?.status===`error`)()?`● error`:n()?.status===`disabled`?`● off`:`● idle`})()),b(t=>{var r=`mcpstate `+(n()?.status??``),i=n()?.lastError??``;return r!==t.e&&L(e,t.e=r),i!==t.t&&I(e,`title`,t.t=i),t},{e:void 0,t:void 0}),e}}),null),R(i,j(N,{get when(){return ie()[t]},get children(){var e=iw();return R(e,()=>ie()[t]),e}}),null),R(i,j(N,{get when(){return fe()[t]},children:n=>(()=>{var r=uw(),i=r.firstChild,a=i.firstChild;return R(a,()=>n().text),R(i,j(N,{get when(){return n().needsOAuth},get children(){return sw()}}),null),R(r,j(N,{get when(){return(n().tools?.length??0)>0},get children(){var e=cw(),t=e.firstChild,r=t.firstChild.nextSibling;r.nextSibling;var i=t.nextSibling;return R(t,()=>n().tools?.length,r),R(t,()=>n().tools?.length===1?``:`s`,null),R(i,j(M,{get each(){return n().tools??[]},children:e=>(()=>{var t=fw(),n=t.firstChild;return R(n,()=>e.name),R(t,j(N,{get when(){return e.description},get children(){var t=dw();return R(t,()=>e.description),t}}),null),b(()=>I(t,`title`,e.description??``)),t})()})),e}}),null),R(r,j(N,{get when(){return gC(_e(),String(e().name??``))?.authorized},get children(){var n=lw(),r=n.firstChild.nextSibling;return r.$$click=async()=>{confirm(`Disconnect ${e().name}?\n\nThe stored OAuth grant is deleted and you will have to authorize again in a browser.`)&&(await Y(`/api/mcp/oauth/disconnect`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:e().name})}).catch(()=>{}),await xe(e().name),A(e=>({...e,[t]:{kind:`ok`,text:`disconnected`}})))},n}}),null),b(()=>L(r,`mcpresult `+(n().kind===`err`?`err`:`ok`))),r})()}),null),b(()=>o.value=e().name),b(()=>s.value=e().url??``),b(()=>l.checked=e().enabled!==!1),b(()=>f.value=e().description??``),b(()=>m.value=e().transport??`http`),b(()=>g.value=ye(String(e().name??``))?`oauth`:oe()[t]??`none`),i})()}})}}),at),at.$$click=()=>ne([...te(),{name:``,url:``,transport:`http`,enabled:!0}]),R(ot,j(N,{get when(){return D().length>0},get children(){return j(Se,{get each(){return D()},children:(e,t)=>(()=>{var n=pw(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling,c=s.firstChild,l=s.nextSibling,u=r.nextSibling;return i.$$input=e=>O(D().map((n,r)=>r===t?{...n,id:e.currentTarget.value}:n)),a.$$input=e=>O(D().map((n,r)=>r===t?{...n,agent:e.currentTarget.value}:n)),o.$$input=e=>O(D().map((n,r)=>r===t?{...n,schedule:e.currentTarget.value}:n)),c.addEventListener(`change`,e=>O(D().map((n,r)=>r===t?{...n,forked:e.currentTarget.checked}:n))),l.$$click=()=>O(D().filter((e,n)=>n!==t)),u.$$input=e=>O(D().map((n,r)=>r===t?{...n,prompt:e.currentTarget.value}:n)),b(()=>i.value=e().id),b(()=>a.value=e().agent),b(()=>o.value=e().schedule),b(()=>c.checked=!!e().forked),b(()=>u.value=e().prompt),n})()})}}),st),st.$$click=()=>O([...D(),{id:``,agent:Pe()[0]??``,schedule:`every 30m`,prompt:``}]),R(ct,j(N,{get when(){return Me().length>0},get fallback(){return mw()},get children(){return j(M,{get each(){return Me()},children:t=>(()=>{var n=hw(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=a.nextSibling,c=r.nextSibling,l=c.nextSibling;return R(i,()=>t.id),R(a,()=>t.sessions,o),R(a,()=>t.sessions===1?``:`s`,null),R(a,(()=>{var e=P(()=>(t.subs??0)>0);return()=>e()?` · +${t.subs} sub-agent${t.subs===1?``:`s`} (restored together)`:``})(),null),R(a,(()=>{var e=P(()=>!!t.archivedAt);return()=>e()?` · archived ${pt(new Date(t.archivedAt).toISOString())}`:``})(),null),R(s,()=>t.workspace),c.$$click=async()=>{let n=await Y(`/api/agents/${t.id}/restore`,{method:`POST`}).catch(()=>null);await je(),e.onSaved();let r=(n?.ids?.length??1)-1;bf((n?.live===!1?`restored ${t.id} — it could not be started (check its provider)`:`restored ${t.id}`)+(r>0?` + ${r} sub-agent${r===1?``:`s`}`:``))},l.$$click=async()=>{confirm(`PERMANENTLY DELETE ${t.id}?\n\n${t.sessions} session${t.sessions===1?``:`s`} of history will be erased from disk along with the config entry. This cannot be undone — archiving was the reversible option.`)&&(await Y(`/api/agents/${t.id}/purge`,{method:`DELETE`}).catch(()=>{}),await je(),e.onSaved(),bf(`deleted ${t.id} for good`))},b(()=>I(s,`title`,t.workspace)),n})()})}}),null),R(lt,j(M,{get each(){return e.cfg.agents??[]},children:e=>(()=>{var t=_w(),n=t.firstChild,r=n.nextSibling;return R(n,()=>e.id),R(r,()=>e.workspace),R(t,j(N,{get when(){return e.parent},get children(){var t=gw();return t.firstChild,R(t,()=>e.parent,null),t}}),null),t})()}),null),R(ft,()=>e.cfg.version??`unknown`,null),mt.$$click=async e=>{try{Te(``);let t=e.currentTarget;t.disabled=!0,t.textContent=`updating…`;let n=await Y(`/api/update/restart`,{method:`POST`});if(!n.ok)throw Error((await n.json()).error??`restart failed`);t.textContent=`restarting…`;let r=null,i=!1;for(let e=0;e<120&&!i;e++){await new Promise(e=>setTimeout(e,1e3));try{let e=await Y(`/api/version`);if(!e.version)continue;r===null&&(r=e.uptimeSeconds??null),(e.version!==`0.37.149`||typeof e.uptimeSeconds==`number`&&r!==null&&e.uptimeSeconds<r)&&(i=!0,window.location.reload())}catch{}}if(!i)throw Error(`restart timeout — new server did not come up`)}catch(e){Te(e.message)}finally{e.currentTarget.disabled=!1,e.currentTarget.textContent=`update & restart`}},R(ht,j(N,{get when(){return e.skills.length>0},get fallback(){return(()=>{var t=vw();return R(t,()=>e.hasSelection?`this session has no skills yet — the agent saves them with save_skill once a procedure proves itself`:`select a session to see the skills available to it`),t})()},get children(){var t=FC();return R(t,j(M,{get each(){return e.skills},children:t=>{let[n,r]=y(!1),[i,a]=y(null),[o,s]=y(``),c=async()=>{if(n())return r(!1);if(r(!0),i()===null&&e.agentId)try{let n=await Y(`/api/agents/${e.agentId}/skills/${encodeURIComponent(t.name)}`);a(String(n.text??``))}catch(e){s(e.message)}};return(()=>{var e=bw(),r=e.firstChild,a=r.firstChild,s=a.nextSibling,l=s.nextSibling;return r.$$click=c,R(a,()=>n()?`▾`:`▸`),R(s,()=>t.name),R(l,()=>t.description),R(e,j(N,{get when(){return n()},get children(){return j(N,{get when(){return i()!==null},get fallback(){return(()=>{var e=xw();return R(e,()=>o()||`loading…`),e})()},get children(){var e=yw();return b(()=>e.innerHTML=ut(String(i()??``))),e}})}}),null),b(()=>e.classList.toggle(`open`,!!n())),e})()}})),t}}),null),R(vt,(()=>{var t=P(()=>!!e.features);return()=>t()?P(()=>!!e.features.imageResize.available)()?`on — ${e.features.imageResize.tool}, long edge ≤ ${e.features.imageResize.maxEdge}px`:`off — no ffmpeg / ImageMagick found; uploads are served as-is`:`checking…`})()),R(yt,(()=>{var t=P(()=>!!e.features);return()=>t()?P(()=>!!e.features.pty.available)()?`on — ${e.features.pty.provider}`:`off — no pty provider; terminals run on plain pipes (no resize)`:`checking…`})()),R(bt,j(N,{get when(){return we()},get children(){var e=IC();return R(e,we),e}}),xt),R(xt,(()=>{var e=P(()=>Qe()===`saving`);return()=>e()?`saving…`:P(()=>Qe()===`saved`)()?`✓ saved`:Qe()===`error`?`✕ failed`:`save settings`})()),b(t=>{var n=F()!==`providers`,r=F()!==`appearance`,i=F()!==`runtime`,a=e.cfg.hasPassword?`(unchanged — type to replace)`:`(none — loopback only)`,o=F()!==`mcp`,s=F()!==`tasks`,c=F()!==`archive`,l=F()!==`agents`,u=F()!==`update`,d=F()!==`skills`,f=F()!==`help`,p=Qe()===`saved`,m=Qe()===`error`,h=Qe()===`saving`;return n!==t.e&&ge.classList.toggle(`hide`,t.e=n),r!==t.t&&Ae.classList.toggle(`hide`,t.t=r),i!==t.a&&Be.classList.toggle(`hide`,t.a=i),a!==t.o&&I(Ze,`placeholder`,t.o=a),o!==t.i&&it.classList.toggle(`hide`,t.i=o),s!==t.n&&ot.classList.toggle(`hide`,t.n=s),c!==t.s&&ct.classList.toggle(`hide`,t.s=c),l!==t.h&&lt.classList.toggle(`hide`,t.h=l),u!==t.r&&dt.classList.toggle(`hide`,t.r=u),d!==t.d&&ht.classList.toggle(`hide`,t.d=d),f!==t.l&&gt.classList.toggle(`hide`,t.l=f),p!==t.u&&xt.classList.toggle(`saved`,t.u=p),m!==t.c&&xt.classList.toggle(`error`,t.c=m),h!==t.w&&(xt.disabled=t.w=h),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0}),b(()=>ke.value=i()),b(()=>Re.checked=He()),b(()=>Ze.value=C()),b(()=>nt.value=p()??``),b(()=>rt.checked=ee()),t}})}Ee([`click`,`input`]);var ww=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`bmp`,`ico`,`avif`]),Tw=new Set([`mp4`,`webm`,`mov`,`mkv`,`avi`,`m4v`]),Ew=new Set([`mp3`,`wav`,`ogg`,`m4a`,`flac`,`aac`,`opus`]);function Dw(e){let t=e.split(`.`).pop()?.toLowerCase()??``,n=Ow(e);return n===`image`?`🖼`:n===`video`?`🎬️`:n===`audio`?`🎵`:[`ts`,`tsx`,`mts`,`cts`].includes(t)?`🟦`:[`js`,`mjs`,`cjs`,`jsx`].includes(t)?`🟨`:t===`json`||t===`jsonc`?`🧾`:t===`md`||t===`mdx`||t===`markdown`?`📝`:t===`css`||t===`scss`||t===`less`?`🎨`:t===`html`||t===`htm`||t===`svg`?`🌐️`:[`py`,`pyi`].includes(t)?`🐍`:t===`rs`?`🦀`:t===`go`?`🐹`:t===`java`||t===`kt`||t===`kts`?`☕️`:t===`rb`?`💎`:t===`php`?`🐘`:t===`c`||t===`h`||t===`cpp`||t===`hpp`||t===`cc`?`🧩`:t===`sh`||t===`bash`||t===`zsh`||t===`fish`?`🐚`:t===`sql`?`🗄`:t===`yml`||t===`yaml`||t===`toml`||t===`ini`||t===`conf`?`⚙️`:t===`lock`?`🔒️`:e===`Dockerfile`||t===`dockerfile`?`🐳`:t===`zip`||t===`gz`||t===`tar`||t===`tgz`||t===`bz2`?`📦`:t===`pdf`?`📕`:t===`txt`||t===`log`?`📄`:`·`}function Ow(e){let t=e.split(`.`).pop()?.toLowerCase()??``;return ww.has(t)?`image`:Tw.has(t)?`video`:Ew.has(t)?`audio`:null}var kw=new Map,Aw=e=>{let t=kw.get(e);return t||(t={expanded:new Set,preview:null,media:null,viewMode:`code`},kw.set(e,t)),t},jw=F(`<span class=fsize>`),Mw=F(`<div><span class=ficon></span><span class=fname>`),Nw=F(`<h3 title="the agent's workspace — lazy-loaded, dotfiles hidden; click a folder to expand, a file to preview"style=display:flex;align-items:center;gap:6px>🗂 files <span class=muted style=text-transform:none;letter-spacing:0>· `),Pw=F(`<div class=filebox>`),Fw=F(`<div class=muted style=padding:6px>`),Iw=F(`<img>`),Lw=F(`<div class=mediapreview><div class="meta muted"> preview`),Rw=F(`<button title="rendered markdown">👁 preview`),zw=F(`<button title="edit and save back to the workspace">✎ edit`),Bw=F(`<div class=filetoolbar><button title="syntax-highlighted source">&lt;/> code`),Vw=F(`<div class=fileeditor><textarea class=mono></textarea><div class=filerow-actions><span class=muted> bytes</span><button class=savebtn>`),Hw=F(`<div class=mono style=margin:0;color:var(--dim)>(binary file — inspect it from the terminal)`),Uw=F(`<div class="content mdpreview shikiwrap">`),Ww=F(`<video controls>`),Gw=F(`<audio controls>`);function Kw(e){let t=Aw(e.agentId),[n,r]=y(new Map),[i,a]=y(t.expanded),[o,s]=y(t.preview),c=e=>{t.preview=e,s(e)},l=e=>{t.expanded=e,a(e)},[u,d]=y(t.media),f=e=>{t.media=e,d(e)},[p,m]=y(t.viewMode),h=e=>{t.viewMode=e,m(e)},[g,_]=y(``),[v,ee]=y(localStorage.getItem(`teapot.ignoreMode`)??`dim`),S=()=>{let e=[`dim`,`hide`,`show`],t=e[(e.indexOf(v())+1)%3];ee(t),localStorage.setItem(`teapot.ignoreMode`,t)},C=e=>v()!==`hide`||!e.ignored,[w,E]=y(localStorage.getItem(`teapot.showHidden`)===`1`),D=()=>{let e=!w(),t=[``,...i()];Promise.all(t.map(async t=>({p:t,rows:await ne(t,e)}))).then(t=>{E(e),localStorage.setItem(`teapot.showHidden`,e?`1`:`0`);for(let{p:e,rows:n}of t)n&&re(e,n)})},O=(e,t)=>t.map(t=>({name:String(t.name),path:e?`${e}/${t.name}`:String(t.name),dir:!!t.dir,...typeof t.size==`number`?{size:t.size}:{},...t.ignored?{ignored:!0}:{}}));async function te(e){return ne(e,w())}async function ne(t,n){try{let r=new URLSearchParams;t&&r.set(`path`,t),n&&r.set(`hidden`,`1`);let i=await Y(`/api/agents/${e.agentId}/tree?${r.toString()}`);return O(t,i.entries??[])}catch(e){return _(e.message),null}}let re=(e,n)=>r(r=>{let i=r.get(e);if(!i)return new Map(r).set(e,n);let a=new Map(i.map(e=>[e.path,e])),o=n.map(e=>{let t=a.get(e.path);return t&&t.dir===e.dir&&t.size===e.size&&t.ignored===e.ignored&&t.name===e.name?t:e}).filter(e=>n.some(t=>t.path===e.path)||t.preview?.path===e.path),s=new Map(r);return s.set(e,o),s}),k=``;x(()=>{let t=e.agentId;t!==k&&(k=t,l(new Set),c(null),f(null),r(new Map),te(``).then(e=>{e&&k===t&&r(new Map([[``,e]]))}))});let ie=async e=>{let t=new Set(i());if(t.has(e.path))t.delete(e.path),l(t);else if(t.add(e.path),l(t),!n().has(e.path)){let t=await te(e.path);t&&re(e.path,t)}},[ae,oe]=y(``),[se,ce]=y(!1),[le,ue]=y(``),[de,fe]=y(!1),A=e=>/\.(md|markdown|mdx)$/i.test(e),pe=0,me=async e=>{let t=++pe;oe(``),ce(!0);try{let{highlightChunks:n}=await J(async()=>{let{highlightChunks:e}=await Promise.resolve().then(()=>px);return{highlightChunks:e}},void 0);for await(let r of n(e.path,e.content)){if(pe!==t)return;oe(e=>e+r)}}catch{pe===t&&oe(``)}finally{pe===t&&ce(!1)}};T(()=>{pe++});let he=async(t,n)=>{let r=Ow(t.path);if(r)c({path:t.path,content:``,binary:!0}),f({path:t.path,kind:r}),h(`media`);else try{let r=await Y(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`);f(null),c({path:t.path,content:r.content??``,binary:r.binary,truncated:r.truncated}),ue(r.content??``),h(r.binary?`code`:n),!r.binary&&n!==`md`&&me({path:t.path,content:r.content??``,truncated:r.truncated})}catch(e){bf(`open failed: ${e.message}`)}},ge=async()=>{let t=o();if(t&&!de()){fe(!0);try{await Y(`/api/agents/${e.agentId}/file?path=${encodeURIComponent(t.path)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({content:le(),baseContent:t.content})}),c({...t,content:le()}),bf(`saved ${t.path}`)}catch(e){let n=e.payload,r=n&&typeof n==`object`&&n.error===`file changed on disk`?n:null;r?.current===void 0?bf(`save failed: ${e.message}`):confirm(`This file changed on disk since you opened it.
181
181
  OK = load the disk version into the editor (your edits are discarded)
182
- Cancel = keep editing your copy`)?(ue(r.current),c({...t,content:r.current}),bf(`loaded the current file from disk`)):bf(`kept your edits — use Save As via bash to force-write`)}finally{fe(!1)}}},_e=e=>!e.binary&&!e.truncated,ve=(e,t)=>[(()=>{var n=Mw(),r=n.firstChild,a=r.nextSibling;return n.$$click=()=>e.dir?void ie(e):void he(e,`code`),R(r,(()=>{var t=P(()=>!!e.dir);return()=>t()?i().has(e.path)?`▾`:`▸`:Dw(e.name)})()),R(a,()=>e.name),R(n,j(N,{get when(){return P(()=>!e.dir)()&&e.size!==void 0},get children(){var t=jw();return R(t,()=>Rx(e.size)),t}}),null),b(r=>{var i=`filerow`+(e.dir?` isdir`:``)+(e.ignored&&v()===`dim`?` gitignored`:``),a=`padding-left:${t*13+8}px`,o=e.dir?`browse ${e.path}`:`preview ${e.path}`;return i!==r.e&&L(n,r.e=i),r.t=Oe(n,a,r.t),o!==r.a&&I(n,`title`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})(),j(N,{get when(){return P(()=>!!e.dir)()&&i().has(e.path)},get children(){return j(M,{get each(){return(n().get(e.path)??[]).filter(C)},children:e=>ve(e,t+1)})}})],ye=()=>e.workspace.split(`/`).filter(Boolean).pop()??e.workspace,[be,xe]=y(!1),Se=async()=>{if(!be()){xe(!0);try{let e=[``,...i()],t=await Promise.all(e.map(async e=>({p:e,rows:await ne(e,w())})));for(let{p:e,rows:n}of t)n&&re(e,n)}finally{xe(!1)}}};return[(()=>{var e=Nw(),t=e.firstChild.nextSibling;return t.firstChild,R(t,ye,null),R(e,j(vd,{class:`filetoggle`,get icon(){return be()?`…`:`⟳`},title:`refresh the tree (root + expanded folders) — open popups are kept`,onClick:()=>void Se()}),null),R(e,j(vd,{class:`filetoggle`,style:`margin-left:auto`,get icon(){return P(()=>v()===`hide`)()?`🙈`:v()===`dim`?`👁`:`✨`},get title(){return`gitignored files: ${v()} — click to cycle (dim → hidden → shown)`},onClick:S}),null),R(e,j(vd,{class:`filetoggle`,get icon(){return w()?`◉.`:`○.`},get title(){return w()?`dotfiles shown — click to hide`:`dotfiles hidden — click to show`},onClick:D}),null),e})(),(()=>{var e=Pw();return R(e,j(N,{get when(){return(n().get(``)??[]).length>0},get fallback(){return(()=>{var e=Fw();return R(e,()=>g()||`empty workspace`),e})()},get children(){return j(M,{get each(){return(n().get(``)??[]).filter(C)},children:e=>ve(e,0)})}})),e})(),j(N,{get when(){return o()},children:t=>j(bd,{get title(){return`🗂 ${t().path}`},onClose:()=>{pe++,c(null),f(null)},get children(){return j(N,{get when(){return u()},get fallback(){return[(()=>{var e=Bw(),n=e.firstChild;return R(e,j(N,{get when(){return P(()=>!!A(t().path))()&&!t().binary},get children(){var e=Rw();return e.$$click=()=>h(`md`),b(()=>L(e,p()===`md`?`on`:``)),e}}),n),n.$$click=()=>{h(`code`),ae()||me({path:t().path,content:t().content,truncated:t().truncated})},R(e,j(N,{get when(){return _e(t())},get children(){var e=zw();return e.$$click=()=>h(`edit`),b(()=>L(e,p()===`edit`?`on`:``)),e}}),null),b(()=>L(n,p()===`code`?`on`:``)),e})(),j(N,{get when(){return!t().binary},get fallback(){return Hw()},get children(){return j(N,{get when(){return p()===`edit`},get fallback(){return j(N,{get when(){return P(()=>p()===`md`)()&&A(t().path)},get fallback(){return j(mf,{get path(){return t().path},get content(){return t().content},get html(){return ae()},get pending(){return se()},get truncated(){return!!t().truncated}})},get children(){var e=Uw();return b(()=>e.innerHTML=Re(t().content)),e}})},get children(){var e=Vw(),n=e.firstChild,r=n.nextSibling.firstChild,i=r.firstChild,a=r.nextSibling;return n.$$input=e=>ue(e.currentTarget.value),I(n,`spellcheck`,!1),R(r,()=>Rx(le().length),i),a.$$click=()=>void ge(),R(a,()=>de()?`saving…`:`💾 save`),b(()=>a.disabled=de()||le()===t().content),b(()=>n.value=le()),e}})}})]},get children(){var t=Lw(),n=t.firstChild,r=n.firstChild;return R(t,j(N,{get when(){return u().kind===`image`},get fallback(){return j(N,{get when(){return u().kind===`video`},get fallback(){return(()=>{var t=Gw();return b(()=>I(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t})()},get children(){var t=Ww();return b(()=>I(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t}})},get children(){var t=Iw();return b(n=>{var r=`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`,i=u().path.split(`/`).pop();return r!==n.e&&I(t,`src`,n.e=r),i!==n.t&&I(t,`alt`,n.t=i),n},{e:void 0,t:void 0}),t}}),n),R(n,()=>u().kind,r),t}})}})})]}Ee([`click`,`input`]);var qw=F(`<div class=overlay><div class=modal style=max-width:360px><div class=modal-head><b>🔒️ sign in</b><span></span></div><form style=display:flex;flex-direction:column;gap:10px><input id=pw-input type=password placeholder=password autofocus><button type=submit class=primarybtn>unlock</button><span class=muted style=font-size:11px>the token is stored locally and sent as Bearer to this server only`),Jw=F(`<div class=leftbarbackdrop>`),Yw=F(`<div class=sidehead><b>agents</b><button class=iconbtn title="close the agent list">✕`),Xw=F(`<i class=notifdot>`),Zw=F(`<br>`),Qw=F(`<button class="iconbtn ham"title="agent list">☰`),$w=F(`<input class="title titleedit">`),eT=F(`<span class="badge queued">⏳ <!> <!> queued`),tT=F(`<button type=button class="badge bgjobs">⚙️ `),nT=F(`<span class="badge cron">⏰ `),rT=F(`<div class=bgjobs-pop role=dialog aria-label="background shells"><div class=bgjobs-head><span>background shells</span><button type=button class=iconbtn title=close>✕`),iT=F(`<header class=chan-head><span class=hash title="rename this chat">#</span><span></span><span class=sub> · <!>/<!> · <!>↻ <!>⚙️</span><span class=head-actions><button></button><span class=head-sep aria-hidden=true>`),aT=F(`<div class=divider-msg>── beginning of log ──`),oT=F(`<div class=divider-msg>loading older events…`),sT=F(`<div class=feedloading><span class=spinner aria-hidden=true></span> loading timeline…`),cT=F(`<div class=feedloading><span class=spinner aria-hidden=true></span> loading newer events…`),lT=F(`<details class=reasoning open><summary>💭 thinking </summary><div class="mono thinkscroll">`),uT=F(`<div class=muted style=font-size:11.5px;margin-bottom:4px>🗜 summarizing older context…`),dT=F(`<div class=content>`),fT=F(`<div class="msg live"><div class=avatar style="background:#5865f233;border:1px solid #5865f266">🫖</div><div class=msg-body><div class=msg-head><span class=author style=color:var(--acc)>agent</span><span class=ts>streaming…`),pT=F(`<div class=feed>`),mT=F(`<div class="termempty muted">no shell here — + opens one, tabs fill the focused pane`),hT=F(`<div class=termsplit>`),gT=F(`<div class="termempty muted">no shell here — click a tab or + to add`),_T=F(`<div class=termpane>`),vT=F(`<div class=termdrawer><div class=termgrip title="drag to resize · double-click to reset"></div><div class=termbar><div class=termtabs></div><div style=display:flex;gap:4px;align-items:center><span class="muted mono"style=flex:1;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap></span></div></div><div class=termbody><div class=termpane>`),yT=F(`<button class=jump>↓ `),bT=F(`<div class=cmds>`),xT=F(`<div class=attachrow><button type=button class=attachclear title="remove every attachment">clear`),ST=F(`<label class=forkchip title="inherit the conversation prefix byte-exactly — the sub-agent's provider prefix cache starts warm"><input type=checkbox>fork ctx`),CT=F(`<div class="hint flashhint">`),wT=F(`<div><form><textarea rows=1></textarea><button type=button class="iconbtn maxbtn"></button><button type=submit>send</button><input id=composer-file type=file accept=image/* multiple style=display:none>`),TT=F(`<div class=rightbarbackdrop>`),ET=F(`<div><nav><div class=agent-list></div><div class=sidebar-footer><div class=footer-row style=justify-content:flex-end><button>🔔️</button></div><div class=brand-row><div class=brand>🫖 teapot <span class=version>v</span><span></span></div></div><div class=metrics></div></div></nav><section class=channel></section><aside><div class=rightbarhead><span class=muted>details`),DT=F(`<div class=notifbackdrop>`),OT=F(`<button class=editbtn>clear all`),kT=F(`<div class=notiflist>`),AT=F(`<div class=notifpanel><div class=notifhead>notifications<span style=display:flex;gap:8px;align-items:center><button class=iconbtn title="close notifications">✕`),jT=F(`<div class=bgphoto aria-hidden=true><img sizes=100vw alt decoding=async><span class=bgphoto-veil>`),MT=F(`<span class=wscount>`),NT=F(`<div class=wsheader><span class=wscaret></span><span class=wsname>`),PT=F(`<span class=notifbadge>🔔️`),FT=F(`<span class=subtag>🧩`),IT=F(`<span class=mini-cron>⏰`),LT=F(`<span class=goaldone title="goal done">✓`),RT=F(`<div><span></span><span>`),zT=F(`<span class=caret-spacer>`),BT=F(`<span class=caret>`),VT=F(`<span class=ghosttag title="workspace missing">👻`),HT=F(`<span>🧩 `),UT=F(`<div class=muted style=display:grid;place-items:center;height:100%>select an agent`),WT=F(`<span class=title>`),GT=F(`<div class="muted bgjobs-empty">no background jobs for this agent`),KT=F(`<pre class="mono bgjob-tail">`),qT=F(`<div class=bgjob><div class=bgjob-line><span></span><code class="mono bgjob-cmd"></code><span class="muted bgjob-meta"></span><button type=button class=bgjob-kill>`),JT=F(`<div class="muted bgjob-detached">this job outlived a harness restart, so its output is no longer captured here. it is still running as pid <!> — read its own log, or stop it yourself.`),YT=F(`<div class="divider-msg compacting"title="the harness is compressing old turns into notes so work can continue within the context window">🗜 `),XT=F(`<div class=muted style=display:grid;place-items:center;height:100%><span><span class=spinner aria-hidden=true></span> loading timeline…`),ZT=F(`<div class=muted style=display:grid;place-items:center;height:100%>no events yet — say something or press ▶ start`),QT=F(`<div class="content muted">thinking…`),$T=F(`<div class=lightbox role=dialog aria-modal=true aria-label="enlarged image"title="click to close"><img alt>`),eE=F(`<span>⌨ <button class=tabx title="close this shell">✕`),tE=F(`<div><b class=mono></b><span class=muted>`),nE=F(`<div class=cmdrow><b>@</b><span class=muted>`),rE=F(`<span class=imgchip><img title="click to enlarge"><button type=button class=imgx title=remove>✕`),iE=F(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> models`),aE=F(`<h3 title="switch provider/model live — applies from the agent's next turn">🧦 model`),oE=F(`<div style=display:flex;gap:6px;align-items:center;margin-top:6px><label class=muted style=font-size:11.5px;white-space:nowrap>effort</label><select style=flex:1;min-width:0><option value>provider default`),sE=F(`<div class=meta style=color:var(--fg)>`),cE=F(`<div class=modelbox><select title="provider (OpenAI-compatible endpoint)"></select><div style=display:flex;gap:4px><input type=text list=model-list style=flex:1;min-width:0><datalist id=model-list></datalist></div><div style=display:flex;gap:6px;align-items:center;margin-top:6px><button title="apply the provider, model and effort above to this session — takes effect from the agent's next turn"style=flex:1>apply</button></div><div class=meta>current: `),lE=F(`<span>`),uE=F(`<h3 title="what the agent is working toward. Stored with the session; the agent reads it via get_goal(). Auto-continue keeps looping while the status is 'active' and stops when marked done.">🎯 goal`),dE=F(`<div class=statrow style=margin-bottom:6px><span class=k>status`),fE=F(`<div class="card goalcard"><div class=content>`),pE=F(`<form style=display:flex;flex-direction:column;gap:6px;margin-top:8px;margin-bottom:6px><textarea id=goal-input rows=3 placeholder="set new goal…"title="drag the bottom edge to make this taller — the height is remembered"style="background:var(--bg-darkest);border:none;border-radius:6px;padding:6px 8px;color:var(--fg);font:inherit;width:100%;resize:vertical"></textarea><textarea id=goal-verify-input rows=2 placeholder="verification contract (optional) — e.g. 'npm test passes; endpoint documented'. finish(goalComplete=true) is then audited against this."title="pi-goal-x-style verification contract — an independent reviewer checks the agent's finish against these requirements"style="background:var(--bg-darkest);border:1px solid var(--bg-light);border-radius:6px;padding:6px 8px;color:var(--fg);font:inherit;font-size:12.5px;width:100%;resize:vertical"></textarea><div style=display:flex;justify-content:flex-end;align-items:center;gap:10px><label class=muted title="auto-continue acts on the GOAL above: it fires after a round ONLY when all hold — ① this toggle is on ② a goal is set and its status is 'active' ③ the round ended cleanly (no error / not stopped). It stops when the goal is marked done, or if you press ■ stop."style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input type=checkbox>auto-continue</label><label class=muted title="queue a harness prompt telling the agent about the new goal at its next turn boundary"style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input id=goal-notify type=checkbox> notify agent</label><button type=submit class=primarybtn>✓ save goal`),mE=F(`<span class=badge>/<!> done`),hE=F(`<h3 title="todo.md — a shared checklist in the session dir. Write tasks like '- [ ] fix login'; the agent ticks them off via set_todo, you edit here. With notify on, it's told at its next turn boundary.">✅ tasks`),gE=F(`<div class=bartrack style=margin-bottom:6px><div>`),_E=F(`<div style=display:flex;justify-content:flex-end;align-items:center;gap:10px;margin-top:4px><label class=muted title="queue a harness prompt telling the agent the task list changed"style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input id=todo-notify type=checkbox checked> notify agent</label><button class=okbtn>✓ save tasks`),vE=F(`<h3 title="latest report_progress snapshot. The harness asks for one after real activity (time AND output gates); errors show under ⚠ problems">📈 progress`),yE=F(`<h3 title="context is how much of the model's window the live conversation occupies. Past the threshold, the oldest turns are summarized into notes so work can continue.">📊 runtime`),bE=F(`<div class=rtcell><span>cost</span><b>$`),xE=F(`<div class=rtcell><span>cached</span><b>%`),SE=F(`<div class="card runcard"><div class=rtgrid><div class=rtcell title="prompt tokens billed this session"><span>tokens in</span><b></b></div><div class=rtcell title="completion tokens billed this session"><span>tokens out</span><b></b></div><div class=rtcell title="assistant turns this session"><span>turns</span><b></b></div><div class=rtcell title="tool calls this session"><span>tools</span><b></b></div><div class=rtcell><span>compacted</span><b>`),CE=F(`<div class=muted style=font-size:11px;text-transform:none;letter-spacing:0>showing <b></b> and the history it inherited before forking`),wE=F(`<h3>🌿 branches <span class=muted style=text-transform:none;letter-spacing:0>· click to filter the feed`),TE=F(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> · all agents`),EE=F(`<h3 title="cron tasks, all agents — click a row to open that agent. Edit them in ⚙️ settings → scheduled tasks.">⏰ schedule`),DE=F(`<option>`),OE=F(`<span class=badge title="no goal set yet">no goal`),kE=F(`<button>`),AE=F(`<div class="card muted">no goal yet — write one below and press ✓ save. Then ▶ start (or any message) sets it in motion.`),jE=F(`<div class=muted>none yet`),ME=F(`<div class=progrow><b>recent</b><span class="content inline-md">`),NE=F(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),PE=F(`<div class=progrow><b>next</b><span class="content inline-md">`),FE=F(`<div class=progrow><b>goal</b><span>`),IE=F(`<div class="card prog"><div class=progrow><b>doing</b><span class="content inline-md"></span></div><div class="meta muted">`),LE=F(`<div class=statrow><span class=k>context</span><span class=muted>no window known for this model yet`),RE=F(`<span>% of `),zE=F(`<div class=bartrack><div>`),BE=F(`<div class=statrow title="a compaction pass is running right now — the summarizer's output streams in the timeline"><span class=k>🗜</span><b>compacting…</b><span class=muted style=font-size:11px;color:var(--acc)>`),VE=F(`<div class=ctxblock title="estimated live context vs the model's real window. Past the window, old turns are summarized into notes (compaction); the compact line below shows where that starts."><div class=statrow><span class=k>context</span><b>~<!> tok</b></div><div class=statrow style=margin-top:4px><span class=k>compact at</span><b> tok</b><span class=muted style=color:var(--dim)></span></div><div class=ctrlrow style=margin-top:6px><label title="when on, older turns are automatically summarized when context exceeds the budget"><input type=checkbox>auto-compact`),HE=F(`<div><span></span><span> events`),UE=F(`<div class=muted>no scheduled tasks — add them in ⚙️ settings ("scheduled tasks")`),WE=F(`<span title="runs on a forked branch so chatter stays off the main line">⑂`),GE=F(`<div><div class=sched-top><b></b><span class=muted>@</span></div><div class=sched-meta> → next </div><div class="sched-prompt muted">`),KE=F(`<div class=muted style=padding:10px>nothing yet — progress, finishes, questions and errors will land here`),qE=F(`<div class=nbody>`),JE=F(`<div><div class=nhead><span class=nicon></span><span class=ntitle></span><span class="meta muted"></span><button class="iconbtn nreadbtn">`),YE=F(`<div style=font-size:12.5px;color:var(--dim)> event(s) came after this prompt and will be discarded — the new branch starts from your edited text.`),XE=F(`<form style=display:flex;flex-direction:column;gap:10px><textarea id=edit-text class="mono w100"rows=6></textarea><div style=display:flex;justify-content:flex-end;gap:8px><button type=button>cancel</button><button type=submit class=primarybtn>⑂ fork & resend`),ZE=F(`<span style=color:var(--err);font-size:13px>`),QE=F(`<form style=display:flex;flex-direction:column;gap:10px><label>workspace directory<div style=display:flex;gap:6px><input type=text class="w100 mono"><button type=button>go</button><button type=button title="parent directory">↑</button></div></label><div class=dirlist></div><div style=display:flex;gap:10px><label style=flex:1>agent name <input type=text placeholder="(directory name)"></label><label style="flex:0 1 auto;min-width:0">provider<select></select></label><label style=flex:1>model <input type=text placeholder="(provider default)"></label></div><button type=submit style=align-self:flex-end>create`),$E=F(`<div class=direntry>📁 `),eD=[`minimal`,`low`,`medium`,`high`],tD=1100,[nD,rD]=y(``),iD,aD=e=>{rD(e),clearTimeout(iD),iD=setTimeout(()=>rD(``),3200)},oD=!1,sD=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`state`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`audit_step`,`system_note`]),cD=new Set([`system_note`]),lD=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`audit_step`]),uD=new Set([`runaway-detected`,`error-retry`,`background-exit`,`context-compacted`,`context-compaction-started`]),dD=location.hash.match(/[#&]token=([^&]+)/);dD&&(localStorage.setItem(`teapot.token`,decodeURIComponent(dD[1])),history.replaceState(null,``,location.pathname+location.search));var fD=()=>{let e=localStorage.getItem(`teapot.token`);return e?`?token=${encodeURIComponent(e)}`:``};function pD(){let[e,t]=y([]),[n,r]=y(null),[i,a]=y(``),[o,s]=y(new Map),[c,l]=y(new Map),[u,d]=y(new Map),f=!1,p=null;async function m(e=!1){if(p)return p;if(f&&!e)return;let t=(async()=>{try{let e=await Y(`/api/sessions`),t=new Map,n=new Map,r=new Map;for(let i of e.sessions??[]){t.set(i.id,i.agentId),typeof i.title==`string`&&i.title&&r.set(i.id,i.title);let e=n.get(i.agentId)??[];e.push(i.id),n.set(i.agentId,e)}s(t),l(n),d(r),f=!0}catch{}})();p=t;try{await t}finally{p===t&&(p=null)}}let[h,g]=y([]),[_,v]=y(0),[ee,E]=y([]),[D,O]=y(null),te=new Map,[ne,re]=y(te.get(n()??``)??``),k=e=>{re(e);let t=n();t&&(e?te.set(t,e):te.delete(t))},[ie,ae]=y({providers:{}}),[oe,se]=y(!1),ce=()=>lr({want:dr({preview:At(),auto:St(),prefersLight:Lt(),dark:Pt(),light:Tt(),fixed:bt()}),customIds:Mt().map(e=>e.id),presetIds:Yd.map(e=>e.key),fallback:`dark`}),le=()=>ce().active,ue=()=>Mt().find(e=>e.id===le())?.backgroundImage??``,[de,fe]=y(!1),A=!1;x(()=>{!A&&ie()?.needsSetup&&(A=!0,requestAnimationFrame(()=>{ti(),fe(!0)}))}),x(()=>{de()&&!Oo()&&Y(`/api/features`).then(e=>ko(e)).catch(()=>ko(null))});let pe=new Set,me=()=>window.innerWidth<=tD,[he,ge]=y(me());w(()=>{let e=()=>{let e=me();e!==he()&&(ge(e),(localStorage.getItem($e(e))!==null||!e)&&st(et(e)))};window.addEventListener(`resize`,e),T(()=>window.removeEventListener(`resize`,e)),e()});let _e=0,ve=null,ye=0,be,xe,Se=0,Ce=0,we=0,Te=()=>{if(xn()||!ve)return;let e=ra();if(!e)return;if(!Ze(performance.now(),Ce)||e.scrollHeight===Vo){ve=Ue(e),ye=performance.now();return}if(!F(e))return;let t=e.scrollHeight;Le(e,ve,Uo),Vo=e.scrollHeight,t!==Vo&&(Bo={top:e.scrollTop,height:e.scrollHeight})},F=e=>{if(!ve)return!1;let t=Ue(e);return t?t.sel===ve.sel||(ve=t,ye=performance.now(),!1):!1},Ee=()=>{Se||=requestAnimationFrame(()=>{Se=0,Te()})},je,Me,Ne=0,Pe=``,Fe=0,Ie=()=>{Ne=0;let e=ra();if(!e)return;let t=e.scrollHeight!==Vo;Vo=e.scrollHeight,Wo=e.clientHeight;let n=e.clientWidth!==Fe;Fe=e.clientWidth,xn()?oa():n&&ve?(Le(e,ve,1200),Wn(ia())):t?Ze(performance.now(),Ce)?(F(e)&&Le(e,ve,Ho),Wn(ia())):(ve=Ue(e),ye=performance.now(),Wn(ia())):Wn(ia())};function Le(e,t,n=Ho){if(!t)return;let r=e.querySelector(t.sel);if(!r)return;let i=r.getBoundingClientRect().top-t.top;Math.abs(i)<1||Math.abs(i)>n||(e.scrollTop+=i,Bo={top:e.scrollTop,height:e.scrollHeight})}let ze=()=>{Ne||=requestAnimationFrame(Ie)},Be=null,Ve=e=>{Be?.();let t=e=>{Ln(e.deltaY)&&(we=performance.now()+400,xn()&&Tn(!1))},n=()=>{we=performance.now()+400,xn()&&Tn(!1)},r=e=>{Rn(e.key)&&n()};e.addEventListener(`wheel`,t,{passive:!0}),e.addEventListener(`touchmove`,n,{passive:!0}),e.addEventListener(`touchstart`,n,{passive:!0}),e.addEventListener(`pointerdown`,n,{passive:!0}),window.addEventListener(`keydown`,r,{capture:!0}),Be=()=>{e.removeEventListener(`wheel`,t),e.removeEventListener(`touchmove`,n),e.removeEventListener(`touchstart`,n),e.removeEventListener(`pointerdown`,n),window.removeEventListener(`keydown`,r,{capture:!0}),Be=null}},He=e=>{e&&(Ve(e),e!==Me&&(je??=new ResizeObserver(e=>{let t=e[0]?.contentRect,n=t?`${Math.round(t.width)}x${Math.round(t.height)}`:``;n!==Pe&&(Pe=n,ze())}),Me&&je.unobserve(Me),Me=e,Pe=``,je.observe(e),typeof MutationObserver<`u`&&(be??=new MutationObserver(Ee),xe&&xe!==e&&xe.removeEventListener(`load`,Ee,!0),xe=e,be.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),e.addEventListener(`load`,Ee,!0))))};w(()=>{window.addEventListener(`resize`,ze),T(()=>{window.removeEventListener(`resize`,ze),je?.disconnect(),je=void 0,Me=void 0,be?.disconnect(),be=void 0,xe&&xe.removeEventListener(`load`,Ee,!0),xe=void 0,Se&&cancelAnimationFrame(Se),Ne&&cancelAnimationFrame(Ne)})});function Ue(e){let t=e.querySelectorAll(`[data-eid]`);if(!t.length)return null;let n=e.getBoundingClientRect().top,r=e=>t[e].getBoundingClientRect(),i=0,a=t.length-1,o=-1;for(;i<=a;){let e=i+a>>1;r(e).bottom>n?(o=e,a=e-1):i=e+1}if(o<0)return null;let s=t[o].dataset.eid??``;return s?{sel:`[data-eid="${CSS.escape(s)}"]`,top:r(o).top}:null}let $e=e=>e?`teapot.panel.narrow`:`teapot.panel`,et=e=>{let t=localStorage.getItem($e(e));return t===null?!e:t===`1`},[ot,st]=y(et(me())),ct=e=>{st(e),localStorage.setItem($e(he()),e?`1`:`0`)},lt=()=>ct(!ot()),ft=()=>{ot()&&ct(!1)},[_t,vt]=y(!1),yt=()=>vt(!1),[bt,xt]=y(localStorage.getItem(`teapot.theme`)??`dark`),[St,wt]=y(localStorage.getItem(`teapot.theme.auto`)===`1`),[Tt,kt]=y(localStorage.getItem(`teapot.theme.light`)??`light`),[At,jt]=y(null),[Mt,Nt]=y(nr());w(()=>{ir().then(e=>{if(e===null)return;let t=tn(Mt(),e);Nt(t),rr(t)})});let[Pt,Ft]=y(localStorage.getItem(`teapot.theme.dark`)??`dark`),It=typeof window.matchMedia==`function`?window.matchMedia(`(prefers-color-scheme: light)`):null,[Lt,Rt]=y(It?.matches??!1);w(()=>{let e=e=>Rt(e.matches);It?.addEventListener(`change`,e);let t=()=>{if(document.visibilityState!==`visible`)return;let e=It?.matches??!1;e!==Lt()&&Rt(e)};document.addEventListener(`visibilitychange`,t),T(()=>{It?.removeEventListener(`change`,e),document.removeEventListener(`visibilitychange`,t)})}),x(()=>{let{active:e,repaired:t}=ce(),n=Mt().find(t=>t.id===e)??null;t&&(St()?localStorage.setItem(Lt()?`teapot.theme.light`:`teapot.theme.dark`,e):localStorage.setItem(`teapot.theme`,e)),document.documentElement.dataset.theme=e,or(document.documentElement,n),document.documentElement.dataset.appearance=n?.mode??Yd.find(t=>t.key===e)?.mode??`dark`});let[zt,Bt]=y(``),[Vt,Ht]=y(``),[Ut,Gt]=y(``);x(()=>{let t=n();Gt(C(()=>e().find(e=>e.id===t)?.reasoningEffort??``))});let[qt,Jt]=y([]),Yt=()=>Object.keys(ie().providers??{});async function Xt(e){if(e)try{let t=await Y(`/api/models?provider=${encodeURIComponent(e)}`);Jt(t.models??[])}catch{Jt([])}}let Zt=e=>{let t={text:`📄`,image:`🖼️`,audio:`🔊`,video:`🎬️`,file:`📎`},n=e=>(e??[`text`]).map(e=>t[e]??e).join(``);return e?.modalities?`${n(e.modalities.input)} → ${n(e.modalities.output)}`:``},Qt=()=>{let e=Vt().trim()||B()?.model||``;if(!e)return``;let t=qt().find(t=>t.id===e);if(!t)return``;let n=[],r=Zt(t);r&&r!==`📄 → 📄`&&n.push(r),t.contextLength&&n.push(`ctx ${Rx(t.contextLength)} tok`);let i=e=>e===void 0?``:`${e*1e6>=10?Math.round(e*1e6):+(e*1e6).toFixed(1)}/M`;if(t.pricing){let e=i(t.pricing.prompt),r=i(t.pricing.completion);e&&r?n.push(`${e} in · ${r} out`):(e||r)&&n.push(i(t.pricing.prompt??t.pricing.completion))}return n.join(` · `)},rn=null,an=!1;x(()=>{let t=n();if(!t)return;let r=e().find(e=>e.id===t),i=r?.provider||ie().defaultProvider||Yt()[0]||``;if(r){if(t!==rn)rn=t,an=!1,C(()=>zt())!==i&&(Bt(i),Xt(i)),C(()=>Vt())&&Ht(``);else{let e=C(()=>zt());!C(()=>Vt())&&e!==i&&Nn(an)&&(Bt(i),Xt(i))}}});let[on,un]=y(!1),[xn,Tn]=y(!0),On,[An,Vn]=y(0),[Hn,Un]=y(-1),Wn=e=>Un(e?Xe(e):-1),[Jn,Xn]=y(null),Zn=()=>cr().startsWith(`[compact] `),Qn=()=>{let e=Zn()?cr().slice(10):cr();return e.length>1200?`…`+e.slice(-1200):e};x(()=>{Jn()||ar(e=>e?.text.startsWith(`[compact] `)?null:e)}),x(()=>{h().length,_(),Jn(),Yr().length,Gi(),Ui(),Vi();let e=ra();if(!e)return;let t=e.scrollHeight;t!==_e&&(_e=t,requestAnimationFrame(()=>requestAnimationFrame(()=>{xn()&&(oa(),requestAnimationFrame(()=>{if(!xn())return;let t=e.scrollHeight;t!==_e&&(_e=t,oa())}))})))});let[$n,er]=y(new Map),tr=()=>{let e=n();return e?$n().get(e)??null:null},ar=e=>{let t=n();t&&er(n=>{let r=new Map(n),i=typeof e==`function`?e(n.get(t)??null):e;return i?r.set(t,{...i,at:Date.now()}):r.delete(t),r})},sr=()=>{let e=tr();if(!e)return;let t=Dt(e,h(),B()?.status);t?(t.text!==e.text||t.reasoning!==e.reasoning)&&ar(t):ar(null)},[cr,ur]=y(``),[fr,pr]=y(0),mr=()=>fr(),[hr,z]=y(``),gr;x(()=>{tr()?gr||=setTimeout(()=>{gr=void 0,ur(tr()?.text??``),z(tr()?.reasoning??``)},(tr()?.text.length??0)>2e4?250:(tr()?.text.length??0)>6e3?120:60):(clearTimeout(gr),gr=void 0,ur(``),z(``))}),T(()=>clearTimeout(gr)),x(()=>{let t=e();er(e=>Et(e,e=>t.find(t=>t.id===e)?.status)),pr(e=>Ot(e,t,n(),tr()))}),x(()=>{let e=cr(),t=tr()?.reasoning??``;(e||t)&&requestAnimationFrame(()=>{xn()&&oa()})}),x(()=>{let e=B()?.pendingPrompts??0,t=B()?.pendingPromptIds,n=Tr(),r=Er(n),i=vn(r,e,t);i!==r&&Dr(n,i)}),x(()=>{let e=B()?.pendingPromptQueue;if(!e?.length)return;let t=B()?.session||Tr(),n=yn(Er(t),e);n!==Er(t)&&Dr(t,n)}),x(()=>{if(!n())return;let e=()=>{document.visibilityState===`visible`&&requestAnimationFrame(()=>{aa()&&(Tn(!0),Vn(0),sa(!0),Ir())})};document.addEventListener(`visibilitychange`,e),T(()=>document.removeEventListener(`visibilitychange`,e))});let B=S(()=>e().find(e=>e.id===n())),_r=()=>Yn({sameSession:!(B()?.session!==Tr()&&B()?.session),agent:B(),echoCount:Xr()}),vr=()=>{let e=B();return e?e.live??(e.status===`running`||e.status===`waiting`||e.status===`needs_operator`):!1},yr=()=>wn(B(),i(),vr()),[br,xr]=y(null);S(()=>{let e=new Set;for(let t of h())t.type===`tool_result`&&t.data?.name===`ask_user`&&e.add(String(t.data.callId));return e});let Sr=new Map,[Cr,wr]=y([]),Tr=()=>i()||n()||`?`,Er=e=>Sr.get(e)??[],Dr=(e,t)=>{let n=new Set,r=[];for(let e=t.length-1;e>=0;e--){let i=t[e],a=i.promptId;a?n.has(a)||(n.add(a),r.push(i)):r.push(i)}r.reverse(),r.length===0?Sr.delete(e):Sr.set(e,r),Tr()===e&&wr(r)},[Or,kr]=y([]),[Ar,jr]=y(localStorage.getItem(`teapot.hideGhosts`)===`1`),[Mr,Nr]=y(!1),Pr=()=>Or().filter(e=>!e.read).length,Fr=e=>{kr(t=>{let n=!1,r=t.map(t=>t.read||t.agentId!==e?t:(n=!0,{...t,read:!0}));return n?r:t})},Ir=()=>{let e=n();e&&Or().some(t=>!t.read&&t.agentId===e)&&Fr(e)},Lr=t=>{let n=Or().filter(e=>!e.read&&e.agentId===t).length;for(let r of e())r.parent===t&&(n+=Lr(r.id));return n},Rr=0,zr=e=>{kr(t=>[{...e,id:`n${++Rr}`,at:Date.now(),read:!1},...t].slice(0,50))},Br=(t,n)=>{if(n.type===`system_note`&&n.data?.event===`background-exit`){let r=e().find(e=>e.id===t)?.id??t,i=n.data.failed===!0,a=Math.round(Number(n.data.durationMs??0)/1e3);zr({agentId:t,kind:i?`error`:`progress`,title:`${r}: ${i?`⚠`:`✓`} background job ${String(n.data.jobId??`?`)} `+(i?`FAILED (exit ${String(n.data.code??`?`)})`:`finished (${a}s)`),body:String(n.data.cmd??``).slice(0,200)});return}let r=e().find(e=>e.id===t)?.id??t,i=typeof n.id==`string`?n.id:void 0;n.type===`message`&&n.data?.final===!0?zr({agentId:t,kind:`finish`,title:`${r} finished`,body:String(n.data.content??``).slice(0,300),eventId:i}):n.type===`question`?zr({agentId:t,kind:`question`,title:`${r} asks a question`,body:String(n.data.question??``).slice(0,300),eventId:i}):n.type===`error`?zr({agentId:t,kind:`error`,title:`${r} hit an error`,body:String(n.data.message??``).slice(0,300),eventId:i}):n.type===`progress`&&zr({agentId:t,kind:`progress`,title:`${r}: ${String(n.data.doing??`progress`)}`.slice(0,120),body:[n.data.recent&&`recent: ${n.data.recent}`,n.data.next&&`next: ${n.data.next}`].filter(Boolean).join(` · `).slice(0,300),eventId:i})},Vr=(e,t=0)=>{let n=i(),r=document.querySelector(`[data-eid="${CSS.escape(e)}"]`),a=!!r&&Qe(r.dataset.session,n);r&&a?(r.scrollIntoView({behavior:`smooth`,block:`center`}),r.classList.add(`flash-target`),setTimeout(()=>r.classList.remove(`flash-target`),1600)):t<30&&requestAnimationFrame(()=>Vr(e,t+1))},Hr=S(()=>{let e=new Map,t=new Set,n=new Map,r=new Map;for(let i of h())if(sD.has(i.type)){if(i.type===`tool_call`){let e=n.get(i.data.callId)??[];e.push(i),n.set(i.data.callId,e)}else if(i.type===`tool_result`){let a=n.get(i.data.callId)?.shift();a?(e.set(a.id,i),t.add(i.id)):r.set(i.id,i)}}return{resFor:e,consumed:t,orphanCalls:r}}),[Ur,Wr]=y(new Set),Gr=e=>{e&&Wr(t=>{if(t.has(e))return t;let n=new Set(t);return n.add(e),n})},Kr=()=>Wr(new Set),qr=S(()=>_n(h(),Ur())),Jr=S(()=>Wt({events:h(),consumed:Hr().consumed,pending:Cr(),echo:ei,feedTypes:sD,renderedTypes:lD,renderedNoteEvents:uD})),Yr=()=>Jr().rows,Xr=()=>Jr().pendingCount,Zr=S(()=>{let e=new WeakMap;return Yr().forEach((t,n)=>e.set(t,n)),e}),Qr=(e,t)=>{let n=Zr().get(e);if(n!==void 0)return Yr()[n+t]},$r=new Map;function ei(e){let t=`${e.id}:${e.sent?`s`:`p`}:${e.promptId??``}`,n=$r.get(t);if(n)return n;$r.size>64&&$r.clear();let r={id:e.id,seq:2**53-1,ts:new Date(e.at).toISOString(),session:B()?.session??``,branch:B()?.branch??`br0`,parent:null,type:`prompt`,data:{source:e.source??`user`,text:e.text,pending:!e.sent,...e.images?.length?{images:e.images}:{},...e.promptId?{promptId:e.promptId}:{}}};return $r.set(t,r),r}let ti=()=>Y(`/api/config`).then(ae).catch(()=>{}),[ni,ri]=y(!1);w(()=>{let e=()=>ri(!0);window.addEventListener(`teapot:unauthorized`,e),T(()=>window.removeEventListener(`teapot:unauthorized`,e))});let[ii,ai]=y(``),[oi,si]=y(!0),[ci,li]=y(!1),ui=``;x(()=>{let t=n(),r=e().find(e=>e.id===t)?.todo??``;t&&t!==ui?(ui=t,li(!1),ai(r)):t&&!ci()&&ai(r)});let di=async()=>{let e=document.getElementById(`todo-notify`)?.checked??!0;if(n())try{await Y(`/api/agents/${n()}/todo`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:ii(),notify:e})}),li(!1),si(!0),aD(`tasks saved${e&&ii().trim()?` & notification queued`:``}`),mi()}catch(e){aD(`save failed: ${e.message}`)}},fi=S(()=>{let e=0,t=0;for(let n of ii().split(`
183
- `)){let r=n.match(/^\s*[-*+] \[([ xX])\]/);r&&(e++,r[1].toLowerCase()===`x`&&t++)}return{total:e,done:t}});function pi(e,t){let n=new Map(e.map(e=>[e.id,e]));return t.map(e=>{let t=n.get(e.id);return t&&JSON.stringify(t)===JSON.stringify(e)?t:e})}let mi=()=>Y(`/api/agents`).then(e=>{let n=!1;t(t=>(t.length!==(e.agents??[]).length&&(n=!0),(e.agents??[]).some(e=>!t.some(t=>t.id===e.id))&&(n=!0),pi(t,e.agents??[]))),n&&m()}).catch(()=>{}),hi=()=>Y(`/api/metrics`).then(O).catch(()=>{}),[gi,_i]=y([]),vi=()=>Y(`/api/tasks`).then(e=>_i(e.tasks)).catch(()=>{}),yi=e=>gi().filter(t=>t.agent===e),[bi,xi]=y((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.expandedSubs`)??`[]`);return new Set(e.filter(e=>typeof e==`string`))}catch{return new Set}})()),[Si,Ci]=y((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.collapsed`)??`[]`);return new Set(e.filter(e=>typeof e==`string`&&!e.startsWith(`chat:`)))}catch{return new Set}})()),wi=e=>Si().has(e)||!bi().has(e),Ti=e=>{let t=new Set(bi());if(t.has(e)?t.delete(e):t.add(e),xi(t),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...t])),t.has(e)&&Si().has(e)){let t=new Set(Si());t.delete(e),Ci(t),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...t]))}},Ei=t=>mn(e(),t),[V,Di]=y((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.wsCollapsed`)??`[]`),t=Array.isArray(e)?e.filter(e=>typeof e==`string`):[];if(Number(localStorage.getItem(`teapot.wsCollapsed.v`)??`0`)<2){let e=t.filter(e=>!e.startsWith(`chat:`));return t.length-e.length>0&&localStorage.setItem(`teapot.wsCollapsed`,JSON.stringify(e)),localStorage.setItem(`teapot.wsCollapsed.v`,`2`),new Set(e)}return new Set(t)}catch{return new Set}})()),Oi=S(()=>{let e=new Set;for(let t of V())t.startsWith(`chat:`)&&e.add(t);return e}),H=S(()=>ln(e(),new Set(e().filter(e=>wi(e.id)).map(e=>e.id)),Ar(),Oi())),ki=(t,r,i,a)=>{let o=new Set(V());if(i)o.delete(t),a&&o.delete(a);else{o.add(t),a&&o.delete(a);let i=n();i&&(t===`chat:${i}`||Ei(e().find(e=>e.id===i))===t)&&aD(`hid ${r} — click the header to show it`)}Di(o);try{localStorage.setItem(`teapot.wsCollapsed`,JSON.stringify([...o]))}catch{}},Ai=e=>e.replace(/\/+$/,``).split(/[/\\]/).pop()||e,ji=e=>{let t=Mi().get(e)??0;return`${t} chat${t===1?``:`s`}`},Mi=S(()=>hn(e())),Ni=S(()=>gn(e(),H(),V())),[Pi,Fi]=y(null),Ii=new Map,Li=()=>{g([]),Ii.clear(),Ri=0},Ri=0;function zi(e){return`${i()||(n()??`?`)}:${e.id}`}function Bi(e){let t=Array.from({length:e.length});for(let n=0;n<e.length;n++){let r=e[n],i=zi(r),a=Ii.get(i);if(t[n]=a??r,!a)for(Ii.set(i,r),Ri+=fa(r);Ii.size>4e3||Ri>8388608;){let e=Ii.keys().next().value;if(e===void 0)break;let t=Ii.get(e);t&&(Ri-=fa(t)),Ii.delete(e)}}return t}let[Vi,Hi]=y(!1),[Ui,Wi]=y(!1),[Gi,Ki]=y(!1),qi=0,U=-1;function Ji(e){let t=Bi(e);g(e=>{if(t.length>0&&e.length>0){let n=e[e.length-1],r=t.every(e=>e.seq>n.seq),i=new Set(e.map(e=>e.id));if(r&&t.every(e=>!i.has(e.id)))return[...e,...t]}let n=new Map;for(let t of e)n.set(t.id,t);let r=!1;for(let e of t)n.has(e.id)||(n.set(e.id,e),r=!0);return r?[...n.values()].sort((e,t)=>e.seq-t.seq):e})}async function Yi(){let e=n();if(!e||Gi()||Vi()||xn())return;if(h().length>=_()){Ki(!0);return}let t=()=>{let e=ra();return e&&e.clientHeight>0?e:null},r=0;for(;r++<20&&!Gi()&&n()===e;){let r=t();if(r&&r.scrollHeight>r.clientHeight+40)return;if(h().length>=_()){Ki(!0);return}let i=h().length;if(await Xi(),h().length===i)return;Ge(ia())&&n()===e&&sa(!0)}}async function Xi(){let e=n(),t=h()[0];if(e&&t&&!Vi()&&!Gi()){Hi(!0);try{let r=ra(),a=r?.scrollHeight??0,o=r?.scrollTop??0,s=Pi(),c=i(),l=(await Y(Qi(e,{before:t.id},c,s))).events??[];if(l.length===0){Ki(!0);return}if(n()!==e||h()[0]?.id!==t.id)return;Ji(l),requestAnimationFrame(()=>{if(n()===e){let e=ra();e&&(e.scrollTop=o+(e.scrollHeight-a))}})}catch{}finally{Hi(!1)}}}function Zi(e,t){return t&&o().has(t)?`&session=${encodeURIComponent(t)}`:``}function Qi(e,t,n,r){let i=[`/api/agents/${encodeURIComponent(e)}/events?limit=2000`];t.before&&i.push(`&before=${encodeURIComponent(t.before)}`),t.after&&i.push(`&after=${encodeURIComponent(t.after)}`);let a=Zi(e,n);return a&&i.push(a),r&&i.push(`&branch=${encodeURIComponent(r)}&lineage=true`),i.join(``)}let $i=!1,[ea,ta]=y(!1);async function na(e,t){let r=qi,a=t??i()??``;try{let t=Pi(),i=r!==U||!ee().length;h().length||Wi(!0),Y(`/api/agents/${e}/skills`).then(t=>{r===qi&&n()===e&&Do(t.skills??[])}).catch(()=>{});let[o,s]=await Promise.all([Y(Qi(e,{},a,t)),i?Y(`/api/agents/${e}/branches`):Promise.resolve({branches:ee()})]);if(i&&(U=r),r!==qi||n()!==e)return;if($i){$i=!1,Ii.clear(),g(Bi(o.events)),ta(!1);let t=ra();t&&((la.get(a)??la.get(e))||(t.scrollTop=t.scrollHeight))}else g(e=>{let t=new Map;for(let n of e)t.set(n.id,n);for(let e of Bi(o.events))t.set(e.id,e);return[...t.values()].sort((e,t)=>e.seq-t.seq)});v(o.total??o.events.length),E(s.branches)}catch{$i&&($i=!1,ta(!1),Li())}finally{Wi(!1)}}function ra(){return document.querySelector(`.feed`)}function ia(){let e=ra();return e?{top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight}:null}function aa(){return Ge(ia())}function oa(){let e=ra();if(!e)return;let t=()=>e.isConnected?(e.scrollTop=e.scrollHeight,Bo={top:e.scrollTop,height:e.scrollHeight},!0):!1;if(!t())return;Vn(0);let n=r=>{e.isConnected&&xn()&&(Ye(xn(),{top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight})&&t(),r>0&&requestAnimationFrame(()=>n(r-1)))};requestAnimationFrame(()=>n(2)),On&&clearTimeout(On),On=setTimeout(()=>n(0),250)}function sa(e=!1){(e||xn())&&oa()}let ca=new Map,la=new Map,ua=(e,t=0,n=!1)=>{let r=n?e.getBoundingClientRect().top:-1/0,i=[];for(let a of e.querySelectorAll(`[data-eid]`)){let e=a.getBoundingClientRect();if(i.push({eid:a.dataset.eid??``,session:a.dataset.session??``,top:e.top+t,height:e.height}),n&&e.top>r+4)break}return i},da=8388608,fa=e=>at(e),pa=(t,n)=>bn(c().get(t),e().find(e=>e.id===t)?.session,n);async function ma(e,t=!0,s){let l=n(),u=i(),d=h(),f=_();qi++,c().size||m();let p=pa(e,s),ee=s&&o().has(s)?s:null,y=p??ee??``;if(l!==e||y!==u){if(u&&d.length){let e=d.reduce((e,t)=>e+fa(t),0);e<=da&&ca.set(u,{events:d,total:f,at:Date.now(),bytes:e}),it(ca,{maxEntries:6,maxBytes:da})}{let e=ra();if(ta(!0),e){let t=ua(e,0,!0),n=u||t.find(e=>e.session)?.session||``,r={top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight},i=n?zn(t,e.getBoundingClientRect().top,n):null;i&&We(r)>1?la.set(n,i):n&&la.delete(n)}}Kr(),$i=!0,ca.get(y)?.events.length||Li(),ta(!0),Xn(null),Vn(0),Tn(!0),zo=void 0}r(e),a(y),k(te.get(e)??``),Fi(null),Ki(!1),Hi(!1),Dr(u||l||`?`,Cr()),wr(Er(y||e)),localStorage.setItem(`teapot.session`,e),Ea(y,t);let b=ca.get(y);if(b?.events.length&&(g(Bi(b.events)),v(b.total),Wi(!0),requestAnimationFrame(()=>{n()===e&&sa(!0)})),Y(`/api/agents/${e}/load`,{method:`POST`}).then(mi).catch(()=>{}),await na(e,y),n()!==e)return;er(t=>{let n=t.get(e)??null,r=Dt(n,h(),B()?.status);if(r===n)return t;let i=new Map(t);return r?i.set(e,r):i.delete(e),i}),Xn(B()?.ctx?.compacting?{phase:String(B().ctx.compacting)}:null),Tn(!0);let x=qi,S=t=>{if(n()!==e||x!==qi||Date.now()<we)return;let r=ra();r&&We({top:r.scrollTop,height:r.scrollHeight,viewport:r.clientHeight})<=1||(sa(!0),t<12&&requestAnimationFrame(()=>S(t+1)))},C=()=>{let t=la.get(y)??la.get(e);if(!t)return`give-up`;let r=ra();if(!r)return`wait`;let i=ua(r,r.scrollTop);if(!i.length)return`wait`;let a=Bn(t,i,r.scrollHeight-r.clientHeight);if(a===null)return la.delete(y),la.delete(e),`give-up`;r.scrollTop=a,Tn(!1),we=performance.now()+400,la.delete(y),la.delete(e);let o=`[data-eid="${CSS.escape(t.eid)}"][data-session="${CSS.escape(t.session)}"]`,s=r=>{if(n()!==e)return;let i=ra();if(!i)return;let a=i.querySelector(o);if(!a)return;let c=i.getBoundingClientRect().top-t.offset,l=a.getBoundingClientRect().top-c;Math.abs(l)<2||r<=0||(i.scrollTop+=l,requestAnimationFrame(()=>s(r-1)))};return requestAnimationFrame(()=>s(6)),`applied`};(async()=>{if(await Yi(),n()!==e||x!==qi)return;let t=performance.now()+1500,r=()=>{if(n()!==e||x!==qi)return;let i=C();i!==`applied`&&(i===`wait`&&performance.now()<t?requestAnimationFrame(r):requestAnimationFrame(()=>S(0)))};requestAnimationFrame(r)})()}let[ha,ga]=y(!1),_a=null,va=null;T(()=>_a?.close());let ya=!1,ba=null;document.addEventListener(`visibilitychange`,()=>ba?.()),T(()=>{ba=null});let xa=!0,Sa=null;async function Ca(){let e=n(),t=h().at(-1)?.id,r=i(),a=document.visibilityState===`hidden`;if(!e||!t)ya=!0,a||Sa?.();else try{let n=Pi(),i=await Y(Qi(e,{after:t},r,n)),o=i.events??[];i.gap?(g(Bi(o)),v(o.length)):o.length&&(Ji(o),v(e=>e+o.length)),await mi(),o.length&&!a&&hi()}catch{ya=!0}}function wa(){xa=!0;let r=location.protocol===`https:`?`wss://`:`ws://`,a=new WebSocket(`${r}${location.host}/api/ws${fD()}`);_a=a,a.onopen=()=>{ga(!0),xa?xa=!1:Ca()},a.onclose=()=>{ga(!1),setTimeout(wa,1500)},a.onerror=()=>a.close();let o=new Set([`state`,`usage`,`session_start`]);a.onmessage=r=>{let s=JSON.parse(r.data);if(s.kind===`ping`)try{a.send(JSON.stringify({kind:`pong`}))}catch{}else if(s.kind!==`pong`){if(s.kind===`hello`&&Array.isArray(s.agents)){t(e=>pi(e,s.agents));let n=e();er(e=>Et(e,e=>n.find(t=>t.id===e)?.status))}else if(s.kind===`event`&&gt(s.event))er(e=>ht(e,s.agentId));else if(s.kind===`llm-delta`){if(!Cn(s,n(),i()))return;if(er(e=>mt(e,s.agentId,s)),s.agentId===n()){let e=String(s.reasoning??``),t=String(s.text??``);e&&!t?fr()||pr(Date.now()):t&&pr(0)}}else if(s.kind===`terminal-closed`&&s.terminalId)Ua(e=>{let t=e.findIndex(e=>e.key===s.terminalId);return t<0?e:(aD(s.reason===`idle`?`a terminal was closed after being idle — open a new shell with +`:`a terminal exited`),e.filter((e,n)=>n!==t))});else if(s.kind===`compaction-progress`){if(s.agentId!==n())return;s.phase===`done`?Xn(null):Xn({phase:s.phase,summarized:s.summarized})}else if(s.kind===`agent-update`&&s.snapshot)t(e=>{let t=e.findIndex(e=>e.id===s.snapshot.id),n=s.snapshot;return t===-1?[...e,n]:pi(e,e.map((e,n)=>n===t?s.snapshot:e))});else if(s.kind===`metrics`&&s.metrics)O(s.metrics);else if(s.kind===`tasks`&&Array.isArray(s.tasks))_i(s.tasks);else{if(s.kind===`event`){let e=s.event?.type,t=s.event?.data??{};if(e===`system_note`&&(t.event===`prompt-delivered`||t.event===`prompt-cancelled`)){let e=String(t.promptId??``);if(e){let t=String(s.event?.session??``),n=new Set;t&&n.add(t),n.add(Tr());for(let[t,r]of Sr)r.some(t=>t.promptId===e)&&n.add(t);for(let t of n){let n=Er(t);n.some(t=>t.promptId===e)&&Dr(t,n.filter(t=>t.promptId!==e))}}}if(o.has(e)&&!cD.has(e)||(Br(s.agentId,s.event),s.event?.agent!==n())||!Sn(s.event,n(),i())||(Ji([s.event]),s.event&&sr(),ya=!0,document.visibilityState!==`visible`))return;c()}document.visibilityState===`hidden`?ya=!0:c()}}};let s=0;function c(){s||=requestAnimationFrame(()=>{s=0,va&&=(clearTimeout(va),null),l()})}ya=!1;let l=async()=>{if(va=null,n()){let e=h().at(-1)?.id,t=h().length,r=tr();r&&!Dt(r,h(),B()?.status)&&ar(null),h().at(-1)?.id!==e&&(xn()?(oa(),Fr(n())):(Vn(e=>e+Math.max(0,h().length-t)),Wn(ia())))}};Sa=l,ba=()=>{document.visibilityState===`visible`&&(hi(),vi(),n()&&(ya?(ya=!1,l()):h().at(-1)?.id?Ca():(ya=!0,l())))}}let Ta=()=>decodeURIComponent(location.pathname.split(`/`)[2]??``);function Ea(e,t=!0){if(!e)return;let n=`/session/${encodeURIComponent(e)}`;t?history.pushState(null,``,n):history.replaceState(null,``,n)}window.addEventListener(`popstate`,()=>{let e=Ta(),t=o().get(e);t&&(t!==n()||e!==i())&&ma(t,!1,e||null)}),x(()=>{let e=B(),t=e?`${vr()?`▶ `:e.status===`error`?`⚠ `:``}${Kn(e)} · teapot`:`teapot`;document.title=Pr()>0?`(${Pr()}) ${t}`:t});let Da=()=>oe()||de()||br()!==null||me()&&ot();window.addEventListener(`keydown`,e=>{let t=e.target;if(t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable))e.key===`Escape`&&t.blur();else if(e.key===`Escape`){if(oe()){se(!1);return}if(de()){fe(!1);return}if(br()){xr(null);return}if(me()&&ot()){ft();return}let e=B();if(e&&vr()){Y(`/api/agents/${e.id}/stop`,{method:`POST`}).then(mi);return}}else if(!Da()){if(e.key===`/`)e.preventDefault(),document.querySelector(`.composer textarea`)?.focus();else if(e.key===`d`)lt();else if(e.key===`t`)Va();else if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=H().map(e=>e.a);if(t.length===0)return;e.preventDefault();let r=t.findIndex(e=>e.id===n()),i=e.key===`ArrowDown`?Math.min(r+1,t.length-1):Math.max(r-1,0);i!==r&&ma(t[i].id)}}});let[Oa,ka]=y(localStorage.getItem(`teapot.term`)===`1`),[Aa,ja]=y([]),[Ma,Na]=y(!1),Pa=async()=>{let e=n();if(!e)return;let t=await Y(`/api/agents/${encodeURIComponent(e)}/bg-jobs`).catch(()=>null);t?.jobs&&ja(t.jobs)};x(()=>{n(),Pa()}),x(()=>{if(!Ma())return;let e=setInterval(()=>void Pa(),2e3);T(()=>clearInterval(e))});let[Fa,Ia]=y(!1),[La,Ra]=y(``),za=()=>{let e=B();e&&(Ra(Kn(e)),Ia(!0))},Ba=async()=>{if(!Fa())return;let e=B();Ia(!1);let t=La().replace(/\s+/g,` `).trim();if(!e||!t||t===Kn(e))return;let n=await Y(`/api/agents/${encodeURIComponent(e.id)}/session-title?session=${encodeURIComponent(e.session)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({title:t})}).catch(e=>({error:String(e)}));n?.error?aD(`rename failed: ${n.error}`):(d(n=>new Map(n).set(e.session,t)),mi())},Va=()=>{let e=!Oa();ka(e),localStorage.setItem(`teapot.term`,e?`1`:`0`)},[Ha,Ua]=y([]),Wa=e=>{let t=(e.cwd??``).replace(/[\\/]+$/,``).split(/[\\/]/).pop();return t&&t.length<=24?t:e.title},Ga=async()=>{let e=(await Y(`/api/terminals`).catch(()=>null))?.terminals??[];e.length&&Ua(t=>t.map(t=>{let n=e.find(e=>e.id===t.key);return n?{...t,title:n.title,cwd:n.cwd}:t}))},[Ka,qa]=y(0),[Ja,Ya]=y(-1),[Xa,Za]=y(!1),[Qa,$a]=y(0),[eo,to]=y(Number(localStorage.getItem(`teapot.termH`))||Math.max(220,Math.round(window.innerHeight*.35))),no=new Map,ro=[null,null],io=()=>Ha()[Qa()===0?Ka():Ja()]??null;function ao(e){if(!Ha()[e])return;let t=Qa(),n=t===0?Ka():Ja(),r=t===0?Ja():Ka(),i=e=>t===0?qa(e):Ya(e);r===e?((e=>t===0?Ya(e):qa(e))(n),i(e)):n!==e&&i(e)}let oo=()=>so();async function so(e){let t=e??n();if(t){if(Ha().filter(e=>e.agentId===t).length>=10)aD(`max 10 shells per agent (${t}) — that's already a lot`);else try{let e=(await Y(`/api/terminals`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({agentId:t})})).terminal;if(!e){aD(`could not open a shell`);return}let n=sd(Ha());Ua(t=>[...t,{key:e.id,agentId:e.agentId,title:e.title,cwd:e.cwd}]),Qa()===0?qa(n):Ya(n)}catch(e){aD(`could not open a shell: ${e.message}`)}}}function co(e){let t=Ha()[e];if(!t)return;Y(`/api/terminals/${encodeURIComponent(t.key)}`,{method:`DELETE`}).catch(()=>{});let n=no.get(t.key);if(n){n.ro?.disconnect();try{n.ws.close()}catch{}n.term.dispose(),no.delete(t.key)}let r=Ha().filter((t,n)=>n!==e);Ua(r),qa(t=>ld(t,e,r.length)),Ya(t=>t===-1?-1:ld(t,e,r.length))}let lo=()=>+!ue();x(()=>{St(),bt(),Lt(),Tt(),Pt(),ue();let e=lo();for(let[,t]of no)Dn(t.term,e)});function uo(){for(let[,e]of no){e.ro?.disconnect();try{e.ws.close()}catch{}e.term.dispose()}no.clear()}function fo(e,t){let n=no.get(e.key);if(n&&Dn(n.term,lo()),n)n.el.parentElement!==t&&(t.appendChild(n.el),setTimeout(()=>{try{n.fit()}catch{}},30));else{let r=document.createElement(`div`);r.className=`termsession`,t.appendChild(r);let i=new rd({cursorBlink:!0,fontSize:12.5,scrollSensitivity:3,fontFamily:`ui-monospace, Menlo, Consolas, monospace`,allowTransparency:!0,theme:En(lo())});i.attachCustomKeyEventHandler(e=>{if(e.type!==`keydown`||!(e.ctrlKey&&e.shiftKey)||e.altKey||e.key!==`C`&&e.key!==`c`)return!0;let t=i.getSelection();return t&&navigator.clipboard?.writeText(t).catch(()=>{}),e.preventDefault(),!1});let a=new od;i.loadAddon(a),i.open(r);let o=location.protocol===`https:`?`wss://`:`ws://`,s=()=>`${o}${location.host}/api/agents/${encodeURIComponent(e.agentId)}/term?terminal=${encodeURIComponent(e.key)}${fD()}`,c=new WebSocket(s()),l,u=!1,d=t=>{t.onmessage=t=>{let n=JSON.parse(t.data);n.kind===`data`?i.write(n.data):n.kind===`ping`||(n.kind===`exit`?(u=!0,i.write(`\r\n\x1b[2m[terminal exited ${n.code??``}]\x1b[0m\r\n`),Ua(t=>t.filter(t=>t.key!==e.key)),no.get(e.key)?.term.dispose(),no.delete(e.key)):n.kind===`attach`&&n.error&&(u=!0,i.write(`\r\n\x1b[2m[${n.error}]\x1b[0m\r\n`)))},t.onclose=()=>{!u&&no.has(e.key)&&(l||=(i.write(`\r
182
+ Cancel = keep editing your copy`)?(ue(r.current),c({...t,content:r.current}),bf(`loaded the current file from disk`)):bf(`kept your edits — use Save As via bash to force-write`)}finally{fe(!1)}}},_e=e=>!e.binary&&!e.truncated,ve=(e,t)=>[(()=>{var n=Mw(),r=n.firstChild,a=r.nextSibling;return n.$$click=()=>e.dir?void ie(e):void he(e,`code`),R(r,(()=>{var t=P(()=>!!e.dir);return()=>t()?i().has(e.path)?`▾`:`▸`:Dw(e.name)})()),R(a,()=>e.name),R(n,j(N,{get when(){return P(()=>!e.dir)()&&e.size!==void 0},get children(){var t=jw();return R(t,()=>Rx(e.size)),t}}),null),b(r=>{var i=`filerow`+(e.dir?` isdir`:``)+(e.ignored&&v()===`dim`?` gitignored`:``),a=`padding-left:${t*13+8}px`,o=e.dir?`browse ${e.path}`:`preview ${e.path}`;return i!==r.e&&L(n,r.e=i),r.t=Oe(n,a,r.t),o!==r.a&&I(n,`title`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})(),j(N,{get when(){return P(()=>!!e.dir)()&&i().has(e.path)},get children(){return j(M,{get each(){return(n().get(e.path)??[]).filter(C)},children:e=>ve(e,t+1)})}})],ye=()=>e.workspace.split(`/`).filter(Boolean).pop()??e.workspace,[be,xe]=y(!1),Se=async()=>{if(!be()){xe(!0);try{let e=[``,...i()],t=await Promise.all(e.map(async e=>({p:e,rows:await ne(e,w())})));for(let{p:e,rows:n}of t)n&&re(e,n)}finally{xe(!1)}}};return[(()=>{var e=Nw(),t=e.firstChild.nextSibling;return t.firstChild,R(t,ye,null),R(e,j(vd,{class:`filetoggle`,get icon(){return be()?`…`:`⟳`},title:`refresh the tree (root + expanded folders) — open popups are kept`,onClick:()=>void Se()}),null),R(e,j(vd,{class:`filetoggle`,style:`margin-left:auto`,get icon(){return P(()=>v()===`hide`)()?`🙈`:v()===`dim`?`👁`:`✨`},get title(){return`gitignored files: ${v()} — click to cycle (dim → hidden → shown)`},onClick:S}),null),R(e,j(vd,{class:`filetoggle`,get icon(){return w()?`◉.`:`○.`},get title(){return w()?`dotfiles shown — click to hide`:`dotfiles hidden — click to show`},onClick:D}),null),e})(),(()=>{var e=Pw();return R(e,j(N,{get when(){return(n().get(``)??[]).length>0},get fallback(){return(()=>{var e=Fw();return R(e,()=>g()||`empty workspace`),e})()},get children(){return j(M,{get each(){return(n().get(``)??[]).filter(C)},children:e=>ve(e,0)})}})),e})(),j(N,{get when(){return o()},children:t=>j(bd,{get title(){return`🗂 ${t().path}`},onClose:()=>{pe++,c(null),f(null)},get children(){return j(N,{get when(){return u()},get fallback(){return[(()=>{var e=Bw(),n=e.firstChild;return R(e,j(N,{get when(){return P(()=>!!A(t().path))()&&!t().binary},get children(){var e=Rw();return e.$$click=()=>h(`md`),b(()=>L(e,p()===`md`?`on`:``)),e}}),n),n.$$click=()=>{h(`code`),ae()||me({path:t().path,content:t().content,truncated:t().truncated})},R(e,j(N,{get when(){return _e(t())},get children(){var e=zw();return e.$$click=()=>h(`edit`),b(()=>L(e,p()===`edit`?`on`:``)),e}}),null),b(()=>L(n,p()===`code`?`on`:``)),e})(),j(N,{get when(){return!t().binary},get fallback(){return Hw()},get children(){return j(N,{get when(){return p()===`edit`},get fallback(){return j(N,{get when(){return P(()=>p()===`md`)()&&A(t().path)},get fallback(){return j(mf,{get path(){return t().path},get content(){return t().content},get html(){return ae()},get pending(){return se()},get truncated(){return!!t().truncated}})},get children(){var e=Uw();return b(()=>e.innerHTML=Re(t().content)),e}})},get children(){var e=Vw(),n=e.firstChild,r=n.nextSibling.firstChild,i=r.firstChild,a=r.nextSibling;return n.$$input=e=>ue(e.currentTarget.value),I(n,`spellcheck`,!1),R(r,()=>Rx(le().length),i),a.$$click=()=>void ge(),R(a,()=>de()?`saving…`:`💾 save`),b(()=>a.disabled=de()||le()===t().content),b(()=>n.value=le()),e}})}})]},get children(){var t=Lw(),n=t.firstChild,r=n.firstChild;return R(t,j(N,{get when(){return u().kind===`image`},get fallback(){return j(N,{get when(){return u().kind===`video`},get fallback(){return(()=>{var t=Gw();return b(()=>I(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t})()},get children(){var t=Ww();return b(()=>I(t,`src`,`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`)),t}})},get children(){var t=Iw();return b(n=>{var r=`/api/agents/${e.agentId}/raw?path=${encodeURIComponent(u().path)}`,i=u().path.split(`/`).pop();return r!==n.e&&I(t,`src`,n.e=r),i!==n.t&&I(t,`alt`,n.t=i),n},{e:void 0,t:void 0}),t}}),n),R(n,()=>u().kind,r),t}})}})})]}Ee([`click`,`input`]);var qw=F(`<div class=overlay><div class=modal style=max-width:360px><div class=modal-head><b>🔒️ sign in</b><span></span></div><form style=display:flex;flex-direction:column;gap:10px><input id=pw-input type=password placeholder=password autofocus><button type=submit class=primarybtn>unlock</button><span class=muted style=font-size:11px>the token is stored locally and sent as Bearer to this server only`),Jw=F(`<div class=leftbarbackdrop>`),Yw=F(`<div class=sidehead><b>agents</b><button class=iconbtn title="close the agent list">✕`),Xw=F(`<i class=notifdot>`),Zw=F(`<br>`),Qw=F(`<button class="iconbtn ham"title="agent list">☰`),$w=F(`<input class="title titleedit">`),eT=F(`<span class="badge queued">⏳ <!> <!> queued`),tT=F(`<button type=button class="badge bgjobs">⚙️ `),nT=F(`<span class="badge cron">⏰ `),rT=F(`<div class=bgjobs-pop role=dialog aria-label="background shells"><div class=bgjobs-head><span>background shells</span><button type=button class=iconbtn title=close>✕`),iT=F(`<header class=chan-head><span class=hash title="rename this chat">#</span><span></span><span class=sub> · <!>/<!> · <!>↻ <!>⚙️</span><span class=head-actions><button></button><span class=head-sep aria-hidden=true>`),aT=F(`<div class=divider-msg>── beginning of log ──`),oT=F(`<div class=divider-msg>loading older events…`),sT=F(`<div class=feedloading><span class=spinner aria-hidden=true></span> loading timeline…`),cT=F(`<div class=feedloading><span class=spinner aria-hidden=true></span> loading newer events…`),lT=F(`<details class=reasoning open><summary>💭 thinking </summary><div class="mono thinkscroll">`),uT=F(`<div class=muted style=font-size:11.5px;margin-bottom:4px>🗜 summarizing older context…`),dT=F(`<div class=content>`),fT=F(`<div class="msg live"><div class=avatar style="background:#5865f233;border:1px solid #5865f266">🫖</div><div class=msg-body><div class=msg-head><span class=author style=color:var(--acc)>agent</span><span class=ts>streaming…`),pT=F(`<div class=feed>`),mT=F(`<div class="termempty muted">no shell here — + opens one, tabs fill the focused pane`),hT=F(`<div class=termsplit>`),gT=F(`<div class="termempty muted">no shell here — click a tab or + to add`),_T=F(`<div class=termpane>`),vT=F(`<div class=termdrawer><div class=termgrip title="drag to resize · double-click to reset"></div><div class=termbar><div class=termtabs></div><div style=display:flex;gap:4px;align-items:center><span class="muted mono"style=flex:1;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap></span></div></div><div class=termbody><div class=termpane>`),yT=F(`<button class=jump>↓ `),bT=F(`<div class=cmds>`),xT=F(`<div class=attachrow><button type=button class=attachclear title="remove every attachment">clear`),ST=F(`<label class=forkchip title="inherit the conversation prefix byte-exactly — the sub-agent's provider prefix cache starts warm"><input type=checkbox>fork ctx`),CT=F(`<div class="hint flashhint">`),wT=F(`<div><form><textarea rows=1></textarea><button type=button class="iconbtn maxbtn"></button><button type=submit>send</button><input id=composer-file type=file accept=image/* multiple style=display:none>`),TT=F(`<div class=rightbarbackdrop>`),ET=F(`<div><nav><div class=agent-list></div><div class=sidebar-footer><div class=footer-row style=justify-content:flex-end><button>🔔️</button></div><div class=brand-row><div class=brand>🫖 teapot <span class=version>v</span><span></span></div></div><div class=metrics></div></div></nav><section class=channel></section><aside><div class=rightbarhead><span class=muted>details`),DT=F(`<div class=notifbackdrop>`),OT=F(`<button class=editbtn>clear all`),kT=F(`<div class=notiflist>`),AT=F(`<div class=notifpanel><div class=notifhead>notifications<span style=display:flex;gap:8px;align-items:center><button class=iconbtn title="close notifications">✕`),jT=F(`<div class=bgphoto aria-hidden=true><img sizes=100vw alt decoding=async><span class=bgphoto-veil>`),MT=F(`<span class=wscount>`),NT=F(`<div class=wsheader><span class=wscaret></span><span class=wsname>`),PT=F(`<span class=notifbadge>🔔️`),FT=F(`<span class=subtag>🧩`),IT=F(`<span class=mini-cron>⏰`),LT=F(`<span class=goaldone title="goal done">✓`),RT=F(`<div><span></span><span>`),zT=F(`<span class=caret-spacer>`),BT=F(`<span class=caret>`),VT=F(`<span class=ghosttag title="workspace missing">👻`),HT=F(`<span>🧩 `),UT=F(`<div class=muted style=display:grid;place-items:center;height:100%>select an agent`),WT=F(`<span class=title>`),GT=F(`<div class="muted bgjobs-empty">no background jobs for this agent`),KT=F(`<pre class="mono bgjob-tail">`),qT=F(`<div class=bgjob><div class=bgjob-line><span></span><code class="mono bgjob-cmd"></code><span class="muted bgjob-meta"></span><button type=button class=bgjob-kill>`),JT=F(`<div class="muted bgjob-detached">this job outlived a harness restart, so its output is no longer captured here. it is still running as pid <!> — read its own log, or stop it yourself.`),YT=F(`<div class="divider-msg compacting"title="the harness is compressing old turns into notes so work can continue within the context window">🗜 `),XT=F(`<div class=muted style=display:grid;place-items:center;height:100%><span><span class=spinner aria-hidden=true></span> loading timeline…`),ZT=F(`<div class=muted style=display:grid;place-items:center;height:100%>no events yet — say something or press ▶ start`),QT=F(`<div class="content muted">thinking…`),$T=F(`<div class=lightbox role=dialog aria-modal=true aria-label="enlarged image"title="click to close"><img alt>`),eE=F(`<span>⌨ <button class=tabx title="close this shell">✕`),tE=F(`<div><b class=mono></b><span class=muted>`),nE=F(`<div class=cmdrow><b>@</b><span class=muted>`),rE=F(`<span class=imgchip><img title="click to enlarge"><button type=button class=imgx title=remove>✕`),iE=F(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> models`),aE=F(`<h3 title="switch provider/model live — applies from the agent's next turn">🧦 model`),oE=F(`<div style=display:flex;gap:6px;align-items:center;margin-top:6px><label class=muted style=font-size:11.5px;white-space:nowrap>effort</label><select style=flex:1;min-width:0><option value>provider default`),sE=F(`<div class=meta style=color:var(--fg)>`),cE=F(`<div class=modelbox><select title="provider (OpenAI-compatible endpoint)"></select><div style=display:flex;gap:4px><input type=text list=model-list style=flex:1;min-width:0><datalist id=model-list></datalist></div><div style=display:flex;gap:6px;align-items:center;margin-top:6px><button title="apply the provider, model and effort above to this session — takes effect from the agent's next turn"style=flex:1>apply</button></div><div class=meta>current: `),lE=F(`<span>`),uE=F(`<h3 title="what the agent is working toward. Stored with the session; the agent reads it via get_goal(). Auto-continue keeps looping while the status is 'active' and stops when marked done.">🎯 goal`),dE=F(`<div class=statrow style=margin-bottom:6px><span class=k>status`),fE=F(`<div class="card goalcard"><div class=content>`),pE=F(`<form style=display:flex;flex-direction:column;gap:6px;margin-top:8px;margin-bottom:6px><textarea id=goal-input rows=3 placeholder="set new goal…"title="drag the bottom edge to make this taller — the height is remembered"style="background:var(--bg-darkest);border:none;border-radius:6px;padding:6px 8px;color:var(--fg);font:inherit;width:100%;resize:vertical"></textarea><textarea id=goal-verify-input rows=2 placeholder="verification contract (optional) — e.g. 'npm test passes; endpoint documented'. finish(goalComplete=true) is then audited against this."title="pi-goal-x-style verification contract — an independent reviewer checks the agent's finish against these requirements"style="background:var(--bg-darkest);border:1px solid var(--bg-light);border-radius:6px;padding:6px 8px;color:var(--fg);font:inherit;font-size:12.5px;width:100%;resize:vertical"></textarea><div style=display:flex;justify-content:flex-end;align-items:center;gap:10px><label class=muted title="auto-continue acts on the GOAL above: it fires after a round ONLY when all hold — ① this toggle is on ② a goal is set and its status is 'active' ③ the round ended cleanly (no error / not stopped). It stops when the goal is marked done, or if you press ■ stop."style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input type=checkbox>auto-continue</label><label class=muted title="queue a harness prompt telling the agent about the new goal at its next turn boundary"style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input id=goal-notify type=checkbox> notify agent</label><button type=submit class=primarybtn>✓ save goal`),mE=F(`<span class=badge>/<!> done`),hE=F(`<h3 title="todo.md — a shared checklist in the session dir. Write tasks like '- [ ] fix login'; the agent ticks them off via set_todo, you edit here. With notify on, it's told at its next turn boundary.">✅ tasks`),gE=F(`<div class=bartrack style=margin-bottom:6px><div>`),_E=F(`<div style=display:flex;justify-content:flex-end;align-items:center;gap:10px;margin-top:4px><label class=muted title="queue a harness prompt telling the agent the task list changed"style=display:flex;align-items:center;gap:4px;font-size:11.5px;white-space:nowrap;cursor:pointer><input id=todo-notify type=checkbox checked> notify agent</label><button class=okbtn>✓ save tasks`),vE=F(`<h3 title="latest report_progress snapshot. The harness asks for one after real activity (time AND output gates); errors show under ⚠ problems">📈 progress`),yE=F(`<h3 title="context is how much of the model's window the live conversation occupies. Past the threshold, the oldest turns are summarized into notes so work can continue.">📊 runtime`),bE=F(`<div class=rtcell><span>cost</span><b>$`),xE=F(`<div class=rtcell><span>cached</span><b>%`),SE=F(`<div class="card runcard"><div class=rtgrid><div class=rtcell title="prompt tokens billed this session"><span>tokens in</span><b></b></div><div class=rtcell title="completion tokens billed this session"><span>tokens out</span><b></b></div><div class=rtcell title="assistant turns this session"><span>turns</span><b></b></div><div class=rtcell title="tool calls this session"><span>tools</span><b></b></div><div class=rtcell><span>compacted</span><b>`),CE=F(`<div class=muted style=font-size:11px;text-transform:none;letter-spacing:0>showing <b></b> and the history it inherited before forking`),wE=F(`<h3>🌿 branches <span class=muted style=text-transform:none;letter-spacing:0>· click to filter the feed`),TE=F(`<span class=muted style=text-transform:none;letter-spacing:0>· <!> · all agents`),EE=F(`<h3 title="cron tasks, all agents — click a row to open that agent. Edit them in ⚙️ settings → scheduled tasks.">⏰ schedule`),DE=F(`<option>`),OE=F(`<span class=badge title="no goal set yet">no goal`),kE=F(`<button>`),AE=F(`<div class="card muted">no goal yet — write one below and press ✓ save. Then ▶ start (or any message) sets it in motion.`),jE=F(`<div class=muted>none yet`),ME=F(`<div class=progrow><b>recent</b><span class="content inline-md">`),NE=F(`<div class="progrow warn"><b>⚠ problems</b><span class="content inline-md">`),PE=F(`<div class=progrow><b>next</b><span class="content inline-md">`),FE=F(`<div class=progrow><b>goal</b><span>`),IE=F(`<div class="card prog"><div class=progrow><b>doing</b><span class="content inline-md"></span></div><div class="meta muted">`),LE=F(`<div class=statrow><span class=k>context</span><span class=muted>no window known for this model yet`),RE=F(`<span>% of `),zE=F(`<div class=bartrack><div>`),BE=F(`<div class=statrow title="a compaction pass is running right now — the summarizer's output streams in the timeline"><span class=k>🗜</span><b>compacting…</b><span class=muted style=font-size:11px;color:var(--acc)>`),VE=F(`<div class=ctxblock title="estimated live context vs the model's real window. Past the window, old turns are summarized into notes (compaction); the compact line below shows where that starts."><div class=statrow><span class=k>context</span><b>~<!> tok</b></div><div class=statrow style=margin-top:4px><span class=k>compact at</span><b> tok</b><span class=muted style=color:var(--dim)></span></div><div class=ctrlrow style=margin-top:6px><label title="when on, older turns are automatically summarized when context exceeds the budget"><input type=checkbox>auto-compact`),HE=F(`<div><span></span><span> events`),UE=F(`<div class=muted>no scheduled tasks — add them in ⚙️ settings ("scheduled tasks")`),WE=F(`<span title="runs on a forked branch so chatter stays off the main line">⑂`),GE=F(`<div><div class=sched-top><b></b><span class=muted>@</span></div><div class=sched-meta> → next </div><div class="sched-prompt muted">`),KE=F(`<div class=muted style=padding:10px>nothing yet — progress, finishes, questions and errors will land here`),qE=F(`<div class=nbody>`),JE=F(`<div><div class=nhead><span class=nicon></span><span class=ntitle></span><span class="meta muted"></span><button class="iconbtn nreadbtn">`),YE=F(`<div style=font-size:12.5px;color:var(--dim)> event(s) came after this prompt and will be discarded — the new branch starts from your edited text.`),XE=F(`<form style=display:flex;flex-direction:column;gap:10px><textarea id=edit-text class="mono w100"rows=6></textarea><div style=display:flex;justify-content:flex-end;gap:8px><button type=button>cancel</button><button type=submit class=primarybtn>⑂ fork & resend`),ZE=F(`<span style=color:var(--err);font-size:13px>`),QE=F(`<form style=display:flex;flex-direction:column;gap:10px><label>workspace directory<div style=display:flex;gap:6px><input type=text class="w100 mono"><button type=button>go</button><button type=button title="parent directory">↑</button></div></label><div class=dirlist></div><div style=display:flex;gap:10px><label style=flex:1>agent name <input type=text placeholder="(directory name)"></label><label style="flex:0 1 auto;min-width:0">provider<select></select></label><label style=flex:1>model <input type=text placeholder="(provider default)"></label></div><button type=submit style=align-self:flex-end>create`),$E=F(`<div class=direntry>📁 `),eD=[`minimal`,`low`,`medium`,`high`],tD=1100,[nD,rD]=y(``),iD,aD=e=>{rD(e),clearTimeout(iD),iD=setTimeout(()=>rD(``),3200)},oD=!1,sD=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`state`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`audit_step`,`system_note`]),cD=new Set([`system_note`]),lD=new Set([`user`,`message`,`prompt`,`tool_call`,`tool_result`,`progress`,`error`,`fork`,`goal`,`todo`,`question`,`decision`,`compaction`,`audit_step`]),uD=new Set([`runaway-detected`,`error-retry`,`background-exit`,`context-compacted`,`context-compaction-started`]),dD=location.hash.match(/[#&]token=([^&]+)/);dD&&(localStorage.setItem(`teapot.token`,decodeURIComponent(dD[1])),history.replaceState(null,``,location.pathname+location.search));var fD=()=>{let e=localStorage.getItem(`teapot.token`);return e?`?token=${encodeURIComponent(e)}`:``};function pD(){let[e,t]=y([]),[n,r]=y(null),[i,a]=y(``),[o,s]=y(new Map),[c,l]=y(new Map),[u,d]=y(new Map),f=!1,p=null;async function m(e=!1){if(p)return p;if(f&&!e)return;let t=(async()=>{try{let e=await Y(`/api/sessions`),t=new Map,n=new Map,r=new Map;for(let i of e.sessions??[]){t.set(i.id,i.agentId),typeof i.title==`string`&&i.title&&r.set(i.id,i.title);let e=n.get(i.agentId)??[];e.push(i.id),n.set(i.agentId,e)}s(t),l(n),d(r),f=!0}catch{}})();p=t;try{await t}finally{p===t&&(p=null)}}let[h,g]=y([]),[_,v]=y(0),[ee,E]=y([]),[D,O]=y(null),te=new Map,[ne,re]=y(te.get(n()??``)??``),k=e=>{re(e);let t=n();t&&(e?te.set(t,e):te.delete(t))},[ie,ae]=y({providers:{}}),[oe,se]=y(!1),ce=()=>lr({want:dr({preview:It(),auto:Mt(),prefersLight:Ut(),dark:Bt(),light:Pt(),fixed:At()}),customIds:Rt().map(e=>e.id),presetIds:Yd.map(e=>e.key),fallback:`dark`}),le=()=>ce().active,ue=()=>Rt().find(e=>e.id===le())?.backgroundImage??``,[de,fe]=y(!1),A=!1;x(()=>{!A&&ie()?.needsSetup&&(A=!0,requestAnimationFrame(()=>{si(),fe(!0)}))}),x(()=>{de()&&!Po()&&Y(`/api/features`).then(e=>Fo(e)).catch(()=>Fo(null))});let pe=new Set,me=()=>window.innerWidth<=tD,[he,ge]=y(me());w(()=>{let e=()=>{let e=me();e!==he()&&(ge(e),(localStorage.getItem(ft(e))!==null||!e)&&yt(_t(e)))};window.addEventListener(`resize`,e),T(()=>window.removeEventListener(`resize`,e)),e()});let _e=0,ve=null,ye=0,be,xe,Se=0,Ce=0,we=0,Te=()=>{if(performance.now()<Fe){let e=la();e&&Be(e);return}if(Un()||!ve)return;let e=la();if(!e)return;if(!Ze(performance.now(),Ce)||e.scrollHeight===qo){ve=lt(e),ye=performance.now();return}if(!F(e))return;let t=e.scrollHeight;Ue(e,ve,Yo),qo=e.scrollHeight,t!==qo&&(Ko={top:e.scrollTop,height:e.scrollHeight})},F=e=>{if(!ve)return!1;let t=lt(e);return t?t.sel===ve.sel||(ve=t,ye=performance.now(),!1):!1},Ee=()=>{Se||=requestAnimationFrame(()=>{Se=0,Te()})},je,Me,Ne=0,Pe=``,Fe=0,Ie=0,Le=()=>{if(Ie=0,performance.now()>=Fe)return;let e=la();e&&We({top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight})>1&&Be(e),Ie=requestAnimationFrame(Le)},ze=(e=1500)=>{Fe=performance.now()+e,Ie||=requestAnimationFrame(Le)},Be=e=>{e.scrollTop=e.scrollHeight,Ko={top:e.scrollTop,height:e.scrollHeight},Wn(!0),Zn(0),ve=lt(e),ye=performance.now()},Ve=0,He=()=>{Ne=0;let e=la();if(!e)return;let t=e.scrollHeight!==qo;qo=e.scrollHeight,Xo=e.clientHeight;let n=e.clientWidth!==Ve;Ve=e.clientWidth,Un()||performance.now()<Fe?fa():n&&ve?(Ue(e,ve,1200),er(ua())):t?Ze(performance.now(),Ce)?(F(e)&&Ue(e,ve,Jo),er(ua())):(ve=lt(e),ye=performance.now(),er(ua())):er(ua())};function Ue(e,t,n=Jo){if(!t)return;let r=e.querySelector(t.sel);if(!r)return;let i=r.getBoundingClientRect().top-t.top;Math.abs(i)<1||Math.abs(i)>n||(e.scrollTop+=i,Ko={top:e.scrollTop,height:e.scrollHeight})}let $e=()=>{Ne||=requestAnimationFrame(He)},et=null,ot=e=>{et?.();let t=e=>{Ln(e.deltaY)&&(we=performance.now()+400,Un()&&Wn(!1))},n=()=>{we=performance.now()+400,Un()&&Wn(!1)},r=e=>{Rn(e.key)&&n()};e.addEventListener(`wheel`,t,{passive:!0}),e.addEventListener(`touchmove`,n,{passive:!0}),e.addEventListener(`touchstart`,n,{passive:!0}),e.addEventListener(`pointerdown`,n,{passive:!0}),window.addEventListener(`keydown`,r,{capture:!0}),et=()=>{e.removeEventListener(`wheel`,t),e.removeEventListener(`touchmove`,n),e.removeEventListener(`touchstart`,n),e.removeEventListener(`pointerdown`,n),window.removeEventListener(`keydown`,r,{capture:!0}),et=null}},st=e=>{e&&(ot(e),e!==Me&&(je??=new ResizeObserver(e=>{let t=e[0]?.contentRect,n=t?`${Math.round(t.width)}x${Math.round(t.height)}`:``;n!==Pe&&(Pe=n,$e())}),Me&&je.unobserve(Me),Me=e,Pe=``,je.observe(e),typeof MutationObserver<`u`&&(be??=new MutationObserver(Ee),xe&&xe!==e&&xe.removeEventListener(`load`,Ee,!0),xe=e,be.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),e.addEventListener(`load`,Ee,!0))))};w(()=>{window.addEventListener(`resize`,$e),T(()=>{window.removeEventListener(`resize`,$e),je?.disconnect(),je=void 0,Me=void 0,be?.disconnect(),be=void 0,xe&&xe.removeEventListener(`load`,Ee,!0),xe=void 0,Se&&cancelAnimationFrame(Se),Ne&&cancelAnimationFrame(Ne)})});let ct=e=>`[data-eid="${globalThis.CSS?.escape?.(e)??e.replace(/["\\]/g,`\\$&`)}"]`;function lt(e){let t=e.querySelectorAll(`[data-eid]`);if(!t.length)return null;let n=e.getBoundingClientRect().top,r=e=>t[e].getBoundingClientRect(),i=0,a=t.length-1,o=-1;for(;i<=a;){let e=i+a>>1;r(e).bottom>n?(o=e,a=e-1):i=e+1}if(o<0)return null;let s=t[o].dataset.eid??``;return s?{sel:ct(s),top:r(o).top}:null}let ft=e=>e?`teapot.panel.narrow`:`teapot.panel`,_t=e=>{let t=localStorage.getItem(ft(e));return t===null?!e:t===`1`},[vt,yt]=y(_t(me())),bt=e=>{yt(e),localStorage.setItem(ft(he()),e?`1`:`0`)},xt=()=>bt(!vt()),St=()=>{vt()&&bt(!1)},[wt,Tt]=y(!1),kt=()=>Tt(!1),[At,jt]=y(localStorage.getItem(`teapot.theme`)??`dark`),[Mt,Nt]=y(localStorage.getItem(`teapot.theme.auto`)===`1`),[Pt,Ft]=y(localStorage.getItem(`teapot.theme.light`)??`light`),[It,Lt]=y(null),[Rt,zt]=y(nr());w(()=>{ir().then(e=>{if(e===null)return;let t=tn(Rt(),e);zt(t),rr(t)})});let[Bt,Vt]=y(localStorage.getItem(`teapot.theme.dark`)??`dark`),Ht=typeof window.matchMedia==`function`?window.matchMedia(`(prefers-color-scheme: light)`):null,[Ut,Gt]=y(Ht?.matches??!1);w(()=>{let e=e=>Gt(e.matches);Ht?.addEventListener(`change`,e);let t=()=>{if(document.visibilityState!==`visible`)return;let e=Ht?.matches??!1;e!==Ut()&&Gt(e)};document.addEventListener(`visibilitychange`,t),T(()=>{Ht?.removeEventListener(`change`,e),document.removeEventListener(`visibilitychange`,t)})}),x(()=>{let{active:e,repaired:t}=ce(),n=Rt().find(t=>t.id===e)??null;t&&(Mt()?localStorage.setItem(Ut()?`teapot.theme.light`:`teapot.theme.dark`,e):localStorage.setItem(`teapot.theme`,e)),document.documentElement.dataset.theme=e,or(document.documentElement,n),document.documentElement.dataset.appearance=n?.mode??Yd.find(t=>t.key===e)?.mode??`dark`});let[qt,Jt]=y(``),[Yt,Xt]=y(``),[Zt,Qt]=y(``);x(()=>{let t=n();Qt(C(()=>e().find(e=>e.id===t)?.reasoningEffort??``))});let[rn,an]=y([]),on=()=>Object.keys(ie().providers??{});async function un(e){if(e)try{let t=await Y(`/api/models?provider=${encodeURIComponent(e)}`);an(t.models??[])}catch{an([])}}let xn=e=>{let t={text:`📄`,image:`🖼️`,audio:`🔊`,video:`🎬️`,file:`📎`},n=e=>(e??[`text`]).map(e=>t[e]??e).join(``);return e?.modalities?`${n(e.modalities.input)} → ${n(e.modalities.output)}`:``},Tn=()=>{let e=Yt().trim()||B()?.model||``;if(!e)return``;let t=rn().find(t=>t.id===e);if(!t)return``;let n=[],r=xn(t);r&&r!==`📄 → 📄`&&n.push(r),t.contextLength&&n.push(`ctx ${Rx(t.contextLength)} tok`);let i=e=>e===void 0?``:`${e*1e6>=10?Math.round(e*1e6):+(e*1e6).toFixed(1)}/M`;if(t.pricing){let e=i(t.pricing.prompt),r=i(t.pricing.completion);e&&r?n.push(`${e} in · ${r} out`):(e||r)&&n.push(i(t.pricing.prompt??t.pricing.completion))}return n.join(` · `)},On=null,An=!1;x(()=>{let t=n();if(!t)return;let r=e().find(e=>e.id===t),i=r?.provider||ie().defaultProvider||on()[0]||``;if(r){if(t!==On)On=t,An=!1,C(()=>qt())!==i&&(Jt(i),un(i)),C(()=>Yt())&&Xt(``);else{let e=C(()=>qt());!C(()=>Yt())&&e!==i&&Nn(An)&&(Jt(i),un(i))}}});let[Vn,Hn]=y(!1),[Un,Wn]=y(!0),Jn,[Xn,Zn]=y(0),[Qn,$n]=y(-1),er=e=>$n(e?Xe(e):-1),[tr,ar]=y(null),sr=()=>z().startsWith(`[compact] `),cr=()=>{let e=sr()?z().slice(10):z();return e.length>1200?`…`+e.slice(-1200):e};x(()=>{tr()||mr(e=>e?.text.startsWith(`[compact] `)?null:e)}),x(()=>{h().length,_(),tr(),ti().length,Xi(),Ji(),qi();let e=la();if(!e)return;let t=e.scrollHeight;t!==_e&&(_e=t,requestAnimationFrame(()=>requestAnimationFrame(()=>{Un()&&(fa(),requestAnimationFrame(()=>{if(!Un())return;let t=e.scrollHeight;t!==_e&&(_e=t,fa())}))})))});let[ur,fr]=y(new Map),pr=()=>{let e=n();return e?ur().get(e)??null:null},mr=e=>{let t=n();t&&fr(n=>{let r=new Map(n),i=typeof e==`function`?e(n.get(t)??null):e;return i?r.set(t,{...i,at:Date.now()}):r.delete(t),r})},hr=()=>{let e=pr();if(!e)return;let t=Dt(e,h(),B()?.status);t?(t.text!==e.text||t.reasoning!==e.reasoning)&&mr(t):mr(null)},[z,gr]=y(``),[_r,vr]=y(0),yr=()=>_r(),[br,xr]=y(``),Sr;x(()=>{pr()?Sr||=setTimeout(()=>{Sr=void 0,gr(pr()?.text??``),xr(pr()?.reasoning??``)},(pr()?.text.length??0)>2e4?250:(pr()?.text.length??0)>6e3?120:60):(clearTimeout(Sr),Sr=void 0,gr(``),xr(``))}),T(()=>clearTimeout(Sr)),x(()=>{let t=e();fr(e=>Et(e,e=>t.find(t=>t.id===e)?.status)),vr(e=>Ot(e,t,n(),pr()))}),x(()=>{let e=z(),t=pr()?.reasoning??``;(e||t)&&requestAnimationFrame(()=>{Un()&&fa()})}),x(()=>{let e=B()?.pendingPrompts??0,t=B()?.pendingPromptIds,n=jr(),r=Mr(n),i=vn(r,e,t);i!==r&&Nr(n,i)}),x(()=>{let e=B()?.pendingPromptQueue;if(!e?.length)return;let t=B()?.session||jr(),n=yn(Mr(t),e);n!==Mr(t)&&Nr(t,n)}),x(()=>{if(!n())return;let e=()=>{document.visibilityState===`visible`&&requestAnimationFrame(()=>{da()&&(Wn(!0),Zn(0),pa(!0),Hr())})};document.addEventListener(`visibilitychange`,e),T(()=>document.removeEventListener(`visibilitychange`,e))});let B=S(()=>e().find(e=>e.id===n())),Cr=()=>Yn({sameSession:!(B()?.session!==jr()&&B()?.session),agent:B(),echoCount:ni()}),wr=()=>{let e=B();return e?e.live??(e.status===`running`||e.status===`waiting`||e.status===`needs_operator`):!1},Tr=()=>wn(B(),i(),wr()),[Er,Dr]=y(null);S(()=>{let e=new Set;for(let t of h())t.type===`tool_result`&&t.data?.name===`ask_user`&&e.add(String(t.data.callId));return e});let Or=new Map,[kr,Ar]=y([]),jr=()=>i()||n()||`?`,Mr=e=>Or.get(e)??[],Nr=(e,t)=>{let n=new Set,r=[];for(let e=t.length-1;e>=0;e--){let i=t[e],a=i.promptId;a?n.has(a)||(n.add(a),r.push(i)):r.push(i)}r.reverse(),r.length===0?Or.delete(e):Or.set(e,r),jr()===e&&Ar(r)},[Pr,Fr]=y([]),[Ir,Lr]=y(localStorage.getItem(`teapot.hideGhosts`)===`1`),[Rr,zr]=y(!1),Br=()=>Pr().filter(e=>!e.read).length,Vr=e=>{Fr(t=>{let n=!1,r=t.map(t=>t.read||t.agentId!==e?t:(n=!0,{...t,read:!0}));return n?r:t})},Hr=()=>{let e=n();e&&Pr().some(t=>!t.read&&t.agentId===e)&&Vr(e)},Ur=t=>{let n=Pr().filter(e=>!e.read&&e.agentId===t).length;for(let r of e())r.parent===t&&(n+=Ur(r.id));return n},Wr=0,Gr=e=>{Fr(t=>[{...e,id:`n${++Wr}`,at:Date.now(),read:!1},...t].slice(0,50))},Kr=(t,n)=>{if(n.type===`system_note`&&n.data?.event===`background-exit`){let r=e().find(e=>e.id===t)?.id??t,i=n.data.failed===!0,a=Math.round(Number(n.data.durationMs??0)/1e3);Gr({agentId:t,kind:i?`error`:`progress`,title:`${r}: ${i?`⚠`:`✓`} background job ${String(n.data.jobId??`?`)} `+(i?`FAILED (exit ${String(n.data.code??`?`)})`:`finished (${a}s)`),body:String(n.data.cmd??``).slice(0,200)});return}let r=e().find(e=>e.id===t)?.id??t,i=typeof n.id==`string`?n.id:void 0;n.type===`message`&&n.data?.final===!0?Gr({agentId:t,kind:`finish`,title:`${r} finished`,body:String(n.data.content??``).slice(0,300),eventId:i}):n.type===`question`?Gr({agentId:t,kind:`question`,title:`${r} asks a question`,body:String(n.data.question??``).slice(0,300),eventId:i}):n.type===`error`?Gr({agentId:t,kind:`error`,title:`${r} hit an error`,body:String(n.data.message??``).slice(0,300),eventId:i}):n.type===`progress`&&Gr({agentId:t,kind:`progress`,title:`${r}: ${String(n.data.doing??`progress`)}`.slice(0,120),body:[n.data.recent&&`recent: ${n.data.recent}`,n.data.next&&`next: ${n.data.next}`].filter(Boolean).join(` · `).slice(0,300),eventId:i})},qr=(e,t=0)=>{let n=i(),r=document.querySelector(ct(e)),a=!!r&&Qe(r.dataset.session,n);r&&a?(r.scrollIntoView({behavior:`smooth`,block:`center`}),r.classList.add(`flash-target`),setTimeout(()=>r.classList.remove(`flash-target`),1600)):t<30&&requestAnimationFrame(()=>qr(e,t+1))},Jr=S(()=>{let e=new Map,t=new Set,n=new Map,r=new Map;for(let i of h())if(sD.has(i.type)){if(i.type===`tool_call`){let e=n.get(i.data.callId)??[];e.push(i),n.set(i.data.callId,e)}else if(i.type===`tool_result`){let a=n.get(i.data.callId)?.shift();a?(e.set(a.id,i),t.add(i.id)):r.set(i.id,i)}}return{resFor:e,consumed:t,orphanCalls:r}}),[Yr,Xr]=y(new Set),Zr=e=>{e&&Xr(t=>{if(t.has(e))return t;let n=new Set(t);return n.add(e),n})},Qr=()=>Xr(new Set),$r=S(()=>_n(h(),Yr())),ei=S(()=>Wt({events:h(),consumed:Jr().consumed,pending:kr(),echo:oi,feedTypes:sD,renderedTypes:lD,renderedNoteEvents:uD})),ti=()=>ei().rows,ni=()=>ei().pendingCount,ri=S(()=>{let e=new WeakMap;return ti().forEach((t,n)=>e.set(t,n)),e}),ii=(e,t)=>{let n=ri().get(e);if(n!==void 0)return ti()[n+t]},ai=new Map;function oi(e){let t=`${e.id}:${e.sent?`s`:`p`}:${e.promptId??``}`,n=ai.get(t);if(n)return n;ai.size>64&&ai.clear();let r={id:e.id,seq:2**53-1,ts:new Date(e.at).toISOString(),session:B()?.session??``,branch:B()?.branch??`br0`,parent:null,type:`prompt`,data:{source:e.source??`user`,text:e.text,pending:!e.sent,...e.images?.length?{images:e.images}:{},...e.promptId?{promptId:e.promptId}:{}}};return ai.set(t,r),r}let si=()=>Y(`/api/config`).then(ae).catch(()=>{}),[ci,li]=y(!1);w(()=>{let e=()=>li(!0);window.addEventListener(`teapot:unauthorized`,e),T(()=>window.removeEventListener(`teapot:unauthorized`,e))});let[ui,di]=y(``),[fi,pi]=y(!0),[mi,hi]=y(!1),gi=``;x(()=>{let t=n(),r=e().find(e=>e.id===t)?.todo??``;t&&t!==gi?(gi=t,hi(!1),di(r)):t&&!mi()&&di(r)});let _i=async()=>{let e=document.getElementById(`todo-notify`)?.checked??!0;if(n())try{await Y(`/api/agents/${n()}/todo`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:ui(),notify:e})}),hi(!1),pi(!0),aD(`tasks saved${e&&ui().trim()?` & notification queued`:``}`),bi()}catch(e){aD(`save failed: ${e.message}`)}},vi=S(()=>{let e=0,t=0;for(let n of ui().split(`
183
+ `)){let r=n.match(/^\s*[-*+] \[([ xX])\]/);r&&(e++,r[1].toLowerCase()===`x`&&t++)}return{total:e,done:t}});function yi(e,t){let n=new Map(e.map(e=>[e.id,e]));return t.map(e=>{let t=n.get(e.id);return t&&JSON.stringify(t)===JSON.stringify(e)?t:e})}let bi=()=>Y(`/api/agents`).then(e=>{let n=!1;t(t=>(t.length!==(e.agents??[]).length&&(n=!0),(e.agents??[]).some(e=>!t.some(t=>t.id===e.id))&&(n=!0),yi(t,e.agents??[]))),n&&m()}).catch(()=>{}),xi=()=>Y(`/api/metrics`).then(O).catch(()=>{}),[Si,Ci]=y([]),wi=()=>Y(`/api/tasks`).then(e=>Ci(e.tasks)).catch(()=>{}),Ti=e=>Si().filter(t=>t.agent===e),[Ei,V]=y((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.expandedSubs`)??`[]`);return new Set(e.filter(e=>typeof e==`string`))}catch{return new Set}})()),[Di,Oi]=y((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.collapsed`)??`[]`);return new Set(e.filter(e=>typeof e==`string`&&!e.startsWith(`chat:`)))}catch{return new Set}})()),H=e=>Di().has(e)||!Ei().has(e),ki=e=>{let t=new Set(Ei());if(t.has(e)?t.delete(e):t.add(e),V(t),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...t])),t.has(e)&&Di().has(e)){let t=new Set(Di());t.delete(e),Oi(t),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...t]))}},Ai=t=>mn(e(),t),[ji,Mi]=y((()=>{try{let e=JSON.parse(localStorage.getItem(`teapot.wsCollapsed`)??`[]`),t=Array.isArray(e)?e.filter(e=>typeof e==`string`):[];if(Number(localStorage.getItem(`teapot.wsCollapsed.v`)??`0`)<2){let e=t.filter(e=>!e.startsWith(`chat:`));return t.length-e.length>0&&localStorage.setItem(`teapot.wsCollapsed`,JSON.stringify(e)),localStorage.setItem(`teapot.wsCollapsed.v`,`2`),new Set(e)}return new Set(t)}catch{return new Set}})()),Ni=S(()=>{let e=new Set;for(let t of ji())t.startsWith(`chat:`)&&e.add(t);return e}),Pi=S(()=>ln(e(),new Set(e().filter(e=>H(e.id)).map(e=>e.id)),Ir(),Ni())),Fi=(t,r,i,a)=>{let o=new Set(ji());if(i)o.delete(t),a&&o.delete(a);else{o.add(t),a&&o.delete(a);let i=n();i&&(t===`chat:${i}`||Ai(e().find(e=>e.id===i))===t)&&aD(`hid ${r} — click the header to show it`)}Mi(o);try{localStorage.setItem(`teapot.wsCollapsed`,JSON.stringify([...o]))}catch{}},Ii=e=>e.replace(/\/+$/,``).split(/[/\\]/).pop()||e,Li=e=>{let t=Ri().get(e)??0;return`${t} chat${t===1?``:`s`}`},Ri=S(()=>hn(e())),zi=S(()=>gn(e(),Pi(),ji())),[Bi,Vi]=y(null),Hi=new Map,Ui=()=>{g([]),Hi.clear(),Wi=0},Wi=0;function Gi(e){return`${i()||(n()??`?`)}:${e.id}`}function Ki(e){let t=Array.from({length:e.length});for(let n=0;n<e.length;n++){let r=e[n],i=Gi(r),a=Hi.get(i);if(t[n]=a??r,!a)for(Hi.set(i,r),Wi+=va(r);Hi.size>4e3||Wi>8388608;){let e=Hi.keys().next().value;if(e===void 0)break;let t=Hi.get(e);t&&(Wi-=va(t)),Hi.delete(e)}}return t}let[qi,U]=y(!1),[Ji,Yi]=y(!1),[Xi,Zi]=y(!1),Qi=0,$i=-1;function ea(e){let t=Ki(e);g(e=>{if(t.length>0&&e.length>0){let n=e[e.length-1],r=t.every(e=>e.seq>n.seq),i=new Set(e.map(e=>e.id));if(r&&t.every(e=>!i.has(e.id)))return[...e,...t]}let n=new Map;for(let t of e)n.set(t.id,t);let r=!1;for(let e of t)n.has(e.id)||(n.set(e.id,e),r=!0);return r?[...n.values()].sort((e,t)=>e.seq-t.seq):e})}async function ta(){let e=n();if(!e||Xi()||qi()||Un())return;if(h().length>=_()){Zi(!0);return}let t=()=>{let e=la();return e&&e.clientHeight>0?e:null},r=0;for(;r++<20&&!Xi()&&n()===e;){let r=t();if(r&&r.scrollHeight>r.clientHeight+40)return;if(h().length>=_()){Zi(!0);return}let i=h().length;if(await na(),h().length===i)return;Ge(ua())&&n()===e&&pa(!0)}}async function na(){let e=n(),t=h()[0];if(e&&t&&!qi()&&!Xi()){U(!0);try{let r=la(),a=r?.scrollHeight??0,o=r?.scrollTop??0,s=Bi(),c=i(),l=(await Y(ia(e,{before:t.id},c,s))).events??[];if(l.length===0){Zi(!0);return}if(n()!==e||h()[0]?.id!==t.id)return;ea(l),requestAnimationFrame(()=>{if(n()===e){let e=la();e&&(e.scrollTop=o+(e.scrollHeight-a))}})}catch{}finally{U(!1)}}}function ra(e,t){return t&&o().has(t)?`&session=${encodeURIComponent(t)}`:``}function ia(e,t,n,r){let i=[`/api/agents/${encodeURIComponent(e)}/events?limit=2000`];t.before&&i.push(`&before=${encodeURIComponent(t.before)}`),t.after&&i.push(`&after=${encodeURIComponent(t.after)}`);let a=ra(e,n);return a&&i.push(a),r&&i.push(`&branch=${encodeURIComponent(r)}&lineage=true`),i.join(``)}let aa=!1,[oa,sa]=y(!1);async function ca(e,t){let r=Qi,a=t??i()??``;try{let t=Bi(),i=r!==$i||!ee().length;h().length||Yi(!0),Y(`/api/agents/${e}/skills`).then(t=>{r===Qi&&n()===e&&No(t.skills??[])}).catch(()=>{});let[o,s]=await Promise.all([Y(ia(e,{},a,t)),i?Y(`/api/agents/${e}/branches`):Promise.resolve({branches:ee()})]);if(i&&($i=r),r!==Qi||n()!==e)return;if(aa){aa=!1,Hi.clear(),g(Ki(o.events)),sa(!1);let t=la();t&&((ha.get(a)??ha.get(e))||(t.scrollTop=t.scrollHeight))}else g(e=>{let t=new Map;for(let n of e)t.set(n.id,n);for(let e of Ki(o.events))t.set(e.id,e);return[...t.values()].sort((e,t)=>e.seq-t.seq)});v(o.total??o.events.length),E(s.branches)}catch{aa&&(aa=!1,sa(!1),Ui())}finally{Yi(!1)}}function la(){return document.querySelector(`.feed`)}function ua(){let e=la();return e?{top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight}:null}function da(){return Ge(ua())}function fa(){let e=la();if(!e)return;let t=()=>e.isConnected?(e.scrollTop=e.scrollHeight,Ko={top:e.scrollTop,height:e.scrollHeight},!0):!1;if(!t())return;Zn(0);let n=r=>{e.isConnected&&Un()&&(Ye(Un(),{top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight})&&t(),r>0&&requestAnimationFrame(()=>n(r-1)))};requestAnimationFrame(()=>n(2)),Jn&&clearTimeout(Jn),Jn=setTimeout(()=>n(0),250)}function pa(e=!1){(e||Un())&&fa()}let ma=new Map,ha=new Map,ga=(e,t=0,n=!1)=>{let r=n?e.getBoundingClientRect().top:-1/0,i=[];for(let a of e.querySelectorAll(`[data-eid]`)){let e=a.getBoundingClientRect();if(i.push({eid:a.dataset.eid??``,session:a.dataset.session??``,top:e.top+t,height:e.height}),n&&e.top>r+4)break}return i},_a=8388608,va=e=>at(e),ya=(t,n)=>bn(c().get(t),e().find(e=>e.id===t)?.session,n);async function ba(e,t=!0,s){let l=n(),u=i(),d=h(),f=_();Qi++,c().size||m();let p=ya(e,s),ee=s&&o().has(s)?s:null,y=p??ee??``;if(l!==e||y!==u){if(u&&d.length){let e=d.reduce((e,t)=>e+va(t),0);e<=_a&&ma.set(u,{events:d,total:f,at:Date.now(),bytes:e}),it(ma,{maxEntries:6,maxBytes:_a})}{let e=la();if(sa(!0),e){let t=ga(e,0,!0),n=u||t.find(e=>e.session)?.session||``,r={top:e.scrollTop,height:e.scrollHeight,viewport:e.clientHeight},i=n?zn(t,e.getBoundingClientRect().top,n):null;i&&We(r)>1?ha.set(n,i):n&&ha.delete(n)}}Qr(),aa=!0,ma.get(y)?.events.length||Ui(),sa(!0),ar(null),Zn(0),Wn(!0),Go=void 0}r(e),a(y),k(te.get(e)??``),Vi(null),Zi(!1),U(!1),Nr(u||l||`?`,kr()),Ar(Mr(y||e)),localStorage.setItem(`teapot.session`,e),Ma(y,t);let b=ma.get(y);if(b?.events.length&&(g(Ki(b.events)),v(b.total),Yi(!0),requestAnimationFrame(()=>{n()===e&&pa(!0)})),Y(`/api/agents/${e}/load`,{method:`POST`}).then(bi).catch(()=>{}),await ca(e,y),n()!==e)return;fr(t=>{let n=t.get(e)??null,r=Dt(n,h(),B()?.status);if(r===n)return t;let i=new Map(t);return r?i.set(e,r):i.delete(e),i}),ar(B()?.ctx?.compacting?{phase:String(B().ctx.compacting)}:null),Wn(!0);let x=Qi;ze(3e3);let S=performance.now()+3e3,C=()=>{if(n()!==e||x!==Qi||Date.now()<we)return;let t=la();t&&Be(t),performance.now()<S&&requestAnimationFrame(C)},w=()=>{let t=ha.get(y)??ha.get(e);if(!t)return`give-up`;let r=la();if(!r)return`wait`;let i=ga(r,r.scrollTop);if(!i.length)return`wait`;let a=Bn(t,i,r.scrollHeight-r.clientHeight);if(a===null)return ha.delete(y),ha.delete(e),`give-up`;r.scrollTop=a,Wn(!1),we=performance.now()+400,ha.delete(y),ha.delete(e);let o=()=>{let e=la();if(!e)return null;for(let n of e.querySelectorAll(`[data-eid]`))if(n.dataset.eid===t.eid&&n.dataset.session===t.session)return n;return null},s=r=>{if(n()!==e)return;let i=la();if(!i)return;let a=o();if(!a)return;let c=i.getBoundingClientRect().top-t.offset,l=a.getBoundingClientRect().top-c;Math.abs(l)<2||r<=0||(i.scrollTop+=l,requestAnimationFrame(()=>s(r-1)))};return requestAnimationFrame(()=>s(6)),`applied`};(async()=>{if(await ta(),n()!==e||x!==Qi)return;let t=performance.now()+1500,r=()=>{if(n()!==e||x!==Qi)return;let i=w();i!==`applied`&&(i===`wait`&&performance.now()<t?requestAnimationFrame(r):requestAnimationFrame(C))};requestAnimationFrame(r)})()}let[xa,Sa]=y(!1),Ca=null,wa=null;T(()=>Ca?.close());let Ta=!1,Ea=null;document.addEventListener(`visibilitychange`,()=>Ea?.()),T(()=>{Ea=null});let Da=!0,Oa=null;async function ka(){let e=n(),t=h().at(-1)?.id,r=i(),a=document.visibilityState===`hidden`;if(!e||!t)Ta=!0,a||Oa?.();else try{let n=Bi(),i=await Y(ia(e,{after:t},r,n)),o=i.events??[];i.gap?(g(Ki(o)),v(o.length)):o.length&&(ea(o),v(e=>e+o.length)),await bi(),o.length&&!a&&xi()}catch{Ta=!0}}function Aa(){Da=!0;let r=location.protocol===`https:`?`wss://`:`ws://`,a=new WebSocket(`${r}${location.host}/api/ws${fD()}`);Ca=a,a.onopen=()=>{Sa(!0),Da?Da=!1:ka()},a.onclose=()=>{Sa(!1),setTimeout(Aa,1500)},a.onerror=()=>a.close();let o=new Set([`state`,`usage`,`session_start`]);a.onmessage=r=>{let s=JSON.parse(r.data);if(s.kind===`ping`)try{a.send(JSON.stringify({kind:`pong`}))}catch{}else if(s.kind!==`pong`){if(s.kind===`hello`&&Array.isArray(s.agents)){t(e=>yi(e,s.agents));let n=e();fr(e=>Et(e,e=>n.find(t=>t.id===e)?.status))}else if(s.kind===`event`&&gt(s.event))fr(e=>ht(e,s.agentId));else if(s.kind===`llm-delta`){if(!Cn(s,n(),i()))return;if(fr(e=>mt(e,s.agentId,s)),s.agentId===n()){let e=String(s.reasoning??``),t=String(s.text??``);e&&!t?_r()||vr(Date.now()):t&&vr(0)}}else if(s.kind===`terminal-closed`&&s.terminalId)Ya(e=>{let t=e.findIndex(e=>e.key===s.terminalId);return t<0?e:(aD(s.reason===`idle`?`a terminal was closed after being idle — open a new shell with +`:`a terminal exited`),e.filter((e,n)=>n!==t))});else if(s.kind===`compaction-progress`){if(s.agentId!==n())return;s.phase===`done`?ar(null):ar({phase:s.phase,summarized:s.summarized})}else if(s.kind===`agent-update`&&s.snapshot)t(e=>{let t=e.findIndex(e=>e.id===s.snapshot.id),n=s.snapshot;return t===-1?[...e,n]:yi(e,e.map((e,n)=>n===t?s.snapshot:e))});else if(s.kind===`metrics`&&s.metrics)O(s.metrics);else if(s.kind===`tasks`&&Array.isArray(s.tasks))Ci(s.tasks);else{if(s.kind===`event`){let e=s.event?.type,t=s.event?.data??{};if(e===`system_note`&&(t.event===`prompt-delivered`||t.event===`prompt-cancelled`)){let e=String(t.promptId??``);if(e){let t=String(s.event?.session??``),n=new Set;t&&n.add(t),n.add(jr());for(let[t,r]of Or)r.some(t=>t.promptId===e)&&n.add(t);for(let t of n){let n=Mr(t);n.some(t=>t.promptId===e)&&Nr(t,n.filter(t=>t.promptId!==e))}}}if(o.has(e)&&!cD.has(e)||(Kr(s.agentId,s.event),s.event?.agent!==n())||!Sn(s.event,n(),i())||(ea([s.event]),s.event&&hr(),Ta=!0,document.visibilityState!==`visible`))return;c()}document.visibilityState===`hidden`?Ta=!0:c()}}};let s=0;function c(){s||=requestAnimationFrame(()=>{s=0,wa&&=(clearTimeout(wa),null),l()})}Ta=!1;let l=async()=>{if(wa=null,n()){let e=h().at(-1)?.id,t=h().length,r=pr();r&&!Dt(r,h(),B()?.status)&&mr(null),h().at(-1)?.id!==e&&(Un()?(fa(),Vr(n())):(Zn(e=>e+Math.max(0,h().length-t)),er(ua())))}};Oa=l,Ea=()=>{document.visibilityState===`visible`&&(xi(),wi(),n()&&(Ta?(Ta=!1,l()):h().at(-1)?.id?ka():(Ta=!0,l())))}}let ja=()=>decodeURIComponent(location.pathname.split(`/`)[2]??``);function Ma(e,t=!0){if(!e)return;let n=`/session/${encodeURIComponent(e)}`;t?history.pushState(null,``,n):history.replaceState(null,``,n)}window.addEventListener(`popstate`,()=>{let e=ja(),t=o().get(e);t&&(t!==n()||e!==i())&&ba(t,!1,e||null)}),x(()=>{let e=B(),t=e?`${wr()?`▶ `:e.status===`error`?`⚠ `:``}${Kn(e)} · teapot`:`teapot`;document.title=Br()>0?`(${Br()}) ${t}`:t});let Na=()=>oe()||de()||Er()!==null||me()&&vt();window.addEventListener(`keydown`,e=>{let t=e.target;if(t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable))e.key===`Escape`&&t.blur();else if(e.key===`Escape`){if(oe()){se(!1);return}if(de()){fe(!1);return}if(Er()){Dr(null);return}if(me()&&vt()){St();return}let e=B();if(e&&wr()){Y(`/api/agents/${e.id}/stop`,{method:`POST`}).then(bi);return}}else if(!Na()){if(e.key===`/`)e.preventDefault(),document.querySelector(`.composer textarea`)?.focus();else if(e.key===`d`)xt();else if(e.key===`t`)qa();else if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=Pi().map(e=>e.a);if(t.length===0)return;e.preventDefault();let r=t.findIndex(e=>e.id===n()),i=e.key===`ArrowDown`?Math.min(r+1,t.length-1):Math.max(r-1,0);i!==r&&ba(t[i].id)}}});let[Pa,Fa]=y(localStorage.getItem(`teapot.term`)===`1`),[Ia,La]=y([]),[Ra,za]=y(!1),Ba=async()=>{let e=n();if(!e)return;let t=await Y(`/api/agents/${encodeURIComponent(e)}/bg-jobs`).catch(()=>null);t?.jobs&&La(t.jobs)};x(()=>{n(),Ba()}),x(()=>{if(!Ra())return;let e=setInterval(()=>void Ba(),2e3);T(()=>clearInterval(e))});let[Va,Ha]=y(!1),[Ua,Wa]=y(``),Ga=()=>{let e=B();e&&(Wa(Kn(e)),Ha(!0))},Ka=async()=>{if(!Va())return;let e=B();Ha(!1);let t=Ua().replace(/\s+/g,` `).trim();if(!e||!t||t===Kn(e))return;let n=await Y(`/api/agents/${encodeURIComponent(e.id)}/session-title?session=${encodeURIComponent(e.session)}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({title:t})}).catch(e=>({error:String(e)}));n?.error?aD(`rename failed: ${n.error}`):(d(n=>new Map(n).set(e.session,t)),bi())},qa=()=>{let e=!Pa();Fa(e),localStorage.setItem(`teapot.term`,e?`1`:`0`),ze(900)},[Ja,Ya]=y([]),Xa=e=>{let t=(e.cwd??``).replace(/[\\/]+$/,``).split(/[\\/]/).pop();return t&&t.length<=24?t:e.title},Za=async()=>{let e=(await Y(`/api/terminals`).catch(()=>null))?.terminals??[];e.length&&Ya(t=>t.map(t=>{let n=e.find(e=>e.id===t.key);return n?{...t,title:n.title,cwd:n.cwd}:t}))},[Qa,$a]=y(0),[eo,to]=y(-1),[no,ro]=y(!1),[io,ao]=y(0),[oo,so]=y(Number(localStorage.getItem(`teapot.termH`))||Math.max(220,Math.round(window.innerHeight*.35))),co=new Map,lo=[null,null],uo=()=>Ja()[io()===0?Qa():eo()]??null;function fo(e){if(!Ja()[e])return;let t=io(),n=t===0?Qa():eo(),r=t===0?eo():Qa(),i=e=>t===0?$a(e):to(e);r===e?((e=>t===0?to(e):$a(e))(n),i(e)):n!==e&&i(e)}let po=()=>mo();async function mo(e){let t=e??n();if(t){if(Ja().filter(e=>e.agentId===t).length>=10)aD(`max 10 shells per agent (${t}) — that's already a lot`);else try{let e=(await Y(`/api/terminals`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({agentId:t})})).terminal;if(!e){aD(`could not open a shell`);return}let n=sd(Ja());Ya(t=>[...t,{key:e.id,agentId:e.agentId,title:e.title,cwd:e.cwd}]),io()===0?$a(n):to(n)}catch(e){aD(`could not open a shell: ${e.message}`)}}}function ho(e){let t=Ja()[e];if(!t)return;Y(`/api/terminals/${encodeURIComponent(t.key)}`,{method:`DELETE`}).catch(()=>{});let n=co.get(t.key);if(n){n.ro?.disconnect();try{n.ws.close()}catch{}n.term.dispose(),co.delete(t.key)}let r=Ja().filter((t,n)=>n!==e);Ya(r),$a(t=>ld(t,e,r.length)),to(t=>t===-1?-1:ld(t,e,r.length))}let go=()=>+!ue();x(()=>{Mt(),At(),Ut(),Pt(),Bt(),ue();let e=go();for(let[,t]of co)Dn(t.term,e)});function _o(){for(let[,e]of co){e.ro?.disconnect();try{e.ws.close()}catch{}e.term.dispose()}co.clear()}function vo(e,t){let n=co.get(e.key);if(n&&Dn(n.term,go()),n)n.el.parentElement!==t&&(t.appendChild(n.el),setTimeout(()=>{try{n.fit()}catch{}},30));else{let r=document.createElement(`div`);r.className=`termsession`,t.appendChild(r);let i=new rd({cursorBlink:!0,fontSize:12.5,scrollSensitivity:3,fontFamily:`ui-monospace, Menlo, Consolas, monospace`,allowTransparency:!0,theme:En(go())});i.attachCustomKeyEventHandler(e=>{if(e.type!==`keydown`||!(e.ctrlKey&&e.shiftKey)||e.altKey||e.key!==`C`&&e.key!==`c`)return!0;let t=i.getSelection();return t&&navigator.clipboard?.writeText(t).catch(()=>{}),e.preventDefault(),!1});let a=new od;i.loadAddon(a),i.open(r);let o=location.protocol===`https:`?`wss://`:`ws://`,s=()=>`${o}${location.host}/api/agents/${encodeURIComponent(e.agentId)}/term?terminal=${encodeURIComponent(e.key)}${fD()}`,c=new WebSocket(s()),l,u=!1,d=t=>{t.onmessage=t=>{let n=JSON.parse(t.data);n.kind===`data`?i.write(n.data):n.kind===`ping`||(n.kind===`exit`?(u=!0,i.write(`\r\n\x1b[2m[terminal exited ${n.code??``}]\x1b[0m\r\n`),Ya(t=>t.filter(t=>t.key!==e.key)),co.get(e.key)?.term.dispose(),co.delete(e.key)):n.kind===`attach`&&n.error&&(u=!0,i.write(`\r\n\x1b[2m[${n.error}]\x1b[0m\r\n`)))},t.onclose=()=>{!u&&co.has(e.key)&&(l||=(i.write(`\r
184
184
  \x1B[2m[connection lost — reconnecting…]\x1B[0m\r
185
- `),setTimeout(function(){if(l=void 0,!no.has(e.key))return;let t=new WebSocket(s());c=t,d(t),t.addEventListener(`open`,()=>h())},1500)))}};d(c),i.onData(e=>{c.readyState===WebSocket.OPEN&&c.send(JSON.stringify({kind:`input`,data:e}))});let f={cols:0,rows:0},p,m=[],h=()=>{try{a.fit()}catch{}c.readyState===WebSocket.OPEN?(i.cols!==f.cols||i.rows!==f.rows)&&(f={cols:i.cols,rows:i.rows},c.send(JSON.stringify({kind:`resize`,cols:i.cols,rows:i.rows}))):g()};function g(){p||=setInterval(()=>{no.has(e.key)?c.readyState===WebSocket.OPEN&&(clearInterval(p),p=void 0,h()):(clearInterval(p),p=void 0)},400)}c.addEventListener(`open`,()=>h());let _=r.parentElement??r,v=new ResizeObserver(()=>{m[0]&&clearTimeout(m[0]),m[0]=setTimeout(h,250)});v.observe(_),_!==r&&v.observe(r),setTimeout(h,60),n={el:r,term:i,fit:a,ws:c,ro:v},no.set(e.key,n)}return n}function po(e){let t=ro[e];if(!t)return;let n=Ha()[e===0?Ka():Ja()];if(!n){[...no.values()].some(e=>e.el.parentElement===t)&&t.replaceChildren();return}let r=fo(n,t);for(let[e,r]of no)e!==n.key&&r.el.parentElement===t&&r.el.remove();requestAnimationFrame(()=>{r.el.parentElement!==t&&t.appendChild(r.el);try{r.fit()}catch{}if(Qa()===(e===0?0:1))try{r.term.focus()}catch{}})}x(()=>{Ha(),Xa(),Ka(),Ja(),eo(),requestAnimationFrame(()=>{po(0),Xa()&&po(1)})});let mo=null;x(()=>{if(!Oa())return;let e=n();if(!e||e===mo)return;mo=e;let t=Ha().map((e,t)=>({t:e,i:t})).filter(t=>t.t.agentId===e);t.length&&ao(t[t.length-1].i)}),x(()=>{let e=Ha().length,t=cd(Ka(),e);if(t!==Ka()&&qa(t),Xa()){let t=cd(Ja(),e);t!==Ja()&&Ya(t)}});let ho=e=>{e.preventDefault();let t=e.clientY,n=eo(),r=e=>{let r=Math.min(Math.max(n-(e.clientY-t),140),Math.round(window.innerHeight*.85));to(r)},i=()=>{window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i),localStorage.setItem(`teapot.termH`,String(eo())),requestAnimationFrame(()=>{po(0),Xa()&&po(1)})};window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i)},go=()=>{let e=!Xa();Za(e),e&&(Ja()<0||Ja()===Ka()||Ja()>=Ha().length)&&Ya(ud(Ka(),Ha().length)),requestAnimationFrame(()=>{po(0),Xa()&&po(1)})};T(uo);let _o=e=>t=>{ro[e]=t,t&&requestAnimationFrame(()=>{po(e),Xa()&&po(1),setTimeout(()=>po(e),200)})};w(()=>{let t=e=>{e.key===`Escape`&&tt()&&rt()};window.addEventListener(`keydown`,t),T(()=>window.removeEventListener(`keydown`,t)),ti(),mi().then(async()=>{await m();let t=Ta(),n=en({agents:e(),urlId:t,ownerOf:e=>o().get(e),lastId:localStorage.getItem(`teapot.session`),hideGhosts:Ar()});n&&ma(n.id,!1,t||null)}),hi(),vi(),bo(),wa(),Y(`/api/terminals`).then(e=>{let t=e.terminals??[];t.length&&(Ua(t.map(e=>({key:e.id,agentId:e.agentId,title:e.title,cwd:e.cwd}))),Oa()&&(qa(0),Ya(-1)))}).catch(()=>{}),T(()=>{})});let vo=[{cmd:`/start`,desc:`start working toward the goal`},{cmd:`/stop`,desc:`interrupt the running agent`},{cmd:`/fork`,desc:`branch the conversation here`},{cmd:`/goal`,desc:`/goal <text> — set goal & notify the agent`},{cmd:`/compact`,desc:`force a context compaction now`},{cmd:`/skill`,desc:`/skill <name> — force-load a skill and follow it`}],[W,yo]=y([]),bo=()=>Y(`/api/personas`).then(e=>yo(e.personas)).catch(()=>{}),[xo,So]=y(!1),Co=()=>{let e=ne().match(/^@([A-Za-z0-9._-]*)$/);return e?e[1].toLowerCase():null},wo=()=>{let t=Co();return t===null?[]:[...W().map(e=>({key:e.key,label:`${e.label} — spawns a sub-agent`,kind:`persona`})),...e().filter(e=>e.id!==n()).map(e=>({key:e.id,label:`${e.status} — send directly`,kind:`agent`}))].filter(e=>e.key.toLowerCase().startsWith(t))},To=new Set([`start`,`stop`,`fork`,`compact`]),[Eo,Do]=y([]),[Oo,ko]=y(null),[Ao,jo]=y(-1),Mo=()=>{let e=ne();if(!e.startsWith(`/`)||e.includes(`
186
- `))return[];let t=e.match(/^\/([a-z]*)(?:\s+(.*))?$/i);if(!t)return[];let n=t[1].toLowerCase(),r=(t[2]??``).trim();if(!r&&n!==`skill`){let e=vo.filter(e=>e.cmd.slice(1).startsWith(n));return e.find(e=>e.cmd.slice(1)===n)&&To.has(n)?[]:e.map(e=>({insert:e.cmd+` `,title:e.desc}))}if(n===`skill`){let e=Eo().filter(e=>e.name.toLowerCase().startsWith(r.toLowerCase()));return e.length===1&&e[0].name.toLowerCase()===r.toLowerCase()?[]:e.map(e=>({insert:`/skill ${e.name} `,title:e.description||`(bundled skill)`}))}return[]},No,Po,Fo,Io=!1;function Lo(e){if(!Po){Po=document.createElement(`div`),Po.setAttribute(`aria-hidden`,`true`);let e=Po.style;e.position=`absolute`,e.visibility=`hidden`,e.pointerEvents=`none`,e.top=`0`,e.left=`-9999px`,e.whiteSpace=`pre-wrap`,e.overflowWrap=`anywhere`,e.wordBreak=`break-word`,Po.dataset.mirror=``}let t=getComputedStyle(e);for(let e of[`font-family`,`font-size`,`font-weight`,`line-height`,`letter-spacing`,`padding-top`,`padding-bottom`,`padding-left`,`padding-right`,`border-top-width`,`border-bottom-width`,`box-sizing`])Po.style.setProperty(e,t.getPropertyValue(e));if(Po.style.width=`${e.clientWidth}px`,Po.setAttribute(`data-mirror-text`,e.value.endsWith(`
187
- `)?`${e.value} `:e.value),Fo||(Fo=document.createElement(`div`),Fo.setAttribute(`aria-hidden`,`true`),Fo.style.cssText=`position:absolute;left:-9999px;top:0;pointer-events:none`,document.body.appendChild(Fo)),Po.parentElement!==Fo&&Fo.appendChild(Po),!Io){let e=document.createElement(`style`);e.textContent=`[data-mirror]::after{content:attr(data-mirror-text);white-space:pre-wrap;display:block}`,document.head.appendChild(e),Io=!0}return Po.scrollHeight}let Ro=()=>{if(!No)return;let e=on();if(!No.value&&!e){No.style.height=``;return}let t=Lo(No),n=e?-1:In(t,360);No.style.height=n===-1?``:`${n}px`},zo,Bo=null,Vo,Ho=240,Uo=1200,Wo;x(()=>{let e=ne();No&&Pn(oD)&&(Fn(No.value,e)&&(No.value=e),Ro())}),w(()=>{let e=0,t=()=>{e||=requestAnimationFrame(()=>{e=0,Ro()})};window.addEventListener(`resize`,t),T(()=>{window.removeEventListener(`resize`,t),e&&cancelAnimationFrame(e)})});let[Go,Ko]=y([]),qo=e=>{let t=Array.from(e).filter(e=>e.type.startsWith(`image/`));for(let e of t){if(e.size>8e6){aD(`"${e.name}" is over 8 MB — skipped`);continue}let t=new FileReader;t.onload=()=>{Ko(n=>[...n,{url:String(t.result),name:e.name}].slice(0,4))},t.readAsDataURL(e)}},Jo=async(t,r)=>{let i=r??n();if(!i)return;let a=Go(),o=e().find(e=>e.id===i)?.session||i,s=xn(),c=`@p${Date.now()}${Math.random().toString(36).slice(2,6)}`;Dr(o,[...Er(o),{id:c,text:t,at:Date.now(),...a.length?{images:a.map(e=>e.url)}:{}}]);try{let e=(await Y(`/api/agents/${i}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:t,start:!0,...a.length?{images:a}:{}})})).promptId;e&&Dr(o,Er(o).map(t=>t.id===c?{...t,promptId:e}:t)),Ko([]),pd(on())&&un(!1),Ro(),s&&(Tn(!0),Vn(0),we=0,requestAnimationFrame(()=>{oa(),requestAnimationFrame(()=>{xn()&&oa()})}))}catch(e){Dr(o,Er(o).filter(e=>e.id!==c)),k(t),console.error(`send failed:`,e)}},Yo=async t=>{t.preventDefault();let r=n(),i=ne().trim();if(r&&i){if(i.startsWith(`@`)){let t=i.indexOf(` `),r=(t===-1?i.slice(1):i.slice(1,t)).toLowerCase(),a=t===-1?``:i.slice(t+1).trim(),o=W().some(e=>e.key.toLowerCase()===r),s=e().some(e=>e.id.toLowerCase()===r);try{if(o){if(!a){aD(`usage: @${r} <task>`);return}aD(`🧩 spawned ${(await Y(`/api/agents/${n()}/spawn`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({persona:r,task:a,context:xo()?`fork`:`none`})})).id}${xo()?` (forked context)`:``}`),mi(),k(``)}else if(s){if(!a){aD(`usage: @${r} <message>`);return}await Y(`/api/agents/${encodeURIComponent(r)}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:a,start:!0})}),aD(`→ delivered to @${r}`),k(``)}else{aD(`unknown @${r} — personas: ${W().map(e=>e.key).join(`, `)||`(none)`}`);return}}catch(e){aD(`@${r} failed: ${e.message}`)}}else if(i.startsWith(`/`)){let e=i.indexOf(` `),t=(e===-1?i.slice(1):i.slice(1,e)).toLowerCase(),n=e===-1?``:i.slice(e+1).trim();if(t===`goal`&&!n){k(`/goal `);return}if(t===`skill`&&!n){k(`/skill `);return}k(``);try{await Xo(t,n)}catch(e){throw k(ne()?`${i}\n${ne()}`:i),e}}else k(``),await Jo(i)}},Xo=async(e,t)=>{let r=n();if(!r)return;let i=(e,t)=>Y(`/api/agents/${r}${e}`,{method:`POST`,headers:{"content-type":`application/json`},...t===void 0?{}:{body:JSON.stringify(t)}}).then(mi);try{if(e===`start`)await i(`/start`);else if(e===`stop`)await i(`/stop`);else if(e===`fork`)await i(`/fork`,{}),await ma(r);else if(e===`compact`)aD((await i(`/compact`))?.ran?`context compacted`:`nothing to compact yet`);else if(e===`goal`){if(!t){aD(`usage: /goal <text>`);return}await i(`/goal`,{text:t,notify:!0}),aD(`goal saved & notification queued`)}else if(e===`skill`){if(!t){aD(`usage: /skill <name>`);return}await i(`/skill`,{name:t}),aD(`skill "${t}" dispatched`)}else aD(`unknown command "${e}" — /start /stop /fork /goal /skill /compact`)}catch(t){aD(`/${e} failed: ${t.message}`)}},Zo,Qo=0;x(()=>{e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!Zo)return;let e=Math.min(Qo,Zo.scrollHeight);Math.abs(Zo.scrollTop-e)>1&&(Zo.scrollTop=e)})})});let $o=e=>()=>n()&&Y(`/api/agents/${n()}${e}`,{method:`POST`}).then(mi),es=async()=>{let i=n();if(!i)return;let a=new Set([i,...pn(e(),i).map(e=>e.id)]),o=a.size-1;if(!confirm(`archive agent ${i}?\n\n`+(o>0?`Its ${o} sub-agent${o===1?``:`s`} will be archived too.\n\n`:``)+`They stop running and leave the list, but the config and full session history are KEPT — restore any of them from ⚙️ settings → archive.`))return;await Y(`/api/agents/${i}/archive`,{method:`POST`}).catch(()=>{}),t(e().filter(e=>!a.has(e.id))),m(!0);let s=dd(e(),a);s?ma(s.id):(r(null),Li())},ts=async()=>{n()&&(aD(`stopped: ${((await Y(`/api/agents/${n()}/stop-children`,{method:`POST`})).stopped??[]).join(`, `)||`(none)`}`),mi())},ns=()=>Y(`/api/agents/${B().id}/fork`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}).then(async()=>{await m(!0),await ma(B().id)}),[rs,is]=y(``),as=()=>({"max-height":`none`,"overflow-y":`auto`,resize:`vertical`}),os=e=>{T(Gn(e,`goalPreview`))},ss=e=>{T(Gn(e,`goal`))},[cs,ls]=y(``),[us,ds]=y(!1),[fs,ps]=y(!0),ms=``;x(()=>{let e=n();e&&(B()?.goal,e!==ms&&(ms=e,ds(!1),is(``),ls(``)))});let G=async e=>{if(e.preventDefault(),n()&&rs().trim())try{await Y(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:rs(),notify:fs(),...cs().trim()?{verify:cs()}:{}})}),is(``),ls(``),ds(!1),mi()}catch(e){aD(`goal save failed: ${e.message}`)}};return[j(N,{get when(){return ni()},get children(){var e=qw();return e.firstChild.firstChild.nextSibling.addEventListener(`submit`,e=>{e.preventDefault();let t=document.getElementById(`pw-input`);localStorage.setItem(`teapot.token`,t.value),location.reload()}),e}}),j(N,{get when(){return ue()},children:e=>(()=>{var t=jT(),n=t.firstChild;return b(t=>{var r=cn(e(),nn[nn.length-1]),i=sn(e());return r!==t.e&&I(n,`src`,t.e=r),i!==t.t&&I(n,`srcset`,t.t=i),t},{e:void 0,t:void 0}),t})()}),(()=>{var t=ET(),r=t.firstChild,i=r.firstChild,a=i.nextSibling.firstChild,o=a.firstChild;o.firstChild;var s=a.nextSibling,c=s.firstChild.firstChild.nextSibling;c.firstChild;var l=c.nextSibling,d=s.nextSibling,f=r.nextSibling,p=f.nextSibling,m=p.firstChild;m.firstChild,R(t,j(N,{get when(){return P(()=>!!he())()&&_t()},get children(){var e=Jw();return e.$$click=yt,e}}),r),R(r,j(N,{get when(){return he()},get children(){var e=Yw(),t=e.firstChild.nextSibling;return t.$$click=yt,e}}),i),R(i,j(M,{get each(){return Ni()},children:t=>[j(N,{get when(){return P(()=>t.wsHeader!==void 0)()&&t.wsHeader!==``},get children(){var e=NT(),n=e.firstChild,r=n.nextSibling;return e.$$click=()=>ki(`ws:${t.wsHeader}`,Ai(t.wsHeader),t.wsCollapsedGroup===!0,t.collapsedVia),R(n,()=>t.wsCollapsedGroup?`▸`:`▾`),R(r,()=>Ai(t.wsHeader)),R(e,j(N,{get when(){return t.wsCollapsedGroup},get children(){var e=MT();return R(e,()=>Mi().get(t.wsHeader)??0),e}}),null),b(n=>{var i=t.wsCollapsedGroup?`${t.wsHeader} — collapsed (${ji(t.wsHeader)} hidden). Click to show.`:(Mi().get(t.wsHeader)??0)>1?`${t.wsHeader} — ${ji(t.wsHeader)} in this directory`:t.wsHeader||``,a=t.wsHeader;return i!==n.e&&I(e,`title`,n.e=i),a!==n.t&&I(r,`title`,n.t=a),n},{e:void 0,t:void 0}),e}}),j(N,{get when(){return P(()=>!t.headerOnly)()&&!t.wsCollapsedGroup},get children(){var r=RT(),i=r.firstChild,a=i.nextSibling;return r.$$click=()=>ma(t.a.id),R(r,j(N,{get when(){return dn({isSub:!!t.a.parent,collapsed:t.chatCollapsedGroup===!0,hasChildren:e().some(e=>e.parent===t.a.id)})},get fallback(){return zT()},get children(){return(()=>{let e=!t.a.parent,n=e&&Oi().has(`chat:${t.a.id}`)||wi(t.a.id);return(()=>{var r=BT();return r.$$click=r=>{if(r.stopPropagation(),e){if(n){if(!bi().has(t.a.id)){let e=new Set(bi());e.add(t.a.id),xi(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}if(Si().has(t.a.id)){let e=new Set(Si());e.delete(t.a.id),Ci(e),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...e]))}}else if(bi().has(t.a.id)){let e=new Set(bi());e.delete(t.a.id),xi(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}ki(`chat:${t.a.id}`,t.a.id,n)}else Ti(t.a.id)},R(r,n?`▸`:`▾`),b(()=>I(r,`title`,e?n?`show ${t.a.id}`:`hide ${t.a.id} and its sub-agents`:n?`expand sub-agents`:`collapse sub-agents`)),r})()})()}}),i),R(a,()=>Kn({id:t.a.id,sessionTitle:t.a.sessionTitle??u().get(t.a.session??``)})),R(r,(()=>{var e=P(()=>!!t.a.workspaceMissing);return()=>e()?VT():null})(),null),R(r,j(N,{get when(){return Lr(t.a.id)>0},get children(){var e=PT();return e.firstChild,R(e,()=>Lr(t.a.id),null),b(()=>I(e,`title`,`${Lr(t.a.id)} unread notification${Lr(t.a.id)>1?`s`:``} (including sub-agents)`)),e}}),null),R(r,j(N,{get when(){return wi(t.a.id)||t.chatCollapsedGroup===!0&&Oi().has(`chat:${t.a.id}`)},get children(){return(()=>{let n=pn(e(),t.a.id),r=n.filter(e=>e.live??(e.status===`running`||e.status===`waiting`||e.status===`needs_operator`)).length;return n.length>0?(()=>{var e=HT();return e.firstChild,L(e,`subcount`+(r>0?` live`:``)),R(e,()=>n.length,null),R(e,r>0?` · ▶${r}`:``,null),b(()=>I(e,`title`,`${n.length} sub-agent${n.length>1?`s`:``} (${r} active)`)),e})():null})()}}),null),R(r,j(N,{get when(){return t.a.parent},get children(){return FT()}}),null),R(r,j(N,{get when(){return yi(t.a.id).length>0},get children(){var e=IT();return b(()=>I(e,`title`,yi(t.a.id).map(e=>`${e.id}: ${e.schedule}`).join(`
188
- `))),e}}),null),R(r,j(N,{get when(){return t.a.goal.status===`done`},get children(){return LT()}}),null),b(e=>{var o=`agent-item`+(t.a.id===n()?` sel`:``)+(t.depth>0?` sub-row`:``)+(t.chatCollapsedGroup?` collapsed`:``),s=t.depth>0?`padding-left:${10+t.depth*14}px`:``,c=t.a.parent?(()=>{let e=fn(t.a.id,W().map(e=>e.key));return e?`sub-agent of @${t.a.parent} — "${e}"`:`sub-agent of @${t.a.parent}`})():void 0,l=`dot ${t.a.status}`,d=t.a.status===`needs_operator`?`waiting for your answer`:t.a.status===`waiting`?`waiting on its own work — resumes by itself`:t.a.status,f=t.a.workspaceMissing?` ghost`:``,p=t.a.workspaceMissing?`workspace not found on disk (${t.a.workspace}) — it will be created when this session runs`:qn({id:t.a.id,sessionTitle:t.a.sessionTitle??u().get(t.a.session??``)});return o!==e.e&&L(r,e.e=o),e.t=Oe(r,s,e.t),c!==e.a&&I(r,`title`,e.a=c),l!==e.o&&L(i,e.o=l),d!==e.i&&I(i,`title`,e.i=d),f!==e.n&&L(a,e.n=f),p!==e.s&&I(a,`title`,e.s=p),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),r}})]})),o.$$click=e=>{e.stopPropagation(),Nr(!Mr()),Mr()||kr(e=>e.map(e=>({...e,read:!0})))},R(o,j(N,{get when(){return Pr()>0},get children(){var e=Xw();return R(e,Pr),e}}),null),R(a,j(vd,{icon:`👻`,get active(){return Ar()},get title(){return Ar()?`show ghost sessions again (👻 workspace missing on disk)`:`hide ghost sessions (👻 — their workspace directory no longer exists)`},onClick:t=>{t.stopPropagation();let r=!Ar();if(jr(r),localStorage.setItem(`teapot.hideGhosts`,r?`1`:`0`),r&&n()&&B()?.workspaceMissing){let t=e().find(e=>!e.workspaceMissing);t&&ma(t.id)}}}),null),R(a,j(vd,{icon:`+`,title:`new agent`,onClick:()=>{ti(),se(!0)}}),null),R(a,j(vd,{icon:`⚙️`,title:`settings`,onClick:()=>{ti(),fe(!0)}}),null),R(c,`0.37.148`,null),R(d,j(N,{get when(){return D()},get children(){return[`master rss `,P(()=>D().rssMb),`MB · heap `,P(()=>D().heapUsedMb),`MB`,j(N,{get when(){return D().heapTotalMb!==void 0},get children(){return[` · total `,P(()=>D().heapTotalMb),`MB`]}}),j(N,{get when(){return D().externalMb!==void 0},get children(){return[` · ext `,P(()=>D().externalMb),`MB`]}}),j(N,{get when(){return D().arrayBuffersMb!==void 0},get children(){return[` · buf `,P(()=>D().arrayBuffersMb),`MB`]}}),Zw(),j(N,{get when(){return D().messagesInMemory!==void 0},get children(){return[`msgs `,P(()=>D().messagesInMemory),` in `,P(()=>D().loadedSessions),` loaded session(s)`,Zw()]}}),`load1 `,P(()=>D().loadavg1),` · up `,P(()=>Math.floor(D().uptimeSec/60)),`m`]}})),R(f,j(N,{get when(){return B()?.id},get fallback(){return UT()},get children(){return[(()=>{var t=iT(),r=t.firstChild,i=r.nextSibling,a=i.nextSibling,o=a.firstChild,s=o.nextSibling,c=s.nextSibling.nextSibling,l=c.nextSibling.nextSibling,u=l.nextSibling.nextSibling;u.nextSibling;var d=a.nextSibling,f=d.firstChild,p=f.nextSibling;return R(t,j(N,{get when(){return he()},get children(){var e=Qw();return e.$$click=()=>vt(!_t()),b(()=>I(e,`aria-expanded`,_t())),e}}),r),r.$$click=()=>za(),R(t,j(N,{get when(){return Fa()},get fallback(){return(()=>{var e=WT();return e.$$click=()=>za(),R(e,()=>Kn(B())),b(()=>I(e,`title`,`${qn(B(),B().session)} — click to rename`)),e})()},get children(){var e=$w();return e.addEventListener(`blur`,()=>void Ba()),e.$$keydown=e=>{e.key===`Enter`?(e.preventDefault(),Ba()):e.key===`Escape`&&(e.preventDefault(),Ia(!1))},e.$$input=e=>Ra(e.currentTarget.value),Ae(e=>{requestAnimationFrame(()=>{e.focus(),e.select()})},e),I(e,`spellcheck`,!1),b(()=>e.value=La()),e}}),i),R(i,()=>B().status),R(t,j(N,{get when(){return _r()>0},get children(){var e=eT(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return n.nextSibling,R(e,_r,t),R(e,()=>_r()===1?`message`:`messages`,n),R(e,()=>B().status===`stopped`?` (stopped)`:``,null),b(()=>I(e,`title`,(()=>{let e=B().pendingPromptQueue??[],t=e.length||B().pendingPromptIds?.length||B().pendingPrompts||0,n=e.length?e.filter(e=>(e.source??`user`)===`user`).length:t,r=t-n;return`${`${t} message${t>1?`s`:``} queued${r?` — ${n} from you, ${r} from the harness`:` from you`}`}. ${B().status===`stopped`?`This agent is STOPPED, so nothing will run until you press start (or it is resumed).`:`They are handed to the model at its next turn boundary — the timeline shows them as queued… until then.`}`+(n?` Yours can be withdrawn with ✕ cancel while still queued.`:``)})())),e}}),a),R(t,j(N,{get when(){return(B()?.bgRunning??0)>0},get children(){var e=tT();return e.firstChild,e.$$click=()=>{Na(!Ma()),Ma()&&Pa()},R(e,()=>B().bgRunning,null),b(t=>{var n=Ma(),r=`${B().bgRunning} background shell(s) running — click to inspect`;return n!==t.e&&I(e,`aria-expanded`,t.e=n),r!==t.t&&I(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),a),R(t,j(N,{get when(){return yi(B().id).length>0},get children(){var e=nT();return e.firstChild,R(e,()=>yi(B().id).length,null),b(()=>I(e,`title`,`scheduled tasks:\n${yi(B().id).map(e=>`${e.schedule} · ${e.id}${e.forked?` (forked)`:``}`).join(`
189
- `)}`)),e}}),a),R(a,()=>B().model,o),R(a,()=>B().session,s),R(a,()=>B().branch,c),R(a,()=>B().stats.turns,l),R(a,()=>B().stats.toolCalls,u),f.$$click=()=>(vr()?$o(`/stop`):$o(`/start`))(),R(f,()=>vr()?`■ stop`:`▶ start`),R(d,j(N,{get when(){return e().some(e=>e.parent===n())},get children(){return j(vd,{icon:`⏹`,title:`stop every sub-agent this agent spawned (descendants included)`,onClick:ts})}}),p),R(d,j(vd,{icon:`🗄`,title:`archive this agent — reversible: it leaves the list but keeps its config and history (restore in ⚙️ settings → archive)`,onClick:es}),null),R(d,j(vd,{icon:`⑂`,title:`fork: branch off the conversation here — try things without disturbing the main line`,onClick:ns}),null),R(d,j(vd,{icon:`⌨`,title:`terminal (t)`,onClick:Va}),null),R(d,j(vd,{icon:`▤`,title:`toggle details panel (d)`,get active(){return ot()},onClick:lt}),null),R(t,j(N,{get when(){return Ma()},get children(){var e=rT(),t=e.firstChild.firstChild.nextSibling;return t.$$click=()=>Na(!1),R(e,j(N,{get when(){return Aa().length>0},get fallback(){return GT()},get children(){return j(M,{get each(){return Aa()},children:e=>(()=>{var t=qT(),n=t.firstChild.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return R(r,()=>zx(e.cmd,80)),R(i,(()=>{var t=P(()=>!!e.detached);return()=>t()?`detached · pid ${e.pid??`?`}`:P(()=>!!e.running)()?dt(Date.now()-e.startedAt):`exit ${e.code??`?`}`})(),null),R(i,()=>e.truncated?` · truncated`:``,null),a.$$click=async()=>{await Y(`/api/agents/${encodeURIComponent(B().id)}/bg-jobs/${encodeURIComponent(e.id)}`,{method:`DELETE`}).catch(()=>{}),await Pa()},R(a,(()=>{var t=P(()=>!!e.detached);return()=>t()?`forget`:e.running?`kill`:`clear`})()),R(t,j(N,{get when(){return e.tail.trim()},get fallback(){return j(N,{get when(){return e.detached},get children(){var t=JT(),n=t.firstChild.nextSibling;return n.nextSibling,R(t,()=>e.pid??`?`,n),t}})},get children(){var t=KT();return R(t,()=>e.tail),t}}),null),b(t=>{var i=`bgjob-dot `+(e.running?`running`:`done`),o=e.running?`running`:`finished`,s=e.cmd,c=e.detached?`this job survived a harness restart (pid ${e.pid??`?`}) — its output can no longer be read here; stop it yourself if needed`:e.running?`kill this job (whole process group)`:`forget this finished job`;return i!==t.e&&L(n,t.e=i),o!==t.t&&I(n,`title`,t.t=o),s!==t.a&&I(r,`title`,t.a=s),c!==t.o&&I(a,`title`,t.o=c),t},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()})}}),null),e}}),null),b(e=>{var t=`badge ${B().status}`,n=B().statusReason&&!/^(round complete|prompt|api start|goal set|created via web|start)$/.test(B().statusReason)?`${B().status} — ${B().statusReason}`:void 0,r=`${B().model} · ${B().session}/${B().branch} · turns ${B().stats.turns} · tools ${B().stats.toolCalls}`,o=`runbtn`+(vr()?` danger`:``),s=vr()?`interrupt: aborts the current LLM call; the running tool finishes first`:`run toward the goal (starts the loop)`;return t!==e.e&&L(i,e.e=t),n!==e.t&&I(i,`title`,e.t=n),r!==e.a&&I(a,`title`,e.a=r),o!==e.o&&L(f,e.o=o),s!==e.i&&I(f,`title`,e.i=s),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t})(),(()=>{var e=pT();return e.addEventListener(`scroll`,e=>{let t=e.currentTarget,r={top:t.scrollTop,height:t.scrollHeight,viewport:t.clientHeight},i=Ke(r,Bo,Vo,Wo);Bo=null,Ce=performance.now();let a=zo?.top,o=zo?.height;Vo=r.height,Wo=r.viewport,zo=r,Wn(r);let s=xn(),c=performance.now();c-ye>100&&(ye=c,ve=Ue(t));let l=o!==void 0&&Math.abs(r.height-o)>.5,u=a!==void 0&&r.top<a-.5&&!l;u&&(we=performance.now()+400);let d=u?!1:Ge(r)?!0:performance.now()<we?!1:Je(s,i,r,a);d!==s&&Tn(d),d&&i!==`reader`?(An()&&Vn(0),Ir(),qe(d,r)&&We(r)>0&&oa()):d&&Ge(r)&&(An()&&Vn(0),Ir()),r.top<=4&&n()&&!Vi()&&!Gi()&&h().length>0&&Xi()}),Ae(e=>He(e),e),R(e,j(N,{get when(){return Jn()},children:e=>(()=>{var t=YT();return t.firstChild,R(t,(()=>{var t=P(()=>e().phase===`harvesting`);return()=>t()?`saving durable lessons…`:`summarizing ${e().summarized?Rx(e().summarized)+` `:``}older messages…`})(),null),t})()}),null),R(e,j(N,{get when(){return P(()=>!!Gi())()&&Yr().length>0},get children(){return aT()}}),null),R(e,j(N,{get when(){return Vi()},get children(){return oT()}}),null),R(e,j(N,{get when(){return Yr().length>0},get fallback(){return P(()=>!!(Ui()||ea()))()?XT():ZT()},get children(){return[j(M,{get each(){return Yr()},children:e=>j(pC,{e,prev:()=>Qr(e,-1),next:()=>Qr(e,1),get showBranch(){return ee().length>1},res:()=>Hr().resFor.get(e.id),get orphan(){return Hr().orphanCalls.has(e.id)},onOption:e=>void Jo(e),answeredIds:qr,onAnswered:Gr,get agentActive(){return P(()=>!!yr())()&&Ct(e)},onResize:()=>{xn()&&oa()},get agentId(){return n()??void 0},get onCancel(){return e.data?.source===`user`&&e.data?.pending&&e.data?.promptId&&e.data?.sent!==!0?()=>{let t=String(e.data.promptId);Y(`/api/agents/${n()}/prompt/cancel`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({promptId:t})}).then(e=>{let n=String(e.text??``);k(ne()?`${n}\n\n${ne()}`:n),Dr(Tr(),Cr().filter(e=>e.promptId!==t)),aD(`message withdrawn — draft restored`)}).catch(()=>aD(`withdraw failed — it may have already been sent`))}:void 0},get onEdit(){return e.type===`prompt`&&e.data?.source===`user`&&!(e.data?.pending&&e.data?.sent!==!0)&&!e.data?.cancelled?async()=>{vr()&&(await Y(`/api/agents/${n()}/stop`,{method:`POST`}).catch(()=>{}),await mi()),xr({eventId:e.id,text:String(e.data?.text??``)})}:void 0}})}),j(N,{get when(){return ea()},get children(){return sT()}}),j(N,{get when(){return P(()=>!!Ui())()&&!ea()},get children(){return cT()}}),j(N,{get when(){return P(()=>!!yr())()&&tr()},get children(){var e=fT(),t=e.firstChild.nextSibling;return t.firstChild,R(t,j(N,{get when(){return hr().trim()!==``},get children(){var e=lT(),t=e.firstChild;t.firstChild;var n=t.nextSibling;return R(t,j(Kd,{get startedAt(){return mr()}}),null),Ae(e=>{let t=!0;e.addEventListener(`scroll`,()=>{t=e.scrollHeight-e.scrollTop-e.clientHeight<24}),x(()=>{hr(),t&&(e.scrollTop=e.scrollHeight)})},n),R(n,hr),e}}),null),R(t,j(N,{get when(){return cr()},get fallback(){return QT()},get children(){return j(N,{get when(){return Zn()},get fallback(){return(()=>{var e=dT();return b(()=>e.innerHTML=Re(cr()+`▍`)),e})()},get children(){return[uT(),(()=>{var e=dT();return b(()=>e.innerHTML=Re(Qn()+`▍`)),e})()]}})}}),null),e}})]}}),null),e})(),j(N,{get when(){return tt()},children:e=>(()=>{var t=$T(),n=t.firstChild;return De(t,`click`,rt,!0),n.$$click=e=>e.stopPropagation(),b(()=>I(n,`src`,e())),t})()}),j(N,{get when(){return Oa()},get children(){var t=vT(),n=t.firstChild,r=n.nextSibling,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=r.nextSibling,c=s.firstChild;n.$$dblclick=()=>{to(Math.max(220,Math.round(window.innerHeight*.35))),localStorage.setItem(`teapot.termH`,String(eo()))},n.$$pointerdown=ho,R(i,j(M,{get each(){return Ha()},children:(e,t)=>(()=>{var n=eE(),r=n.firstChild.nextSibling;return n.$$click=()=>{ao(t()),Ga()},R(n,()=>Wa(e),r),r.$$click=e=>{e.stopPropagation(),co(t())},b(r=>{var i=`termtab`+(Qa()===0&&Ka()===t()?` active`:``)+(Xa()&&Qa()===1&&Ja()===t()?` active`:``),a=`${e.cwd?`${e.cwd}\n`:``}${e.title} — click to show in focused pane`;return i!==r.e&&L(n,r.e=i),a!==r.t&&I(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()}),null),R(i,j(vd,{icon:`+`,title:`new shell in this workspace`,onClick:oo}),null),R(o,(()=>{var t=P(()=>!!io());return()=>t()?e().find(e=>e.id===io().agentId)?.workspace.split(`/`).filter(Boolean).pop():B()?.workspace})()),R(a,j(vd,{icon:`◫`,get title(){return Xa()?`single pane`:`split panes (50/50)`},onClick:go}),null),R(a,j(vd,{icon:`▾`,title:`hide the terminal (shells keep running; reopen with t) — close individual shells with their ✕ tab buttons`,onClick:Va}),null);var l=_o(0);return typeof l==`function`&&Ae(l,c),c.$$pointerdown=()=>$a(0),R(c,j(N,{get when(){return Ka()<0||Ka()>=Ha().length},get children(){return mT()}})),R(s,j(N,{get when(){return Xa()},get children(){return[hT(),(()=>{var e=_T(),t=_o(1);return typeof t==`function`&&Ae(t,e),e.$$pointerdown=()=>$a(1),R(e,j(N,{get when(){return Ja()<0||Ja()>=Ha().length},get children(){return gT()}})),b(()=>e.classList.toggle(`focused`,Qa()===1)),e})()]}}),null),b(e=>{var n={height:`${eo()}px`},r=!!Xa(),i=Qa()===0;return e.e=Oe(t,n,e.e),r!==e.t&&s.classList.toggle(`split`,e.t=r),i!==e.a&&c.classList.toggle(`focused`,e.a=i),e},{e:void 0,t:void 0,a:void 0}),t}}),(()=>{var e=wT(),t=e.firstChild,n=t.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return R(e,j(N,{get when(){return P(()=>Hn()>32)()&&!xn()},get children(){var e=yT();return e.firstChild,e.$$click=()=>{sa(!0),Ir()},R(e,(()=>{var e=P(()=>An()>0);return()=>e()?`${An()} new message${An()>1?`s`:``}`:`jump to present`})(),null),e}}),t),R(e,j(N,{get when(){return Mo().length>0},get children(){var e=bT();return R(e,j(M,{get each(){return Mo()},children:(e,t)=>(()=>{var n=tE(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{k(e.insert),jo(-1)},R(r,()=>e.insert.trim()),R(i,()=>e.title),b(r=>{var i=`cmdrow`+(t()===Ao()?` active`:``),a=e.title;return i!==r.e&&L(n,r.e=i),a!==r.t&&I(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()})),e}}),t),R(e,j(N,{get when(){return wo().length>0},get children(){var e=bT();return R(e,j(M,{get each(){return wo()},children:e=>(()=>{var t=nE(),n=t.firstChild;n.firstChild;var r=n.nextSibling;return t.$$click=()=>{k(`@${e.key} `),jo(-1)},R(n,()=>e.key,null),R(r,()=>e.label),b(()=>I(t,`title`,e.label)),t})()})),e}}),t),R(e,j(N,{get when(){return Go().length>0},get children(){var e=xT(),t=e.firstChild;return R(e,j(M,{get each(){return Go()},children:(e,t)=>(()=>{var n=rE(),r=n.firstChild,i=r.nextSibling;return r.$$click=()=>nt(e.url),i.$$click=()=>Ko(e=>e.filter((e,n)=>n!==t())),b(t=>{var i=e.name,a=e.url,o=e.name;return i!==t.e&&I(n,`title`,t.e=i),a!==t.t&&I(r,`src`,t.t=a),o!==t.a&&I(r,`alt`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),n})()}),t),t.$$click=()=>Ko([]),e}}),t),t.addEventListener(`submit`,Yo),n.$$keydown=e=>{let t=Mo();t.length>0&&e.key===`ArrowDown`?(e.preventDefault(),jo(e=>Math.min(e+1,t.length-1))):t.length>0&&e.key===`ArrowUp`?(e.preventDefault(),jo(e=>Math.max(e-1,0))):t.length>0&&(e.key===`Tab`||e.key===`Enter`)&&!e.shiftKey&&Ao()>=0&&!oD?(e.preventDefault(),k(t[Ao()].insert),jo(-1)):e.key===`Escape`&&t.length>0?jo(-1):fd({key:e.key,shiftKey:e.shiftKey,composing:oD,maximized:on()})&&(e.preventDefault(),Yo(e))},n.$$input=e=>{k(e.currentTarget.value),jo(0),Ro()},n.addEventListener(`paste`,e=>{let t=Array.from(e.clipboardData?.files??[]).filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),qo(t))}),n.addEventListener(`compositionend`,()=>{requestAnimationFrame(()=>{oD=!1}),k(No?.value??``)}),n.addEventListener(`compositionstart`,()=>{oD=!0}),Ae(e=>{No=e,e.value=ne()},n),R(t,j(N,{get when(){return P(()=>!!ne().startsWith(`@`))()&&ne().includes(` `)},get children(){var e=ST(),t=e.firstChild;return t.addEventListener(`change`,e=>So(e.currentTarget.checked)),b(()=>t.checked=xo()),e}}),r),r.$$click=()=>{let e=!on();un(e),requestAnimationFrame(()=>Ro())},R(r,()=>on()?`⤡`:`⤢`),R(t,j(vd,{icon:`📎`,title:`attach images (or paste them straight into the box)`,onClick:()=>document.getElementById(`composer-file`)?.click()}),i),a.addEventListener(`change`,e=>{e.currentTarget.files?.length&&qo(e.currentTarget.files),e.currentTarget.value=``}),R(e,j(N,{get when(){return nD()},get children(){var e=CT();return R(e,nD),e}}),null),b(t=>{var i=`composer`+(on()?` maximized`:``),a=`message #${B().id} — / for commands · paste or 📎 to attach images`,o=on()?`restore composer (hide timeline)`:`maximize composer — hide the timeline and fill the main column`;return i!==t.e&&L(e,t.e=i),a!==t.t&&I(n,`placeholder`,t.t=a),o!==t.a&&I(r,`title`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),e})()]}})),R(t,j(N,{get when(){return P(()=>!!he())()&&ot()},get children(){var e=TT();return e.$$click=()=>ct(!1),e}}),p),p.addEventListener(`scroll`,e=>{Qo=e.currentTarget.scrollTop});var g=Zo;return typeof g==`function`?Ae(g,p):Zo=p,R(m,j(vd,{icon:`✕`,title:`close details panel (esc)`,onClick:ft}),null),R(p,j(N,{get when(){return B()?.id},keyed:!0,fallback:null,children:t=>[j(N,{get when(){return B().id},keyed:!0,fallback:null,children:e=>j(Kw,{agentId:e,get workspace(){return B().workspace}})}),(()=>{var e=aE();return e.firstChild,R(e,j(N,{get when(){return qt().length},get children(){var e=iE(),t=e.firstChild.nextSibling;return t.nextSibling,R(e,()=>qt().length,t),e}}),null),e})(),(()=>{var t=cE(),r=t.firstChild,i=r.nextSibling,a=i.firstChild,o=a.nextSibling,s=i.nextSibling,c=s.firstChild,l=s.nextSibling;return l.firstChild,r.addEventListener(`change`,t=>{let r=t.currentTarget.value;an=!0,Bt(r),Ht(jn(ie().providers,r,e().find(e=>e.id===n()))),Xt(r)}),R(r,j(M,{get each(){return Yt()},children:e=>(()=>{var t=DE();return t.value=e,R(t,e,null),R(t,()=>e===ie().defaultProvider?` ★`:``,null),t})()})),a.$$input=e=>Ht(e.currentTarget.value),R(o,j(M,{get each(){return qt()},children:e=>(()=>{var t=DE();return b(()=>t.value=e.id),t})()})),R(t,j(N,{get when(){return B().effortSupported},get children(){var e=oE(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>Gt(e.currentTarget.value)),R(t,j(M,{get each(){return P(()=>!!B().effortOptions?.length)()?B().effortOptions:eD},children:e=>(()=>{var t=DE();return t.value=e,R(t,e),t})()}),null),b(()=>t.value=Ut()),e}}),s),c.$$click=async e=>{if(!n())return;let t=e.currentTarget;t.disabled=!0;try{await Y(`/api/agents/${n()}/model`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:zt(),model:Vt().trim()||void 0,contextWindowTokens:qt().find(e=>e.id===(Vt().trim()||void 0))?.contextLength,...B().effortSupported?{reasoningEffort:Ut()}:{}})}),t.textContent=`✓ applied`,mi()}catch(e){alert(`apply failed: ${e.message}`)}finally{setTimeout(()=>{t.textContent=`apply`,t.disabled=!1},1200)}},R(l,()=>B().model,null),R(t,j(N,{get when(){return Qt()},get children(){var e=sE();return R(e,Qt),e}}),null),b(()=>I(a,`placeholder`,Mn(ie().providers,zt(),B(),kn(B(),ie().providers,ie().defaultProvider)))),b(()=>r.value=zt()),b(()=>a.value=Vt()),t})(),(()=>{var e=uE();return e.firstChild,R(e,j(N,{get when(){return!!B().goal.text.trim()},get fallback(){return OE()},get children(){var e=lE();return R(e,()=>B().goal.status),b(()=>L(e,`badge ${B().goal.status===`active`?`running`:B().goal.status}`)),e}}),null),e})(),(()=>{var e=dE();return e.firstChild,R(e,j(M,{each:[`active`,`done`,`paused`],children:e=>(()=>{var t=kE();return t.$$click=()=>{n()&&Y(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({status:e})}).then(mi)},I(t,`title`,e===`active`?`agent keeps working toward the goal (with auto-continue)`:e===`done`?`mark achieved — auto-continue stops`:`parked on purpose — resume by setting active again`),R(t,e===`active`?`▶ working`:e===`done`?`✓ done`:`⏸ paused`),b(n=>{var r=`goalstate`+(B().goal.text.trim()&&B().goal.status===e?` on ${e}`:``),i=!!B().goal.text.trim()&&B().goal.status===e;return r!==n.e&&L(t,n.e=r),i!==n.t&&(t.disabled=n.t=i),n},{e:void 0,t:void 0}),t})()}),null),e})(),j(N,{get when(){return B().goal.text},get fallback(){return AE()},get children(){return[(()=>{var e=fE(),t=e.firstChild;return Ae(os,e),b(n=>{var r=as(),i=Re(String(B().goal.text));return n.e=Oe(e,r,n.e),i!==n.t&&(t.innerHTML=n.t=i),n},{e:void 0,t:void 0}),e})(),j(N,{get when(){return B().goal.verify},get children(){return j($t,{title:`🔍️ verification contract`,tone:`tool`,get body(){return String(B().goal.verify)}})}}),j(N,{get when(){return B().goal.audit},children:e=>j($t,{get title(){return e().verdict===`approved`?`✅ audit: approved`:`⚠ audit: changes required`},get meta(){return pt(e().at)},get tone(){return e().verdict===`approved`?`ok`:`warn`},get body(){return P(()=>!!Kt(e().feedback))()?`_the auditor returned a verdict with no detail_`:e().feedback}})})]}}),(()=>{var e=pE(),t=e.firstChild,r=t.nextSibling,i=r.nextSibling.firstChild,a=i.firstChild,o=i.nextSibling.firstChild;return e.addEventListener(`submit`,G),t.$$input=e=>{is(e.currentTarget.value),ds(!0)},Ae(ss,t),r.$$input=e=>{ls(e.currentTarget.value),ds(!0)},a.addEventListener(`change`,e=>{n()&&Y(`/api/agents/${n()}/auto-continue`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(mi)}),o.addEventListener(`change`,e=>ps(e.currentTarget.checked)),b(()=>t.value=rs()),b(()=>r.value=cs()),b(()=>a.checked=B().autoContinue??!0),b(()=>o.checked=fs()),e})(),(()=>{var e=hE();return e.firstChild,R(e,j(N,{get when(){return fi().total>0},get children(){var e=mE(),t=e.firstChild,n=t.nextSibling;return n.nextSibling,R(e,()=>fi().done,t),R(e,()=>fi().total,n),b(t=>Oe(e,fi().done===fi().total?`color:var(--ok)`:`color:var(--warn)`,t)),e}}),null),e})(),j(N,{get when(){return fi().total>0},get children(){var e=gE(),t=e.firstChild;return b(e=>{var n=`barfill `+(fi().done===fi().total?``:`warn`),r=`${Math.round(fi().done/fi().total*100)}%`;return n!==e.e&&L(t,e.e=n),r!==e.t&&ke(t,`width`,e.t=r),e},{e:void 0,t:void 0}),e}}),j(pf,{get draft(){return ii()},get preview(){return oi()},onDraft:e=>{ai(e),li(!0)}}),(()=>{var e=_E(),t=e.firstChild,n=t.nextSibling;return R(e,j(vd,{get icon(){return oi()?`✎`:`👁`},get title(){return oi()?`edit markdown`:`rendered checklist`},onClick:()=>si(!oi())}),t),n.$$click=di,e})(),vE(),j(N,{get when(){return B().latestProgress},get fallback(){return jE()},children:e=>(()=>{var t=IE(),n=t.firstChild,r=n.firstChild.nextSibling,i=n.nextSibling;return R(t,j(N,{get when(){return e().recent},get children(){var t=ME(),n=t.firstChild.nextSibling;return b(()=>n.innerHTML=ut(e().recent)),t}}),i),R(t,j(N,{get when(){return e().problems},get children(){var t=NE(),n=t.firstChild.nextSibling;return b(()=>n.innerHTML=ut(e().problems)),t}}),i),R(t,j(N,{get when(){return e().next},get children(){var t=PE(),n=t.firstChild.nextSibling;return b(()=>n.innerHTML=ut(e().next)),t}}),i),R(t,j(N,{get when(){return e().goalStatus},get children(){var t=FE(),n=t.firstChild.nextSibling;return R(n,()=>e().goalStatus),t}}),i),R(i,()=>pt(e().ts)),b(()=>r.innerHTML=ut(e().doing)),t})()}),yE(),(()=>{var e=SE(),t=e.firstChild,r=t.firstChild,i=r.firstChild.nextSibling,a=r.nextSibling,o=a.firstChild.nextSibling,s=a.nextSibling,c=s.firstChild.nextSibling,l=s.nextSibling,u=l.firstChild.nextSibling,d=l.nextSibling,f=d.firstChild.nextSibling;return R(e,j(N,{get when(){return B().ctx},keyed:!0,get fallback(){return LE()},children:e=>{let t=S(()=>{let t=e,n=qt().find(e=>e.id===B().model),r=t.window||n?.contextLength||0,i=r?Math.min(999,t.usedTokens/r*100):0;return{usedTokens:t.usedTokens,compactAt:t.compactAt,compacting:t.compacting,window:t.window,effectiveWindow:r,pct:i,cls:r?i>=85?`crit`:i>=70?`warn`:`ok`:``,derivedBudget:r?Math.round(r*.75):0,usingDerived:t.compactAtIsManual!==!0}}),r=()=>t(),i=e=>{let t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)};return(()=>{var e=VE(),t=e.firstChild,a=t.firstChild.nextSibling,o=a.firstChild.nextSibling;o.nextSibling;var s=t.nextSibling,c=s.firstChild.nextSibling,l=c.firstChild,u=c.nextSibling,d=s.nextSibling,f=d.firstChild.firstChild;return R(a,()=>Rx(r().usedTokens),o),R(t,j(N,{get when(){return r().effectiveWindow},get children(){var e=RE(),t=e.firstChild;return R(e,()=>i(r().pct),t),R(e,()=>Rx(r().effectiveWindow),null),b(()=>L(e,`pill ${r().cls}`)),e}}),null),R(e,j(N,{get when(){return r().effectiveWindow},get children(){var e=zE(),t=e.firstChild;return b(e=>{var n=`barfill ${r().cls}`,i=`${Math.min(100,r().pct)}%`;return n!==e.e&&L(t,e.e=n),i!==e.t&&ke(t,`width`,e.t=i),e},{e:void 0,t:void 0}),e}}),s),R(c,()=>Rx(r().usingDerived?r().derivedBudget:r().compactAt),l),R(u,()=>r().usingDerived?`75% of window`:`manual`),R(e,j(N,{get when(){return Jn()||r().compacting},get children(){var e=BE(),t=e.firstChild.nextSibling.nextSibling;return R(t,()=>Jn()?.phase??String(r().compacting)),e}}),d),f.addEventListener(`change`,e=>{n()&&Y(`/api/agents/${n()}/auto-compact`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(mi)}),b(()=>f.checked=B().autoCompact!==!1),e})()}}),t),R(i,()=>Rx(B().stats.inputTokens)),R(o,()=>Rx(B().stats.outputTokens)),R(c,()=>B().stats.turns),R(u,()=>B().stats.toolCalls),R(f,()=>B().stats.compactions??0),R(t,j(N,{get when(){return(B().stats.costUsd??0)>0},get children(){var e=bE(),t=e.firstChild.nextSibling;return t.firstChild,R(t,()=>hD(B().stats.costUsd??0),null),b(()=>I(e,`title`,`≈ ${(B().stats.costUsd??0).toFixed(4)} this session, from the model's per-token pricing and per-turn usage. Cached input is estimated at ~10% of the prompt rate; treat as an approximation, not an invoice.`)),e}}),null),R(t,j(N,{get when(){return(B().stats.cachedInputTokens??0)>0},get children(){var e=xE(),t=e.firstChild.nextSibling,n=t.firstChild;return R(t,()=>Math.round(B().stats.cachedInputTokens/Math.max(1,B().stats.inputTokens)*100),n),b(()=>I(e,`title`,`${Rx(B().stats.cachedInputTokens)} input tokens were served from the provider's prompt cache — billed far cheaper than fresh input`)),e}}),null),b(()=>I(d,`title`,`how many times old turns were summarized into notes to make room. ${B().stats.compactions?`Each one keeps the recent stretch verbatim.`:`Not yet — the context has fit so far.`}`)),e})(),(()=>{var e=wE();return e.firstChild.nextSibling,R(e,j(N,{get when(){return Pi()},get children(){var e=CE(),t=e.firstChild.nextSibling;return R(t,Pi),e}}),null),e})(),j(M,{get each(){return ee()},children:e=>(()=>{var t=HE(),r=t.firstChild,i=r.nextSibling,a=i.firstChild;return t.$$click=()=>{let t=Pi()===e.branch?null:e.branch,r=t!==Pi();Fi(t),n()&&(r&&(qi++,Li(),v(0),Ki(!1)),na(n()))},R(r,()=>e.branch,null),R(r,()=>e.branch===B().branch?` (current)`:``,null),R(i,()=>e.events,a),b(n=>{var r=`branch-row`+(e.branch===B().branch||e.branch===Pi()?` cur`:``),i=e.branch===Pi()?`click to show all branches again`:`show only ${e.branch}`;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),(()=>{var e=EE();return e.firstChild,R(e,j(N,{get when(){return gi().length>0},get children(){var e=TE(),t=e.firstChild.nextSibling;return t.nextSibling,R(e,()=>gi().length,t),e}}),null),e})(),j(N,{get when(){return gi().length>0},get fallback(){return UE()},get children(){return j(M,{get each(){return gi()},children:e=>(()=>{var t=GE(),r=t.firstChild,i=r.firstChild,a=i.nextSibling;a.firstChild;var o=r.nextSibling,s=o.firstChild,c=o.nextSibling;return t.$$click=()=>ma(e.agent),R(i,()=>e.id),R(a,()=>e.agent,null),R(r,j(N,{get when(){return e.forked},get children(){return WE()}}),null),R(o,()=>e.schedule,s),R(o,(()=>{var t=P(()=>!!e.next);return()=>t()?pt(e.next):`—`})(),null),R(o,(()=>{var t=P(()=>!!e.last);return()=>t()?` · last ${pt(e.last)}`:` · never ran`})(),null),R(c,()=>zx(e.prompt,90)),b(r=>{var i=`sched-row`+(e.agent===n()?` cur`:``),a=`${zx(e.prompt,200)}\nclick to open #${e.agent}`;return i!==r.e&&L(t,r.e=i),a!==r.t&&I(t,`title`,r.t=a),r},{e:void 0,t:void 0}),t})()})}})]}),null),b(e=>{var n=`layout`+(ot()?``:` right-hidden`)+(_t()?` left-open`:``),i=`sidebar`+(_t()?` open`:``),a=`iconbtn notifbtn`+(Pr()>0?` has-unread`:``),s=Pr()>0?`${Pr()} unread notifications`:`notifications`,c=`conn`+(ha()?` ok`:``),u=ha()?`live (websocket)`:`reconnecting…`,d={"--termh":`${eo()}px`},m=`rightbar`+(ot()?` open`:``);return n!==e.e&&L(t,e.e=n),i!==e.t&&L(r,e.t=i),a!==e.a&&L(o,e.a=a),s!==e.o&&I(o,`title`,e.o=s),c!==e.i&&L(l,e.i=c),u!==e.n&&I(l,`title`,e.n=u),e.s=Oe(f,d,e.s),m!==e.h&&L(p,e.h=m),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0}),t})(),j(N,{get when(){return Mr()},get children(){return[(()=>{var e=DT();return e.$$click=()=>Nr(!1),e})(),(()=>{var t=AT(),r=t.firstChild.firstChild.nextSibling,i=r.firstChild;return R(r,j(N,{get when(){return Or().length>0},get children(){var e=OT();return e.$$click=()=>kr([]),e}}),i),i.$$click=()=>Nr(!1),R(t,j(N,{get when(){return Or().length>0},get fallback(){return KE()},get children(){var t=kT();return R(t,j(M,{get each(){return Or()},children:t=>(()=>{var r=JE(),i=r.firstChild.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling;return r.$$click=()=>{kr(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e)),n()!==t.agentId&&e().some(e=>e.id===t.agentId)&&ma(t.agentId),Nr(!1),t.eventId&&Vr(t.eventId)},R(i,(()=>{var e=P(()=>t.kind===`finish`);return()=>e()?`✅`:P(()=>t.kind===`question`)()?`❓️`:t.kind===`error`?`⚠️`:`📈`})()),R(a,()=>t.title),R(o,()=>pt(new Date(t.at).toISOString())),s.$$click=e=>{e.stopPropagation(),kr(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e))},R(s,()=>t.read?`✓`:`○`),R(r,j(N,{get when(){return t.body},get children(){var e=qE();return R(e,()=>mD(t.body,160)),e}}),null),b(e=>{var n=`notifitem `+t.kind+(t.read?` read`:``),i=`from ${t.agentId}`,a=t.read?`already read`:`mark as read`;return n!==e.e&&L(r,e.e=n),i!==e.t&&I(r,`title`,e.t=i),a!==e.a&&I(s,`title`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),r})()})),t}}),null),t})()]}}),j(N,{get when(){return oe()},get children(){return j(gD,{get providers(){return Object.keys(ie().providers??{})},onClose:()=>se(!1),onCreated:e=>{se(!1),t(t=>pi(t,[e])),ma(e.id)}})}}),j(N,{get when(){return de()},get children(){return j(Cw,{get cfg(){return ie()},onClose:()=>fe(!1),announcedOAuth:pe,get skills(){return Eo()},get hasSelection(){return!!n()},get agentId(){return n()},get features(){return Oo()},onSaved:()=>{ti(),vi()},theme:{themes:Mt,activeId:bt,paintedId:le,auto:St,setAuto:e=>{wt(e),localStorage.setItem(`teapot.theme.auto`,e?`1`:`0`)},dark:Pt,setDark:Ft,light:Tt,setLight:kt,setThemes:Nt,setActive:xt,preview:e=>jt(e),commitAppearance:e=>{localStorage.setItem(`teapot.theme.auto`,e.auto?`1`:`0`),localStorage.setItem(`teapot.theme.dark`,e.dark),localStorage.setItem(`teapot.theme.light`,e.light),localStorage.setItem(`teapot.theme`,e.fixed)}}})}}),j(N,{get when(){return br()},fallback:null,children:e=>{let t=()=>h().findIndex(t=>t.id===e().eventId),r=()=>Math.max(0,h().length-t()-1);return j(bd,{title:`edit prompt — forks the conversation`,onClose:()=>xr(null),get children(){var t=XE(),i=t.firstChild,a=i.nextSibling,o=a.firstChild;return t.addEventListener(`submit`,async t=>{t.preventDefault();let r=document.getElementById(`edit-text`);try{await Y(`/api/agents/${n()}/edit-prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({eventId:e().eventId,text:r.value})}),xr(null),mi();let t=n();t&&await ma(t)}catch(e){alert(`edit failed: ${e.message}`)}}),R(t,j(N,{get when(){return r()>0},get children(){var e=YE(),t=e.firstChild;return R(e,r,t),e}}),a),o.$$click=()=>xr(null),b(()=>i.value=e().text),t}})}})]}function mD(e,t){return e.length>t?e.slice(0,t)+` …`:e}function hD(e){return e>=100?Math.round(e).toLocaleString():e>=10?e.toFixed(1):e>=1?e.toFixed(2):e>=.01?e.toFixed(3):e.toFixed(4)}function gD(e){let[t,n]=y(`~`),[r,i]=y([]),[a,o]=y(``),[s,c]=y(e.providers[0]??``),[l,u]=y(``),[d,f]=y(``);async function p(e){let r=await Y(`/api/fs?path=${encodeURIComponent(e??t())}`);n(r.path),h(r.parent??``),i(r.entries??[])}w(()=>p(t()));let[m,h]=y(``),g=async n=>{n.preventDefault(),f(``);try{let n=await Y(`/api/agents`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({workspace:t(),id:a(),provider:s()||void 0,model:l()||void 0,start:!1})});e.onCreated(n.agent)}catch(e){f(String(e.message))}};return j(bd,{title:`new agent`,get onClose(){return e.onClose},get children(){var i=QE(),f=i.firstChild,h=f.firstChild.nextSibling.firstChild,_=h.nextSibling,v=_.nextSibling,ee=f.nextSibling,y=ee.nextSibling,x=y.firstChild,S=x.firstChild.nextSibling,C=x.nextSibling,w=C.firstChild.nextSibling,T=C.nextSibling.firstChild.nextSibling,E=y.nextSibling;return i.addEventListener(`submit`,g),h.$$input=e=>n(e.currentTarget.value),_.$$click=()=>p(t()),v.$$click=()=>m()?p(m()):p(`..`),R(ee,j(M,{get each(){return r()},children:e=>(()=>{var n=$E();return n.firstChild,n.$$click=()=>p(`${t()}/${e}`.replace(/\/+/g,`/`)),R(n,e,null),n})()})),S.$$input=e=>o(e.currentTarget.value),w.addEventListener(`change`,e=>c(e.currentTarget.value)),R(w,j(M,{get each(){return e.providers},children:e=>(()=>{var t=DE();return R(t,e),t})()})),T.$$input=e=>u(e.currentTarget.value),R(i,j(N,{get when(){return d()},get children(){var e=ZE();return R(e,d),e}}),E),b(()=>h.value=t()),b(()=>S.value=a()),b(()=>w.value=s()),b(()=>T.value=l()),i}})}Ee([`click`,`input`,`keydown`,`pointerdown`,`dblclick`]),Te(()=>j(pD,{}),document.getElementById(`root`));
190
- //# sourceMappingURL=index-C_m63cqt.js.map
185
+ `),setTimeout(function(){if(l=void 0,!co.has(e.key))return;let t=new WebSocket(s());c=t,d(t),t.addEventListener(`open`,()=>h())},1500)))}};d(c),i.onData(e=>{c.readyState===WebSocket.OPEN&&c.send(JSON.stringify({kind:`input`,data:e}))});let f={cols:0,rows:0},p,m=[],h=()=>{try{a.fit()}catch{}c.readyState===WebSocket.OPEN?(i.cols!==f.cols||i.rows!==f.rows)&&(f={cols:i.cols,rows:i.rows},c.send(JSON.stringify({kind:`resize`,cols:i.cols,rows:i.rows}))):g()};function g(){p||=setInterval(()=>{co.has(e.key)?c.readyState===WebSocket.OPEN&&(clearInterval(p),p=void 0,h()):(clearInterval(p),p=void 0)},400)}c.addEventListener(`open`,()=>h());let _=r.parentElement??r,v=new ResizeObserver(()=>{m[0]&&clearTimeout(m[0]),m[0]=setTimeout(h,250)});v.observe(_),_!==r&&v.observe(r),setTimeout(h,60),n={el:r,term:i,fit:a,ws:c,ro:v},co.set(e.key,n)}return n}function W(e){let t=lo[e];if(!t)return;let n=Ja()[e===0?Qa():eo()];if(!n){[...co.values()].some(e=>e.el.parentElement===t)&&t.replaceChildren();return}let r=vo(n,t);for(let[e,r]of co)e!==n.key&&r.el.parentElement===t&&r.el.remove();requestAnimationFrame(()=>{r.el.parentElement!==t&&t.appendChild(r.el);try{r.fit()}catch{}if(io()===(e===0?0:1))try{r.term.focus()}catch{}})}x(()=>{Ja(),no(),Qa(),eo(),oo(),requestAnimationFrame(()=>{W(0),no()&&W(1)})});let yo=null;x(()=>{if(!Pa())return;let e=n();if(!e||e===yo)return;yo=e;let t=Ja().map((e,t)=>({t:e,i:t})).filter(t=>t.t.agentId===e);t.length&&fo(t[t.length-1].i)}),x(()=>{let e=Ja().length,t=cd(Qa(),e);if(t!==Qa()&&$a(t),no()){let t=cd(eo(),e);t!==eo()&&to(t)}});let bo=e=>{e.preventDefault();let t=e.clientY,n=oo(),r=e=>{let r=Math.min(Math.max(n-(e.clientY-t),140),Math.round(window.innerHeight*.85));so(r)},i=()=>{window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i),localStorage.setItem(`teapot.termH`,String(oo())),requestAnimationFrame(()=>{W(0),no()&&W(1)})};window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i)},xo=()=>{let e=!no();ro(e),e&&(eo()<0||eo()===Qa()||eo()>=Ja().length)&&to(ud(Qa(),Ja().length)),requestAnimationFrame(()=>{W(0),no()&&W(1)})};T(_o);let So=e=>t=>{lo[e]=t,t&&requestAnimationFrame(()=>{W(e),no()&&W(1),setTimeout(()=>W(e),200)})};w(()=>{let t=e=>{e.key===`Escape`&&tt()&&rt()};window.addEventListener(`keydown`,t),T(()=>window.removeEventListener(`keydown`,t)),si(),bi().then(async()=>{await m();let t=ja(),n=en({agents:e(),urlId:t,ownerOf:e=>o().get(e),lastId:localStorage.getItem(`teapot.session`),hideGhosts:Ir()});n&&ba(n.id,!1,t||null)}),xi(),wi(),Eo(),Aa(),Y(`/api/terminals`).then(e=>{let t=e.terminals??[];t.length&&(Ya(t.map(e=>({key:e.id,agentId:e.agentId,title:e.title,cwd:e.cwd}))),Pa()&&($a(0),to(-1)))}).catch(()=>{}),T(()=>{})});let Co=[{cmd:`/start`,desc:`start working toward the goal`},{cmd:`/stop`,desc:`interrupt the running agent`},{cmd:`/fork`,desc:`branch the conversation here`},{cmd:`/goal`,desc:`/goal <text> — set goal & notify the agent`},{cmd:`/compact`,desc:`force a context compaction now`},{cmd:`/skill`,desc:`/skill <name> — force-load a skill and follow it`}],[wo,To]=y([]),Eo=()=>Y(`/api/personas`).then(e=>To(e.personas)).catch(()=>{}),[Do,Oo]=y(!1),ko=()=>{let e=ne().match(/^@([A-Za-z0-9._-]*)$/);return e?e[1].toLowerCase():null},Ao=()=>{let t=ko();return t===null?[]:[...wo().map(e=>({key:e.key,label:`${e.label} — spawns a sub-agent`,kind:`persona`})),...e().filter(e=>e.id!==n()).map(e=>({key:e.id,label:`${e.status} — send directly`,kind:`agent`}))].filter(e=>e.key.toLowerCase().startsWith(t))},jo=new Set([`start`,`stop`,`fork`,`compact`]),[Mo,No]=y([]),[Po,Fo]=y(null),[Io,Lo]=y(-1),Ro=()=>{let e=ne();if(!e.startsWith(`/`)||e.includes(`
186
+ `))return[];let t=e.match(/^\/([a-z]*)(?:\s+(.*))?$/i);if(!t)return[];let n=t[1].toLowerCase(),r=(t[2]??``).trim();if(!r&&n!==`skill`){let e=Co.filter(e=>e.cmd.slice(1).startsWith(n));return e.find(e=>e.cmd.slice(1)===n)&&jo.has(n)?[]:e.map(e=>({insert:e.cmd+` `,title:e.desc}))}if(n===`skill`){let e=Mo().filter(e=>e.name.toLowerCase().startsWith(r.toLowerCase()));return e.length===1&&e[0].name.toLowerCase()===r.toLowerCase()?[]:e.map(e=>({insert:`/skill ${e.name} `,title:e.description||`(bundled skill)`}))}return[]},zo,Bo,Vo,Ho=!1;function Uo(e){if(!Bo){Bo=document.createElement(`div`),Bo.setAttribute(`aria-hidden`,`true`);let e=Bo.style;e.position=`absolute`,e.visibility=`hidden`,e.pointerEvents=`none`,e.top=`0`,e.left=`-9999px`,e.whiteSpace=`pre-wrap`,e.overflowWrap=`anywhere`,e.wordBreak=`break-word`,Bo.dataset.mirror=``}let t=getComputedStyle(e);for(let e of[`font-family`,`font-size`,`font-weight`,`line-height`,`letter-spacing`,`padding-top`,`padding-bottom`,`padding-left`,`padding-right`,`border-top-width`,`border-bottom-width`,`box-sizing`])Bo.style.setProperty(e,t.getPropertyValue(e));if(Bo.style.width=`${e.clientWidth}px`,Bo.setAttribute(`data-mirror-text`,e.value.endsWith(`
187
+ `)?`${e.value} `:e.value),Vo||(Vo=document.createElement(`div`),Vo.setAttribute(`aria-hidden`,`true`),Vo.style.cssText=`position:absolute;left:-9999px;top:0;pointer-events:none`,document.body.appendChild(Vo)),Bo.parentElement!==Vo&&Vo.appendChild(Bo),!Ho){let e=document.createElement(`style`);e.textContent=`[data-mirror]::after{content:attr(data-mirror-text);white-space:pre-wrap;display:block}`,document.head.appendChild(e),Ho=!0}return Bo.scrollHeight}let Wo=()=>{if(!zo)return;let e=Vn();if(!zo.value&&!e){zo.style.height=``;return}let t=Uo(zo),n=e?-1:In(t,360);zo.style.height=n===-1?``:`${n}px`},Go,Ko=null,qo,Jo=240,Yo=1200,Xo;x(()=>{let e=ne();zo&&Pn(oD)&&(Fn(zo.value,e)&&(zo.value=e),Wo())}),w(()=>{let e=0,t=()=>{e||=requestAnimationFrame(()=>{e=0,Wo()})};window.addEventListener(`resize`,t),T(()=>{window.removeEventListener(`resize`,t),e&&cancelAnimationFrame(e)})});let[Zo,Qo]=y([]),$o=e=>{let t=Array.from(e).filter(e=>e.type.startsWith(`image/`));for(let e of t){if(e.size>8e6){aD(`"${e.name}" is over 8 MB — skipped`);continue}let t=new FileReader;t.onload=()=>{Qo(n=>[...n,{url:String(t.result),name:e.name}].slice(0,4))},t.readAsDataURL(e)}},es=async(t,r)=>{let i=r??n();if(!i)return;let a=Zo(),o=e().find(e=>e.id===i)?.session||i,s=Un(),c=`@p${Date.now()}${Math.random().toString(36).slice(2,6)}`;Nr(o,[...Mr(o),{id:c,text:t,at:Date.now(),...a.length?{images:a.map(e=>e.url)}:{}}]);try{let e=(await Y(`/api/agents/${i}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:t,start:!0,...a.length?{images:a}:{}})})).promptId;e&&Nr(o,Mr(o).map(t=>t.id===c?{...t,promptId:e}:t)),Qo([]),pd(Vn())&&Hn(!1),Wo(),s&&(Wn(!0),Zn(0),we=0,requestAnimationFrame(()=>{fa(),requestAnimationFrame(()=>{Un()&&fa()})}))}catch(e){Nr(o,Mr(o).filter(e=>e.id!==c)),k(t),console.error(`send failed:`,e)}},ts=async t=>{t.preventDefault();let r=n(),i=ne().trim();if(r&&i){if(i.startsWith(`@`)){let t=i.indexOf(` `),r=(t===-1?i.slice(1):i.slice(1,t)).toLowerCase(),a=t===-1?``:i.slice(t+1).trim(),o=wo().some(e=>e.key.toLowerCase()===r),s=e().some(e=>e.id.toLowerCase()===r);try{if(o){if(!a){aD(`usage: @${r} <task>`);return}aD(`🧩 spawned ${(await Y(`/api/agents/${n()}/spawn`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({persona:r,task:a,context:Do()?`fork`:`none`})})).id}${Do()?` (forked context)`:``}`),bi(),k(``)}else if(s){if(!a){aD(`usage: @${r} <message>`);return}await Y(`/api/agents/${encodeURIComponent(r)}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:a,start:!0})}),aD(`→ delivered to @${r}`),k(``)}else{aD(`unknown @${r} — personas: ${wo().map(e=>e.key).join(`, `)||`(none)`}`);return}}catch(e){aD(`@${r} failed: ${e.message}`)}}else if(i.startsWith(`/`)){let e=i.indexOf(` `),t=(e===-1?i.slice(1):i.slice(1,e)).toLowerCase(),n=e===-1?``:i.slice(e+1).trim();if(t===`goal`&&!n){k(`/goal `);return}if(t===`skill`&&!n){k(`/skill `);return}k(``);try{await ns(t,n)}catch(e){throw k(ne()?`${i}\n${ne()}`:i),e}}else k(``),await es(i)}},ns=async(e,t)=>{let r=n();if(!r)return;let i=(e,t)=>Y(`/api/agents/${r}${e}`,{method:`POST`,headers:{"content-type":`application/json`},...t===void 0?{}:{body:JSON.stringify(t)}}).then(bi);try{if(e===`start`)await i(`/start`);else if(e===`stop`)await i(`/stop`);else if(e===`fork`)await i(`/fork`,{}),await ba(r);else if(e===`compact`)aD((await i(`/compact`))?.ran?`context compacted`:`nothing to compact yet`);else if(e===`goal`){if(!t){aD(`usage: /goal <text>`);return}await i(`/goal`,{text:t,notify:!0}),aD(`goal saved & notification queued`)}else if(e===`skill`){if(!t){aD(`usage: /skill <name>`);return}await i(`/skill`,{name:t}),aD(`skill "${t}" dispatched`)}else aD(`unknown command "${e}" — /start /stop /fork /goal /skill /compact`)}catch(t){aD(`/${e} failed: ${t.message}`)}},rs,is=0;x(()=>{e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!rs)return;let e=Math.min(is,rs.scrollHeight);Math.abs(rs.scrollTop-e)>1&&(rs.scrollTop=e)})})});let as=e=>()=>n()&&Y(`/api/agents/${n()}${e}`,{method:`POST`}).then(bi),os=async()=>{let i=n();if(!i)return;let a=new Set([i,...pn(e(),i).map(e=>e.id)]),o=a.size-1;if(!confirm(`archive agent ${i}?\n\n`+(o>0?`Its ${o} sub-agent${o===1?``:`s`} will be archived too.\n\n`:``)+`They stop running and leave the list, but the config and full session history are KEPT — restore any of them from ⚙️ settings → archive.`))return;await Y(`/api/agents/${i}/archive`,{method:`POST`}).catch(()=>{}),t(e().filter(e=>!a.has(e.id))),m(!0);let s=dd(e(),a);s?ba(s.id):(r(null),Ui())},ss=async()=>{n()&&(aD(`stopped: ${((await Y(`/api/agents/${n()}/stop-children`,{method:`POST`})).stopped??[]).join(`, `)||`(none)`}`),bi())},cs=()=>Y(`/api/agents/${B().id}/fork`,{method:`POST`,headers:{"content-type":`application/json`},body:`{}`}).then(async()=>{await m(!0),await ba(B().id)}),[ls,us]=y(``),ds=()=>({"max-height":`none`,"overflow-y":`auto`,resize:`vertical`}),fs=e=>{T(Gn(e,`goalPreview`))},ps=e=>{T(Gn(e,`goal`))},[ms,G]=y(``),[hs,gs]=y(!1),[_s,vs]=y(!0),ys=``;x(()=>{let e=n();e&&(B()?.goal,e!==ys&&(ys=e,gs(!1),us(``),G(``)))});let bs=async e=>{if(e.preventDefault(),n()&&ls().trim())try{await Y(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:ls(),notify:_s(),...ms().trim()?{verify:ms()}:{}})}),us(``),G(``),gs(!1),bi()}catch(e){aD(`goal save failed: ${e.message}`)}};return[j(N,{get when(){return ci()},get children(){var e=qw();return e.firstChild.firstChild.nextSibling.addEventListener(`submit`,e=>{e.preventDefault();let t=document.getElementById(`pw-input`);localStorage.setItem(`teapot.token`,t.value),location.reload()}),e}}),j(N,{get when(){return ue()},children:e=>(()=>{var t=jT(),n=t.firstChild;return b(t=>{var r=cn(e(),nn[nn.length-1]),i=sn(e());return r!==t.e&&I(n,`src`,t.e=r),i!==t.t&&I(n,`srcset`,t.t=i),t},{e:void 0,t:void 0}),t})()}),(()=>{var t=ET(),r=t.firstChild,i=r.firstChild,a=i.nextSibling.firstChild,o=a.firstChild;o.firstChild;var s=a.nextSibling,c=s.firstChild.firstChild.nextSibling;c.firstChild;var l=c.nextSibling,d=s.nextSibling,f=r.nextSibling,p=f.nextSibling,m=p.firstChild;m.firstChild,R(t,j(N,{get when(){return P(()=>!!he())()&&wt()},get children(){var e=Jw();return e.$$click=kt,e}}),r),R(r,j(N,{get when(){return he()},get children(){var e=Yw(),t=e.firstChild.nextSibling;return t.$$click=kt,e}}),i),R(i,j(M,{get each(){return zi()},children:t=>[j(N,{get when(){return P(()=>t.wsHeader!==void 0)()&&t.wsHeader!==``},get children(){var e=NT(),n=e.firstChild,r=n.nextSibling;return e.$$click=()=>Fi(`ws:${t.wsHeader}`,Ii(t.wsHeader),t.wsCollapsedGroup===!0,t.collapsedVia),R(n,()=>t.wsCollapsedGroup?`▸`:`▾`),R(r,()=>Ii(t.wsHeader)),R(e,j(N,{get when(){return t.wsCollapsedGroup},get children(){var e=MT();return R(e,()=>Ri().get(t.wsHeader)??0),e}}),null),b(n=>{var i=t.wsCollapsedGroup?`${t.wsHeader} — collapsed (${Li(t.wsHeader)} hidden). Click to show.`:(Ri().get(t.wsHeader)??0)>1?`${t.wsHeader} — ${Li(t.wsHeader)} in this directory`:t.wsHeader||``,a=t.wsHeader;return i!==n.e&&I(e,`title`,n.e=i),a!==n.t&&I(r,`title`,n.t=a),n},{e:void 0,t:void 0}),e}}),j(N,{get when(){return P(()=>!t.headerOnly)()&&!t.wsCollapsedGroup},get children(){var r=RT(),i=r.firstChild,a=i.nextSibling;return r.$$click=()=>ba(t.a.id),R(r,j(N,{get when(){return dn({isSub:!!t.a.parent,collapsed:t.chatCollapsedGroup===!0,hasChildren:e().some(e=>e.parent===t.a.id)})},get fallback(){return zT()},get children(){return(()=>{let e=!t.a.parent,n=e&&Ni().has(`chat:${t.a.id}`)||H(t.a.id);return(()=>{var r=BT();return r.$$click=r=>{if(r.stopPropagation(),e){if(n){if(!Ei().has(t.a.id)){let e=new Set(Ei());e.add(t.a.id),V(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}if(Di().has(t.a.id)){let e=new Set(Di());e.delete(t.a.id),Oi(e),localStorage.setItem(`teapot.collapsed`,JSON.stringify([...e]))}}else if(Ei().has(t.a.id)){let e=new Set(Ei());e.delete(t.a.id),V(e),localStorage.setItem(`teapot.expandedSubs`,JSON.stringify([...e]))}Fi(`chat:${t.a.id}`,t.a.id,n)}else ki(t.a.id)},R(r,n?`▸`:`▾`),b(()=>I(r,`title`,e?n?`show ${t.a.id}`:`hide ${t.a.id} and its sub-agents`:n?`expand sub-agents`:`collapse sub-agents`)),r})()})()}}),i),R(a,()=>Kn({id:t.a.id,sessionTitle:t.a.sessionTitle??u().get(t.a.session??``)})),R(r,(()=>{var e=P(()=>!!t.a.workspaceMissing);return()=>e()?VT():null})(),null),R(r,j(N,{get when(){return Ur(t.a.id)>0},get children(){var e=PT();return e.firstChild,R(e,()=>Ur(t.a.id),null),b(()=>I(e,`title`,`${Ur(t.a.id)} unread notification${Ur(t.a.id)>1?`s`:``} (including sub-agents)`)),e}}),null),R(r,j(N,{get when(){return H(t.a.id)||t.chatCollapsedGroup===!0&&Ni().has(`chat:${t.a.id}`)},get children(){return(()=>{let n=pn(e(),t.a.id),r=n.filter(e=>e.live??(e.status===`running`||e.status===`waiting`||e.status===`needs_operator`)).length;return n.length>0?(()=>{var e=HT();return e.firstChild,L(e,`subcount`+(r>0?` live`:``)),R(e,()=>n.length,null),R(e,r>0?` · ▶${r}`:``,null),b(()=>I(e,`title`,`${n.length} sub-agent${n.length>1?`s`:``} (${r} active)`)),e})():null})()}}),null),R(r,j(N,{get when(){return t.a.parent},get children(){return FT()}}),null),R(r,j(N,{get when(){return Ti(t.a.id).length>0},get children(){var e=IT();return b(()=>I(e,`title`,Ti(t.a.id).map(e=>`${e.id}: ${e.schedule}`).join(`
188
+ `))),e}}),null),R(r,j(N,{get when(){return t.a.goal.status===`done`},get children(){return LT()}}),null),b(e=>{var o=`agent-item`+(t.a.id===n()?` sel`:``)+(t.depth>0?` sub-row`:``)+(t.chatCollapsedGroup?` collapsed`:``),s=t.depth>0?`padding-left:${10+t.depth*14}px`:``,c=t.a.parent?(()=>{let e=fn(t.a.id,wo().map(e=>e.key));return e?`sub-agent of @${t.a.parent} — "${e}"`:`sub-agent of @${t.a.parent}`})():void 0,l=`dot ${t.a.status}`,d=t.a.status===`needs_operator`?`waiting for your answer`:t.a.status===`waiting`?`waiting on its own work — resumes by itself`:t.a.status,f=t.a.workspaceMissing?` ghost`:``,p=t.a.workspaceMissing?`workspace not found on disk (${t.a.workspace}) — it will be created when this session runs`:qn({id:t.a.id,sessionTitle:t.a.sessionTitle??u().get(t.a.session??``)});return o!==e.e&&L(r,e.e=o),e.t=Oe(r,s,e.t),c!==e.a&&I(r,`title`,e.a=c),l!==e.o&&L(i,e.o=l),d!==e.i&&I(i,`title`,e.i=d),f!==e.n&&L(a,e.n=f),p!==e.s&&I(a,`title`,e.s=p),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),r}})]})),o.$$click=e=>{e.stopPropagation(),zr(!Rr()),Rr()||Fr(e=>e.map(e=>({...e,read:!0})))},R(o,j(N,{get when(){return Br()>0},get children(){var e=Xw();return R(e,Br),e}}),null),R(a,j(vd,{icon:`👻`,get active(){return Ir()},get title(){return Ir()?`show ghost sessions again (👻 workspace missing on disk)`:`hide ghost sessions (👻 — their workspace directory no longer exists)`},onClick:t=>{t.stopPropagation();let r=!Ir();if(Lr(r),localStorage.setItem(`teapot.hideGhosts`,r?`1`:`0`),r&&n()&&B()?.workspaceMissing){let t=e().find(e=>!e.workspaceMissing);t&&ba(t.id)}}}),null),R(a,j(vd,{icon:`+`,title:`new agent`,onClick:()=>{si(),se(!0)}}),null),R(a,j(vd,{icon:`⚙️`,title:`settings`,onClick:()=>{si(),fe(!0)}}),null),R(c,`0.37.149`,null),R(d,j(N,{get when(){return D()},get children(){return[`master rss `,P(()=>D().rssMb),`MB · heap `,P(()=>D().heapUsedMb),`MB`,j(N,{get when(){return D().heapTotalMb!==void 0},get children(){return[` · total `,P(()=>D().heapTotalMb),`MB`]}}),j(N,{get when(){return D().externalMb!==void 0},get children(){return[` · ext `,P(()=>D().externalMb),`MB`]}}),j(N,{get when(){return D().arrayBuffersMb!==void 0},get children(){return[` · buf `,P(()=>D().arrayBuffersMb),`MB`]}}),Zw(),j(N,{get when(){return D().messagesInMemory!==void 0},get children(){return[`msgs `,P(()=>D().messagesInMemory),` in `,P(()=>D().loadedSessions),` loaded session(s)`,Zw()]}}),`load1 `,P(()=>D().loadavg1),` · up `,P(()=>Math.floor(D().uptimeSec/60)),`m`]}})),R(f,j(N,{get when(){return B()?.id},get fallback(){return UT()},get children(){return[(()=>{var t=iT(),r=t.firstChild,i=r.nextSibling,a=i.nextSibling,o=a.firstChild,s=o.nextSibling,c=s.nextSibling.nextSibling,l=c.nextSibling.nextSibling,u=l.nextSibling.nextSibling;u.nextSibling;var d=a.nextSibling,f=d.firstChild,p=f.nextSibling;return R(t,j(N,{get when(){return he()},get children(){var e=Qw();return e.$$click=()=>Tt(!wt()),b(()=>I(e,`aria-expanded`,wt())),e}}),r),r.$$click=()=>Ga(),R(t,j(N,{get when(){return Va()},get fallback(){return(()=>{var e=WT();return e.$$click=()=>Ga(),R(e,()=>Kn(B())),b(()=>I(e,`title`,`${qn(B(),B().session)} — click to rename`)),e})()},get children(){var e=$w();return e.addEventListener(`blur`,()=>void Ka()),e.$$keydown=e=>{e.key===`Enter`?(e.preventDefault(),Ka()):e.key===`Escape`&&(e.preventDefault(),Ha(!1))},e.$$input=e=>Wa(e.currentTarget.value),Ae(e=>{requestAnimationFrame(()=>{e.focus(),e.select()})},e),I(e,`spellcheck`,!1),b(()=>e.value=Ua()),e}}),i),R(i,()=>B().status),R(t,j(N,{get when(){return Cr()>0},get children(){var e=eT(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return n.nextSibling,R(e,Cr,t),R(e,()=>Cr()===1?`message`:`messages`,n),R(e,()=>B().status===`stopped`?` (stopped)`:``,null),b(()=>I(e,`title`,(()=>{let e=B().pendingPromptQueue??[],t=e.length||B().pendingPromptIds?.length||B().pendingPrompts||0,n=e.length?e.filter(e=>(e.source??`user`)===`user`).length:t,r=t-n;return`${`${t} message${t>1?`s`:``} queued${r?` — ${n} from you, ${r} from the harness`:` from you`}`}. ${B().status===`stopped`?`This agent is STOPPED, so nothing will run until you press start (or it is resumed).`:`They are handed to the model at its next turn boundary — the timeline shows them as queued… until then.`}`+(n?` Yours can be withdrawn with ✕ cancel while still queued.`:``)})())),e}}),a),R(t,j(N,{get when(){return(B()?.bgRunning??0)>0},get children(){var e=tT();return e.firstChild,e.$$click=()=>{za(!Ra()),Ra()&&Ba()},R(e,()=>B().bgRunning,null),b(t=>{var n=Ra(),r=`${B().bgRunning} background shell(s) running — click to inspect`;return n!==t.e&&I(e,`aria-expanded`,t.e=n),r!==t.t&&I(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),a),R(t,j(N,{get when(){return Ti(B().id).length>0},get children(){var e=nT();return e.firstChild,R(e,()=>Ti(B().id).length,null),b(()=>I(e,`title`,`scheduled tasks:\n${Ti(B().id).map(e=>`${e.schedule} · ${e.id}${e.forked?` (forked)`:``}`).join(`
189
+ `)}`)),e}}),a),R(a,()=>B().model,o),R(a,()=>B().session,s),R(a,()=>B().branch,c),R(a,()=>B().stats.turns,l),R(a,()=>B().stats.toolCalls,u),f.$$click=()=>(wr()?as(`/stop`):as(`/start`))(),R(f,()=>wr()?`■ stop`:`▶ start`),R(d,j(N,{get when(){return e().some(e=>e.parent===n())},get children(){return j(vd,{icon:`⏹`,title:`stop every sub-agent this agent spawned (descendants included)`,onClick:ss})}}),p),R(d,j(vd,{icon:`🗄`,title:`archive this agent — reversible: it leaves the list but keeps its config and history (restore in ⚙️ settings → archive)`,onClick:os}),null),R(d,j(vd,{icon:`⑂`,title:`fork: branch off the conversation here — try things without disturbing the main line`,onClick:cs}),null),R(d,j(vd,{icon:`⌨`,title:`terminal (t)`,onClick:qa}),null),R(d,j(vd,{icon:`▤`,title:`toggle details panel (d)`,get active(){return vt()},onClick:xt}),null),R(t,j(N,{get when(){return Ra()},get children(){var e=rT(),t=e.firstChild.firstChild.nextSibling;return t.$$click=()=>za(!1),R(e,j(N,{get when(){return Ia().length>0},get fallback(){return GT()},get children(){return j(M,{get each(){return Ia()},children:e=>(()=>{var t=qT(),n=t.firstChild.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return R(r,()=>zx(e.cmd,80)),R(i,(()=>{var t=P(()=>!!e.detached);return()=>t()?`detached · pid ${e.pid??`?`}`:P(()=>!!e.running)()?dt(Date.now()-e.startedAt):`exit ${e.code??`?`}`})(),null),R(i,()=>e.truncated?` · truncated`:``,null),a.$$click=async()=>{await Y(`/api/agents/${encodeURIComponent(B().id)}/bg-jobs/${encodeURIComponent(e.id)}`,{method:`DELETE`}).catch(()=>{}),await Ba()},R(a,(()=>{var t=P(()=>!!e.detached);return()=>t()?`forget`:e.running?`kill`:`clear`})()),R(t,j(N,{get when(){return e.tail.trim()},get fallback(){return j(N,{get when(){return e.detached},get children(){var t=JT(),n=t.firstChild.nextSibling;return n.nextSibling,R(t,()=>e.pid??`?`,n),t}})},get children(){var t=KT();return R(t,()=>e.tail),t}}),null),b(t=>{var i=`bgjob-dot `+(e.running?`running`:`done`),o=e.running?`running`:`finished`,s=e.cmd,c=e.detached?`this job survived a harness restart (pid ${e.pid??`?`}) — its output can no longer be read here; stop it yourself if needed`:e.running?`kill this job (whole process group)`:`forget this finished job`;return i!==t.e&&L(n,t.e=i),o!==t.t&&I(n,`title`,t.t=o),s!==t.a&&I(r,`title`,t.a=s),c!==t.o&&I(a,`title`,t.o=c),t},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()})}}),null),e}}),null),b(e=>{var t=`badge ${B().status}`,n=B().statusReason&&!/^(round complete|prompt|api start|goal set|created via web|start)$/.test(B().statusReason)?`${B().status} — ${B().statusReason}`:void 0,r=`${B().model} · ${B().session}/${B().branch} · turns ${B().stats.turns} · tools ${B().stats.toolCalls}`,o=`runbtn`+(wr()?` danger`:``),s=wr()?`interrupt: aborts the current LLM call; the running tool finishes first`:`run toward the goal (starts the loop)`;return t!==e.e&&L(i,e.e=t),n!==e.t&&I(i,`title`,e.t=n),r!==e.a&&I(a,`title`,e.a=r),o!==e.o&&L(f,e.o=o),s!==e.i&&I(f,`title`,e.i=s),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t})(),(()=>{var e=pT();return e.addEventListener(`scroll`,e=>{let t=e.currentTarget,r={top:t.scrollTop,height:t.scrollHeight,viewport:t.clientHeight},i=Ke(r,Ko,qo,Xo);Ko=null,Ce=performance.now();let a=Go?.top,o=Go?.height;qo=r.height,Xo=r.viewport,Go=r,er(r);let s=Un(),c=performance.now();c-ye>100&&(ye=c,ve=lt(t));let l=o!==void 0&&Math.abs(r.height-o)>.5,u=a!==void 0&&r.top<a-.5&&!l;u&&(we=performance.now()+400);let d=u?!1:Ge(r)?!0:performance.now()<we?!1:Je(s,i,r,a);d!==s&&Wn(d),d&&i!==`reader`?(Xn()&&Zn(0),Hr(),qe(d,r)&&We(r)>0&&fa()):d&&Ge(r)&&(Xn()&&Zn(0),Hr()),r.top<=4&&n()&&!qi()&&!Xi()&&h().length>0&&na()}),Ae(e=>st(e),e),R(e,j(N,{get when(){return tr()},children:e=>(()=>{var t=YT();return t.firstChild,R(t,(()=>{var t=P(()=>e().phase===`harvesting`);return()=>t()?`saving durable lessons…`:`summarizing ${e().summarized?Rx(e().summarized)+` `:``}older messages…`})(),null),t})()}),null),R(e,j(N,{get when(){return P(()=>!!Xi())()&&ti().length>0},get children(){return aT()}}),null),R(e,j(N,{get when(){return qi()},get children(){return oT()}}),null),R(e,j(N,{get when(){return ti().length>0},get fallback(){return P(()=>!!(Ji()||oa()))()?XT():ZT()},get children(){return[j(M,{get each(){return ti()},children:e=>j(pC,{e,prev:()=>ii(e,-1),next:()=>ii(e,1),get showBranch(){return ee().length>1},res:()=>Jr().resFor.get(e.id),get orphan(){return Jr().orphanCalls.has(e.id)},onOption:e=>void es(e),answeredIds:$r,onAnswered:Zr,get agentActive(){return P(()=>!!Tr())()&&Ct(e)},onResize:()=>{Un()&&fa()},get agentId(){return n()??void 0},get onCancel(){return e.data?.source===`user`&&e.data?.pending&&e.data?.promptId&&e.data?.sent!==!0?()=>{let t=String(e.data.promptId);Y(`/api/agents/${n()}/prompt/cancel`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({promptId:t})}).then(e=>{let n=String(e.text??``);k(ne()?`${n}\n\n${ne()}`:n),Nr(jr(),kr().filter(e=>e.promptId!==t)),aD(`message withdrawn — draft restored`)}).catch(()=>aD(`withdraw failed — it may have already been sent`))}:void 0},get onEdit(){return e.type===`prompt`&&e.data?.source===`user`&&!(e.data?.pending&&e.data?.sent!==!0)&&!e.data?.cancelled?async()=>{wr()&&(await Y(`/api/agents/${n()}/stop`,{method:`POST`}).catch(()=>{}),await bi()),Dr({eventId:e.id,text:String(e.data?.text??``)})}:void 0}})}),j(N,{get when(){return oa()},get children(){return sT()}}),j(N,{get when(){return P(()=>!!Ji())()&&!oa()},get children(){return cT()}}),j(N,{get when(){return P(()=>!!Tr())()&&pr()},get children(){var e=fT(),t=e.firstChild.nextSibling;return t.firstChild,R(t,j(N,{get when(){return br().trim()!==``},get children(){var e=lT(),t=e.firstChild;t.firstChild;var n=t.nextSibling;return R(t,j(Kd,{get startedAt(){return yr()}}),null),Ae(e=>{let t=!0;e.addEventListener(`scroll`,()=>{t=e.scrollHeight-e.scrollTop-e.clientHeight<24}),x(()=>{br(),t&&(e.scrollTop=e.scrollHeight)})},n),R(n,br),e}}),null),R(t,j(N,{get when(){return z()},get fallback(){return QT()},get children(){return j(N,{get when(){return sr()},get fallback(){return(()=>{var e=dT();return b(()=>e.innerHTML=Re(z()+`▍`)),e})()},get children(){return[uT(),(()=>{var e=dT();return b(()=>e.innerHTML=Re(cr()+`▍`)),e})()]}})}}),null),e}})]}}),null),e})(),j(N,{get when(){return tt()},children:e=>(()=>{var t=$T(),n=t.firstChild;return De(t,`click`,rt,!0),n.$$click=e=>e.stopPropagation(),b(()=>I(n,`src`,e())),t})()}),j(N,{get when(){return Pa()},get children(){var t=vT(),n=t.firstChild,r=n.nextSibling,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=r.nextSibling,c=s.firstChild;n.$$dblclick=()=>{so(Math.max(220,Math.round(window.innerHeight*.35))),localStorage.setItem(`teapot.termH`,String(oo()))},n.$$pointerdown=bo,R(i,j(M,{get each(){return Ja()},children:(e,t)=>(()=>{var n=eE(),r=n.firstChild.nextSibling;return n.$$click=()=>{fo(t()),Za()},R(n,()=>Xa(e),r),r.$$click=e=>{e.stopPropagation(),ho(t())},b(r=>{var i=`termtab`+(io()===0&&Qa()===t()?` active`:``)+(no()&&io()===1&&eo()===t()?` active`:``),a=`${e.cwd?`${e.cwd}\n`:``}${e.title} — click to show in focused pane`;return i!==r.e&&L(n,r.e=i),a!==r.t&&I(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()}),null),R(i,j(vd,{icon:`+`,title:`new shell in this workspace`,onClick:po}),null),R(o,(()=>{var t=P(()=>!!uo());return()=>t()?e().find(e=>e.id===uo().agentId)?.workspace.split(`/`).filter(Boolean).pop():B()?.workspace})()),R(a,j(vd,{icon:`◫`,get title(){return no()?`single pane`:`split panes (50/50)`},onClick:xo}),null),R(a,j(vd,{icon:`▾`,title:`hide the terminal (shells keep running; reopen with t) — close individual shells with their ✕ tab buttons`,onClick:qa}),null);var l=So(0);return typeof l==`function`&&Ae(l,c),c.$$pointerdown=()=>ao(0),R(c,j(N,{get when(){return Qa()<0||Qa()>=Ja().length},get children(){return mT()}})),R(s,j(N,{get when(){return no()},get children(){return[hT(),(()=>{var e=_T(),t=So(1);return typeof t==`function`&&Ae(t,e),e.$$pointerdown=()=>ao(1),R(e,j(N,{get when(){return eo()<0||eo()>=Ja().length},get children(){return gT()}})),b(()=>e.classList.toggle(`focused`,io()===1)),e})()]}}),null),b(e=>{var n={height:`${oo()}px`},r=!!no(),i=io()===0;return e.e=Oe(t,n,e.e),r!==e.t&&s.classList.toggle(`split`,e.t=r),i!==e.a&&c.classList.toggle(`focused`,e.a=i),e},{e:void 0,t:void 0,a:void 0}),t}}),(()=>{var e=wT(),t=e.firstChild,n=t.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.nextSibling;return R(e,j(N,{get when(){return P(()=>Qn()>32)()&&!Un()},get children(){var e=yT();return e.firstChild,e.$$click=()=>{pa(!0),Hr()},R(e,(()=>{var e=P(()=>Xn()>0);return()=>e()?`${Xn()} new message${Xn()>1?`s`:``}`:`jump to present`})(),null),e}}),t),R(e,j(N,{get when(){return Ro().length>0},get children(){var e=bT();return R(e,j(M,{get each(){return Ro()},children:(e,t)=>(()=>{var n=tE(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{k(e.insert),Lo(-1)},R(r,()=>e.insert.trim()),R(i,()=>e.title),b(r=>{var i=`cmdrow`+(t()===Io()?` active`:``),a=e.title;return i!==r.e&&L(n,r.e=i),a!==r.t&&I(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()})),e}}),t),R(e,j(N,{get when(){return Ao().length>0},get children(){var e=bT();return R(e,j(M,{get each(){return Ao()},children:e=>(()=>{var t=nE(),n=t.firstChild;n.firstChild;var r=n.nextSibling;return t.$$click=()=>{k(`@${e.key} `),Lo(-1)},R(n,()=>e.key,null),R(r,()=>e.label),b(()=>I(t,`title`,e.label)),t})()})),e}}),t),R(e,j(N,{get when(){return Zo().length>0},get children(){var e=xT(),t=e.firstChild;return R(e,j(M,{get each(){return Zo()},children:(e,t)=>(()=>{var n=rE(),r=n.firstChild,i=r.nextSibling;return r.$$click=()=>nt(e.url),i.$$click=()=>Qo(e=>e.filter((e,n)=>n!==t())),b(t=>{var i=e.name,a=e.url,o=e.name;return i!==t.e&&I(n,`title`,t.e=i),a!==t.t&&I(r,`src`,t.t=a),o!==t.a&&I(r,`alt`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),n})()}),t),t.$$click=()=>Qo([]),e}}),t),t.addEventListener(`submit`,ts),n.$$keydown=e=>{let t=Ro();t.length>0&&e.key===`ArrowDown`?(e.preventDefault(),Lo(e=>Math.min(e+1,t.length-1))):t.length>0&&e.key===`ArrowUp`?(e.preventDefault(),Lo(e=>Math.max(e-1,0))):t.length>0&&(e.key===`Tab`||e.key===`Enter`)&&!e.shiftKey&&Io()>=0&&!oD?(e.preventDefault(),k(t[Io()].insert),Lo(-1)):e.key===`Escape`&&t.length>0?Lo(-1):fd({key:e.key,shiftKey:e.shiftKey,composing:oD,maximized:Vn()})&&(e.preventDefault(),ts(e))},n.$$input=e=>{k(e.currentTarget.value),Lo(0),Wo()},n.addEventListener(`paste`,e=>{let t=Array.from(e.clipboardData?.files??[]).filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),$o(t))}),n.addEventListener(`compositionend`,()=>{requestAnimationFrame(()=>{oD=!1}),k(zo?.value??``)}),n.addEventListener(`compositionstart`,()=>{oD=!0}),Ae(e=>{zo=e,e.value=ne()},n),R(t,j(N,{get when(){return P(()=>!!ne().startsWith(`@`))()&&ne().includes(` `)},get children(){var e=ST(),t=e.firstChild;return t.addEventListener(`change`,e=>Oo(e.currentTarget.checked)),b(()=>t.checked=Do()),e}}),r),r.$$click=()=>{let e=!Vn();Hn(e),ze(900),requestAnimationFrame(()=>Wo())},R(r,()=>Vn()?`⤡`:`⤢`),R(t,j(vd,{icon:`📎`,title:`attach images (or paste them straight into the box)`,onClick:()=>document.getElementById(`composer-file`)?.click()}),i),a.addEventListener(`change`,e=>{e.currentTarget.files?.length&&$o(e.currentTarget.files),e.currentTarget.value=``}),R(e,j(N,{get when(){return nD()},get children(){var e=CT();return R(e,nD),e}}),null),b(t=>{var i=`composer`+(Vn()?` maximized`:``),a=`message #${B().id} — / for commands · paste or 📎 to attach images`,o=Vn()?`restore composer (hide timeline)`:`maximize composer — hide the timeline and fill the main column`;return i!==t.e&&L(e,t.e=i),a!==t.t&&I(n,`placeholder`,t.t=a),o!==t.a&&I(r,`title`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),e})()]}})),R(t,j(N,{get when(){return P(()=>!!he())()&&vt()},get children(){var e=TT();return e.$$click=()=>bt(!1),e}}),p),p.addEventListener(`scroll`,e=>{is=e.currentTarget.scrollTop});var g=rs;return typeof g==`function`?Ae(g,p):rs=p,R(m,j(vd,{icon:`✕`,title:`close details panel (esc)`,onClick:St}),null),R(p,j(N,{get when(){return B()?.id},keyed:!0,fallback:null,children:t=>[j(N,{get when(){return B().id},keyed:!0,fallback:null,children:e=>j(Kw,{agentId:e,get workspace(){return B().workspace}})}),(()=>{var e=aE();return e.firstChild,R(e,j(N,{get when(){return rn().length},get children(){var e=iE(),t=e.firstChild.nextSibling;return t.nextSibling,R(e,()=>rn().length,t),e}}),null),e})(),(()=>{var t=cE(),r=t.firstChild,i=r.nextSibling,a=i.firstChild,o=a.nextSibling,s=i.nextSibling,c=s.firstChild,l=s.nextSibling;return l.firstChild,r.addEventListener(`change`,t=>{let r=t.currentTarget.value;An=!0,Jt(r),Xt(jn(ie().providers,r,e().find(e=>e.id===n()))),un(r)}),R(r,j(M,{get each(){return on()},children:e=>(()=>{var t=DE();return t.value=e,R(t,e,null),R(t,()=>e===ie().defaultProvider?` ★`:``,null),t})()})),a.$$input=e=>Xt(e.currentTarget.value),R(o,j(M,{get each(){return rn()},children:e=>(()=>{var t=DE();return b(()=>t.value=e.id),t})()})),R(t,j(N,{get when(){return B().effortSupported},get children(){var e=oE(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>Qt(e.currentTarget.value)),R(t,j(M,{get each(){return P(()=>!!B().effortOptions?.length)()?B().effortOptions:eD},children:e=>(()=>{var t=DE();return t.value=e,R(t,e),t})()}),null),b(()=>t.value=Zt()),e}}),s),c.$$click=async e=>{if(!n())return;let t=e.currentTarget;t.disabled=!0;try{await Y(`/api/agents/${n()}/model`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:qt(),model:Yt().trim()||void 0,contextWindowTokens:rn().find(e=>e.id===(Yt().trim()||void 0))?.contextLength,...B().effortSupported?{reasoningEffort:Zt()}:{}})}),t.textContent=`✓ applied`,bi()}catch(e){alert(`apply failed: ${e.message}`)}finally{setTimeout(()=>{t.textContent=`apply`,t.disabled=!1},1200)}},R(l,()=>B().model,null),R(t,j(N,{get when(){return Tn()},get children(){var e=sE();return R(e,Tn),e}}),null),b(()=>I(a,`placeholder`,Mn(ie().providers,qt(),B(),kn(B(),ie().providers,ie().defaultProvider)))),b(()=>r.value=qt()),b(()=>a.value=Yt()),t})(),(()=>{var e=uE();return e.firstChild,R(e,j(N,{get when(){return!!B().goal.text.trim()},get fallback(){return OE()},get children(){var e=lE();return R(e,()=>B().goal.status),b(()=>L(e,`badge ${B().goal.status===`active`?`running`:B().goal.status}`)),e}}),null),e})(),(()=>{var e=dE();return e.firstChild,R(e,j(M,{each:[`active`,`done`,`paused`],children:e=>(()=>{var t=kE();return t.$$click=()=>{n()&&Y(`/api/agents/${n()}/goal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({status:e})}).then(bi)},I(t,`title`,e===`active`?`agent keeps working toward the goal (with auto-continue)`:e===`done`?`mark achieved — auto-continue stops`:`parked on purpose — resume by setting active again`),R(t,e===`active`?`▶ working`:e===`done`?`✓ done`:`⏸ paused`),b(n=>{var r=`goalstate`+(B().goal.text.trim()&&B().goal.status===e?` on ${e}`:``),i=!!B().goal.text.trim()&&B().goal.status===e;return r!==n.e&&L(t,n.e=r),i!==n.t&&(t.disabled=n.t=i),n},{e:void 0,t:void 0}),t})()}),null),e})(),j(N,{get when(){return B().goal.text},get fallback(){return AE()},get children(){return[(()=>{var e=fE(),t=e.firstChild;return Ae(fs,e),b(n=>{var r=ds(),i=Re(String(B().goal.text));return n.e=Oe(e,r,n.e),i!==n.t&&(t.innerHTML=n.t=i),n},{e:void 0,t:void 0}),e})(),j(N,{get when(){return B().goal.verify},get children(){return j($t,{title:`🔍️ verification contract`,tone:`tool`,get body(){return String(B().goal.verify)}})}}),j(N,{get when(){return B().goal.audit},children:e=>j($t,{get title(){return e().verdict===`approved`?`✅ audit: approved`:`⚠ audit: changes required`},get meta(){return pt(e().at)},get tone(){return e().verdict===`approved`?`ok`:`warn`},get body(){return P(()=>!!Kt(e().feedback))()?`_the auditor returned a verdict with no detail_`:e().feedback}})})]}}),(()=>{var e=pE(),t=e.firstChild,r=t.nextSibling,i=r.nextSibling.firstChild,a=i.firstChild,o=i.nextSibling.firstChild;return e.addEventListener(`submit`,bs),t.$$input=e=>{us(e.currentTarget.value),gs(!0)},Ae(ps,t),r.$$input=e=>{G(e.currentTarget.value),gs(!0)},a.addEventListener(`change`,e=>{n()&&Y(`/api/agents/${n()}/auto-continue`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(bi)}),o.addEventListener(`change`,e=>vs(e.currentTarget.checked)),b(()=>t.value=ls()),b(()=>r.value=ms()),b(()=>a.checked=B().autoContinue??!0),b(()=>o.checked=_s()),e})(),(()=>{var e=hE();return e.firstChild,R(e,j(N,{get when(){return vi().total>0},get children(){var e=mE(),t=e.firstChild,n=t.nextSibling;return n.nextSibling,R(e,()=>vi().done,t),R(e,()=>vi().total,n),b(t=>Oe(e,vi().done===vi().total?`color:var(--ok)`:`color:var(--warn)`,t)),e}}),null),e})(),j(N,{get when(){return vi().total>0},get children(){var e=gE(),t=e.firstChild;return b(e=>{var n=`barfill `+(vi().done===vi().total?``:`warn`),r=`${Math.round(vi().done/vi().total*100)}%`;return n!==e.e&&L(t,e.e=n),r!==e.t&&ke(t,`width`,e.t=r),e},{e:void 0,t:void 0}),e}}),j(pf,{get draft(){return ui()},get preview(){return fi()},onDraft:e=>{di(e),hi(!0)}}),(()=>{var e=_E(),t=e.firstChild,n=t.nextSibling;return R(e,j(vd,{get icon(){return fi()?`✎`:`👁`},get title(){return fi()?`edit markdown`:`rendered checklist`},onClick:()=>pi(!fi())}),t),n.$$click=_i,e})(),vE(),j(N,{get when(){return B().latestProgress},get fallback(){return jE()},children:e=>(()=>{var t=IE(),n=t.firstChild,r=n.firstChild.nextSibling,i=n.nextSibling;return R(t,j(N,{get when(){return e().recent},get children(){var t=ME(),n=t.firstChild.nextSibling;return b(()=>n.innerHTML=ut(e().recent)),t}}),i),R(t,j(N,{get when(){return e().problems},get children(){var t=NE(),n=t.firstChild.nextSibling;return b(()=>n.innerHTML=ut(e().problems)),t}}),i),R(t,j(N,{get when(){return e().next},get children(){var t=PE(),n=t.firstChild.nextSibling;return b(()=>n.innerHTML=ut(e().next)),t}}),i),R(t,j(N,{get when(){return e().goalStatus},get children(){var t=FE(),n=t.firstChild.nextSibling;return R(n,()=>e().goalStatus),t}}),i),R(i,()=>pt(e().ts)),b(()=>r.innerHTML=ut(e().doing)),t})()}),yE(),(()=>{var e=SE(),t=e.firstChild,r=t.firstChild,i=r.firstChild.nextSibling,a=r.nextSibling,o=a.firstChild.nextSibling,s=a.nextSibling,c=s.firstChild.nextSibling,l=s.nextSibling,u=l.firstChild.nextSibling,d=l.nextSibling,f=d.firstChild.nextSibling;return R(e,j(N,{get when(){return B().ctx},keyed:!0,get fallback(){return LE()},children:e=>{let t=S(()=>{let t=e,n=rn().find(e=>e.id===B().model),r=t.window||n?.contextLength||0,i=r?Math.min(999,t.usedTokens/r*100):0;return{usedTokens:t.usedTokens,compactAt:t.compactAt,compacting:t.compacting,window:t.window,effectiveWindow:r,pct:i,cls:r?i>=85?`crit`:i>=70?`warn`:`ok`:``,derivedBudget:r?Math.round(r*.75):0,usingDerived:t.compactAtIsManual!==!0}}),r=()=>t(),i=e=>{let t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)};return(()=>{var e=VE(),t=e.firstChild,a=t.firstChild.nextSibling,o=a.firstChild.nextSibling;o.nextSibling;var s=t.nextSibling,c=s.firstChild.nextSibling,l=c.firstChild,u=c.nextSibling,d=s.nextSibling,f=d.firstChild.firstChild;return R(a,()=>Rx(r().usedTokens),o),R(t,j(N,{get when(){return r().effectiveWindow},get children(){var e=RE(),t=e.firstChild;return R(e,()=>i(r().pct),t),R(e,()=>Rx(r().effectiveWindow),null),b(()=>L(e,`pill ${r().cls}`)),e}}),null),R(e,j(N,{get when(){return r().effectiveWindow},get children(){var e=zE(),t=e.firstChild;return b(e=>{var n=`barfill ${r().cls}`,i=`${Math.min(100,r().pct)}%`;return n!==e.e&&L(t,e.e=n),i!==e.t&&ke(t,`width`,e.t=i),e},{e:void 0,t:void 0}),e}}),s),R(c,()=>Rx(r().usingDerived?r().derivedBudget:r().compactAt),l),R(u,()=>r().usingDerived?`75% of window`:`manual`),R(e,j(N,{get when(){return tr()||r().compacting},get children(){var e=BE(),t=e.firstChild.nextSibling.nextSibling;return R(t,()=>tr()?.phase??String(r().compacting)),e}}),d),f.addEventListener(`change`,e=>{n()&&Y(`/api/agents/${n()}/auto-compact`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({value:e.currentTarget.checked})}).then(bi)}),b(()=>f.checked=B().autoCompact!==!1),e})()}}),t),R(i,()=>Rx(B().stats.inputTokens)),R(o,()=>Rx(B().stats.outputTokens)),R(c,()=>B().stats.turns),R(u,()=>B().stats.toolCalls),R(f,()=>B().stats.compactions??0),R(t,j(N,{get when(){return(B().stats.costUsd??0)>0},get children(){var e=bE(),t=e.firstChild.nextSibling;return t.firstChild,R(t,()=>hD(B().stats.costUsd??0),null),b(()=>I(e,`title`,`≈ ${(B().stats.costUsd??0).toFixed(4)} this session, from the model's per-token pricing and per-turn usage. Cached input is estimated at ~10% of the prompt rate; treat as an approximation, not an invoice.`)),e}}),null),R(t,j(N,{get when(){return(B().stats.cachedInputTokens??0)>0},get children(){var e=xE(),t=e.firstChild.nextSibling,n=t.firstChild;return R(t,()=>Math.round(B().stats.cachedInputTokens/Math.max(1,B().stats.inputTokens)*100),n),b(()=>I(e,`title`,`${Rx(B().stats.cachedInputTokens)} input tokens were served from the provider's prompt cache — billed far cheaper than fresh input`)),e}}),null),b(()=>I(d,`title`,`how many times old turns were summarized into notes to make room. ${B().stats.compactions?`Each one keeps the recent stretch verbatim.`:`Not yet — the context has fit so far.`}`)),e})(),(()=>{var e=wE();return e.firstChild.nextSibling,R(e,j(N,{get when(){return Bi()},get children(){var e=CE(),t=e.firstChild.nextSibling;return R(t,Bi),e}}),null),e})(),j(M,{get each(){return ee()},children:e=>(()=>{var t=HE(),r=t.firstChild,i=r.nextSibling,a=i.firstChild;return t.$$click=()=>{let t=Bi()===e.branch?null:e.branch,r=t!==Bi();Vi(t),n()&&(r&&(Qi++,Ui(),v(0),Zi(!1)),ca(n()))},R(r,()=>e.branch,null),R(r,()=>e.branch===B().branch?` (current)`:``,null),R(i,()=>e.events,a),b(n=>{var r=`branch-row`+(e.branch===B().branch||e.branch===Bi()?` cur`:``),i=e.branch===Bi()?`click to show all branches again`:`show only ${e.branch}`;return r!==n.e&&L(t,n.e=r),i!==n.t&&I(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),(()=>{var e=EE();return e.firstChild,R(e,j(N,{get when(){return Si().length>0},get children(){var e=TE(),t=e.firstChild.nextSibling;return t.nextSibling,R(e,()=>Si().length,t),e}}),null),e})(),j(N,{get when(){return Si().length>0},get fallback(){return UE()},get children(){return j(M,{get each(){return Si()},children:e=>(()=>{var t=GE(),r=t.firstChild,i=r.firstChild,a=i.nextSibling;a.firstChild;var o=r.nextSibling,s=o.firstChild,c=o.nextSibling;return t.$$click=()=>ba(e.agent),R(i,()=>e.id),R(a,()=>e.agent,null),R(r,j(N,{get when(){return e.forked},get children(){return WE()}}),null),R(o,()=>e.schedule,s),R(o,(()=>{var t=P(()=>!!e.next);return()=>t()?pt(e.next):`—`})(),null),R(o,(()=>{var t=P(()=>!!e.last);return()=>t()?` · last ${pt(e.last)}`:` · never ran`})(),null),R(c,()=>zx(e.prompt,90)),b(r=>{var i=`sched-row`+(e.agent===n()?` cur`:``),a=`${zx(e.prompt,200)}\nclick to open #${e.agent}`;return i!==r.e&&L(t,r.e=i),a!==r.t&&I(t,`title`,r.t=a),r},{e:void 0,t:void 0}),t})()})}})]}),null),b(e=>{var n=`layout`+(vt()?``:` right-hidden`)+(wt()?` left-open`:``),i=`sidebar`+(wt()?` open`:``),a=`iconbtn notifbtn`+(Br()>0?` has-unread`:``),s=Br()>0?`${Br()} unread notifications`:`notifications`,c=`conn`+(xa()?` ok`:``),u=xa()?`live (websocket)`:`reconnecting…`,d={"--termh":`${oo()}px`},m=`rightbar`+(vt()?` open`:``);return n!==e.e&&L(t,e.e=n),i!==e.t&&L(r,e.t=i),a!==e.a&&L(o,e.a=a),s!==e.o&&I(o,`title`,e.o=s),c!==e.i&&L(l,e.i=c),u!==e.n&&I(l,`title`,e.n=u),e.s=Oe(f,d,e.s),m!==e.h&&L(p,e.h=m),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0}),t})(),j(N,{get when(){return Rr()},get children(){return[(()=>{var e=DT();return e.$$click=()=>zr(!1),e})(),(()=>{var t=AT(),r=t.firstChild.firstChild.nextSibling,i=r.firstChild;return R(r,j(N,{get when(){return Pr().length>0},get children(){var e=OT();return e.$$click=()=>Fr([]),e}}),i),i.$$click=()=>zr(!1),R(t,j(N,{get when(){return Pr().length>0},get fallback(){return KE()},get children(){var t=kT();return R(t,j(M,{get each(){return Pr()},children:t=>(()=>{var r=JE(),i=r.firstChild.firstChild,a=i.nextSibling,o=a.nextSibling,s=o.nextSibling;return r.$$click=()=>{Fr(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e)),n()!==t.agentId&&e().some(e=>e.id===t.agentId)&&ba(t.agentId),zr(!1),t.eventId&&qr(t.eventId)},R(i,(()=>{var e=P(()=>t.kind===`finish`);return()=>e()?`✅`:P(()=>t.kind===`question`)()?`❓️`:t.kind===`error`?`⚠️`:`📈`})()),R(a,()=>t.title),R(o,()=>pt(new Date(t.at).toISOString())),s.$$click=e=>{e.stopPropagation(),Fr(e=>e.map(e=>e.id===t.id?{...e,read:!0}:e))},R(s,()=>t.read?`✓`:`○`),R(r,j(N,{get when(){return t.body},get children(){var e=qE();return R(e,()=>mD(t.body,160)),e}}),null),b(e=>{var n=`notifitem `+t.kind+(t.read?` read`:``),i=`from ${t.agentId}`,a=t.read?`already read`:`mark as read`;return n!==e.e&&L(r,e.e=n),i!==e.t&&I(r,`title`,e.t=i),a!==e.a&&I(s,`title`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),r})()})),t}}),null),t})()]}}),j(N,{get when(){return oe()},get children(){return j(gD,{get providers(){return Object.keys(ie().providers??{})},onClose:()=>se(!1),onCreated:e=>{se(!1),t(t=>yi(t,[e])),ba(e.id)}})}}),j(N,{get when(){return de()},get children(){return j(Cw,{get cfg(){return ie()},onClose:()=>fe(!1),announcedOAuth:pe,get skills(){return Mo()},get hasSelection(){return!!n()},get agentId(){return n()},get features(){return Po()},onSaved:()=>{si(),wi()},theme:{themes:Rt,activeId:At,paintedId:le,auto:Mt,setAuto:e=>{Nt(e),localStorage.setItem(`teapot.theme.auto`,e?`1`:`0`)},dark:Bt,setDark:Vt,light:Pt,setLight:Ft,setThemes:zt,setActive:jt,preview:e=>Lt(e),commitAppearance:e=>{localStorage.setItem(`teapot.theme.auto`,e.auto?`1`:`0`),localStorage.setItem(`teapot.theme.dark`,e.dark),localStorage.setItem(`teapot.theme.light`,e.light),localStorage.setItem(`teapot.theme`,e.fixed)}}})}}),j(N,{get when(){return Er()},fallback:null,children:e=>{let t=()=>h().findIndex(t=>t.id===e().eventId),r=()=>Math.max(0,h().length-t()-1);return j(bd,{title:`edit prompt — forks the conversation`,onClose:()=>Dr(null),get children(){var t=XE(),i=t.firstChild,a=i.nextSibling,o=a.firstChild;return t.addEventListener(`submit`,async t=>{t.preventDefault();let r=document.getElementById(`edit-text`);try{await Y(`/api/agents/${n()}/edit-prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({eventId:e().eventId,text:r.value})}),Dr(null),bi();let t=n();t&&await ba(t)}catch(e){alert(`edit failed: ${e.message}`)}}),R(t,j(N,{get when(){return r()>0},get children(){var e=YE(),t=e.firstChild;return R(e,r,t),e}}),a),o.$$click=()=>Dr(null),b(()=>i.value=e().text),t}})}})]}function mD(e,t){return e.length>t?e.slice(0,t)+` …`:e}function hD(e){return e>=100?Math.round(e).toLocaleString():e>=10?e.toFixed(1):e>=1?e.toFixed(2):e>=.01?e.toFixed(3):e.toFixed(4)}function gD(e){let[t,n]=y(`~`),[r,i]=y([]),[a,o]=y(``),[s,c]=y(e.providers[0]??``),[l,u]=y(``),[d,f]=y(``);async function p(e){let r=await Y(`/api/fs?path=${encodeURIComponent(e??t())}`);n(r.path),h(r.parent??``),i(r.entries??[])}w(()=>p(t()));let[m,h]=y(``),g=async n=>{n.preventDefault(),f(``);try{let n=await Y(`/api/agents`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({workspace:t(),id:a(),provider:s()||void 0,model:l()||void 0,start:!1})});e.onCreated(n.agent)}catch(e){f(String(e.message))}};return j(bd,{title:`new agent`,get onClose(){return e.onClose},get children(){var i=QE(),f=i.firstChild,h=f.firstChild.nextSibling.firstChild,_=h.nextSibling,v=_.nextSibling,ee=f.nextSibling,y=ee.nextSibling,x=y.firstChild,S=x.firstChild.nextSibling,C=x.nextSibling,w=C.firstChild.nextSibling,T=C.nextSibling.firstChild.nextSibling,E=y.nextSibling;return i.addEventListener(`submit`,g),h.$$input=e=>n(e.currentTarget.value),_.$$click=()=>p(t()),v.$$click=()=>m()?p(m()):p(`..`),R(ee,j(M,{get each(){return r()},children:e=>(()=>{var n=$E();return n.firstChild,n.$$click=()=>p(`${t()}/${e}`.replace(/\/+/g,`/`)),R(n,e,null),n})()})),S.$$input=e=>o(e.currentTarget.value),w.addEventListener(`change`,e=>c(e.currentTarget.value)),R(w,j(M,{get each(){return e.providers},children:e=>(()=>{var t=DE();return R(t,e),t})()})),T.$$input=e=>u(e.currentTarget.value),R(i,j(N,{get when(){return d()},get children(){var e=ZE();return R(e,d),e}}),E),b(()=>h.value=t()),b(()=>S.value=a()),b(()=>w.value=s()),b(()=>T.value=l()),i}})}Ee([`click`,`input`,`keydown`,`pointerdown`,`dblclick`]),Te(()=>j(pD,{}),document.getElementById(`root`));
190
+ //# sourceMappingURL=index-Cy7-gH_6.js.map