@x-otto/tui 0.0.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,109 @@
1
+ import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as l,E as u,Et as d,F as f,Ft as p,G as m,Gt as h,H as g,Ht as _,I as v,It as y,J as b,Jt as x,K as S,Kt as C,L as w,Lt as T,M as E,N as D,Nt as O,O as ee,Ot as te,P as ne,Pt as k,Q as re,Qt as ie,Rt as A,S as ae,St as j,T as oe,Tt as se,U as M,Ut as N,V as ce,Vt as P,W as le,Wt as ue,X as de,Xt as fe,Y as pe,Yt as me,Z as he,Zt as F,_ as ge,_t as _e,a as ve,an as ye,at as be,b as xe,c as Se,cn as Ce,ct as we,d as I,dn as L,dt as Te,en as Ee,et as De,f as Oe,fn as ke,ft as Ae,g as je,h as Me,ht as Ne,i as Pe,in as Fe,it as Ie,j as Le,jt as Re,k as ze,kt as Be,l as Ve,ln as He,lt as Ue,m as We,mt as Ge,n as Ke,nn as qe,nt as Je,o as Ye,on as Xe,ot as Ze,p as Qe,pn as $e,pt as et,q as tt,qt as nt,r as rt,rn as it,rt as at,s as ot,sn as st,st as ct,t as lt,tn as R,tt as ut,u as z,un as dt,ut as ft,v as pt,w as mt,wt as ht,x as gt,xt as _t,y as vt,z as yt,zt as bt}from"./WizardDialog-BGWYjvqR.js";import{i as xt,n as B,r as St,t as Ct}from"./i18n-CznO8p1Y.js";import{CommandRegistry as wt,createBuiltinCommands as Tt,showCommandPalette as Et}from"./compat.js";import{createRequire as Dt}from"node:module";import Ot from"wrap-ansi";import V,{createContext as kt,createElement as H,useCallback as At,useContext as jt,useEffect as U,useMemo as W,useRef as G,useState as K}from"react";import{Fragment as Mt,jsx as q,jsxs as J}from"react/jsx-runtime";import*as Nt from"ink";import{Box as Y,Static as Pt,Text as X,render as Ft,useBoxMetrics as It,useInput as Lt,usePaste as Rt,useStdin as zt,useStdout as Bt}from"ink";import{I18nextProvider as Vt}from"react-i18next";import{createStore as Ht}from"zustand/vanilla";import{useStore as Ut}from"zustand";import{LARGE_FILE_BYTE_THRESHOLD as Wt,matchSubsequence as Gt,matchesGlobPattern as Kt,positionsToHighlightRanges as qt,rankCandidates as Jt,rankLabeledItems as Yt,rankNamedItems as Xt,readFileCapped as Zt,scoreSubsequence as Qt}from"@x-otto/shared";import{readdirSync as $t,statSync as en}from"node:fs";import{adjustDismissedSigil as tn,applySigilCompletion as nn,applySigilReplacement as rn,evaluateSigilTrigger as an,extractSigilPrefix as on}from"@x-otto/interchange";import{basename as sn,dirname as cn,join as ln,resolve as un}from"node:path";import{execSync as dn,spawn as fn}from"node:child_process";import pn from"chalk";import{DEFAULT_DELEGATION_TOOLS as mn,SESSION_MAX_PER_SESSION_BYTES as hn,SESSION_RESUME_WINDOW_MESSAGES as gn}from"@x-otto/session-contract";import{marked as _n}from"marked";import{PassThrough as vn}from"node:stream";const yn=[`trust`,`readonly`,`exit`];function bn({root:e,onChoice:t}){let n=[{key:`trust`,label:B.t(`trust.optTrust`),color:L.success},{key:`readonly`,label:B.t(`trust.optReadonly`),color:L.accent},{key:`exit`,label:B.t(`trust.optExit`),color:L.inactive}];return J(y,{header:q(p,{color:L.warning,children:B.t(`trust.title`)}),footer:q(O,{items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[`1/2/3`,B.t(`hint.quick`)],[T.enter,B.t(`hint.confirm`)],[T.esc,B.t(`hint.exit`)]]}),children:[q(Y,{marginTop:F.tight,children:q(X,{wrap:`truncate-end`,children:B.t(`trust.body`,{path:e})})}),q(Y,{marginTop:F.tight,children:q(Ne.Root,{id:`trust-prompt-dialog`,onPick:e=>t(yn[e]??`exit`),escapeIndex:yn.indexOf(`exit`),children:n.map(e=>q(Ne.Item,{label:e.label,color:e.color},e.key))})})]})}function xn(e){return St(e.language===`zh`?`zh`:e.language===`en`?`en`:Ct()),new Promise(t=>{let n=!1,r=Ft(V.createElement(bn,{root:e.root,onChoice:e=>{n||(n=!0,r.clear(),r.unmount(),_(),t(e))}}),{exitOnCtrlC:!1})})}const Sn=[`use_parent`,`create_new`,`exit`];function Cn({parentRoot:e,currentRoot:t,onChoice:n}){let r=[{key:`use_parent`,label:B.t(`parent.optUseParent`),color:L.success},{key:`create_new`,label:B.t(`parent.optCreateNew`),color:L.accent},{key:`exit`,label:B.t(`parent.optExit`),color:L.inactive}];return J(y,{header:q(p,{color:L.warning,children:B.t(`parent.title`)}),footer:q(O,{items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[`1/2/3`,B.t(`hint.quick`)],[T.enter,B.t(`hint.confirm`)],[T.esc,B.t(`hint.exit`)]]}),children:[q(Y,{marginTop:F.tight,children:q(X,{wrap:`truncate-end`,children:B.t(`parent.body`,{parentRoot:e,currentRoot:t})})}),q(Y,{marginTop:F.tight,children:q(Ne.Root,{id:`parent-workspace-dialog`,onPick:e=>n(Sn[e]??`exit`),escapeIndex:Sn.indexOf(`exit`),children:r.map(e=>q(Ne.Item,{label:e.label,color:e.color},e.key))})})]})}function wn(e){return St(e.language===`zh`?`zh`:e.language===`en`?`en`:Ct()),new Promise(t=>{let n=!1,r=Ft(V.createElement(Cn,{parentRoot:e.parentRoot,currentRoot:e.currentRoot,onChoice:e=>{n||(n=!0,r.clear(),r.unmount(),_(),t(e))}}),{exitOnCtrlC:!1})})}const Tn={five_hour:`5h`,seven_day:`7d`,seven_day_opus:`7d-opus`,seven_day_sonnet:`7d-sonnet`,seven_day_overage_included:`7d`},En={five_hour:`5-hour`,seven_day:`7-day`,seven_day_opus:`7-day (Opus)`,seven_day_sonnet:`7-day (Sonnet)`,seven_day_overage_included:`7-day`};function Dn(e){return En[e]??e}function On(e,t){let n=Math.max(0,Math.round(e-t/1e3)),r=Math.floor(n/3600),i=Math.floor(n%3600/60);return r>0?`${r}h${i>0?`${i}m`:``}`:i>0?`${i}m`:`<1m`}function kn(e,t){return e===`rejected`&&(t===`allowed`||t===`allowed_warning`)}function An(e,t){let n=e.limitType?Tn[e.limitType]??e.limitType:``,r=e.usedPercent===void 0?``:` ${Math.round(e.usedPercent)}%`,i=!!(n||r);if(kn(e.status,e.overageStatus)&&e.overageResetsAt!==void 0)return`${n}${r} +${On(e.overageResetsAt,t)}`.trim();let a=i?` → `:``;return`${n}${r}${e.resetsAt===void 0?``:`${a}${On(e.resetsAt,t)}`}`.trim()}const jn={five_hour:300*60,seven_day:10080*60,seven_day_opus:10080*60,seven_day_sonnet:10080*60,seven_day_overage_included:10080*60};function Mn(e,t,n,r){if(!e||t===void 0||n===void 0)return null;let i=jn[e];if(!i)return null;let a=r/1e3,o=n-i,s=Math.max(0,Math.min(100,Math.round((a-o)/i*100)));return(e===`five_hour`?[[90,72]]:[[75,60],[50,35],[25,15]]).some(([e,n])=>t>=e&&s<=n)?{usedPct:t,timePct:s}:null}function Nn(e,t,n,r,i,a){return kn(e,a)||e===`allowed_warning`||e===`allowed`&&i!==void 0&&Mn(t,n,r,i)?`warning`:`inactive`}function Z(e,t){return Ut(e.zustand,t)}function Pn(e){let t=Ht()(()=>e);return{getState:()=>t.getState(),setState:e=>{let n=t.getState(),r=typeof e==`function`?e(n):e,i=!1;for(let e of Object.keys(r))if(!Object.is(n[e],r[e])){i=!0;break}i&&t.setState(r)},subscribe:e=>t.subscribe(()=>e()),zustand:t}}var Fn=class{buffer=``;active=!1;timer=null;timeoutMs;onEmptyPaste;constructor(e={}){this.timeoutMs=e.timeoutMs??100,this.onEmptyPaste=e.onEmptyPaste}get isPasting(){return this.active}get currentBuffer(){return this.active?this.buffer:``}feed(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(`\x1B[200~`,n),i=e.indexOf(`\x1B[201~`,n),a=r>=0&&i>=0&&i<r;if(this.active){if(r>=0&&!a){this.buffer+=e.slice(n,r),this.clearTimer(),t.push(this.flushPasteEnd()),n=r+6,this.active=!0,this.resetTimer(),t.push({type:`paste_start`});continue}if(i>=0){this.buffer+=e.slice(n,i),this.clearTimer(),t.push(this.flushPasteEnd()),n=i+6;continue}this.buffer+=e.slice(n),this.resetTimer();break}if(r>=0){this.active=!0,this.resetTimer(),t.push({type:`paste_start`}),n=r+6;continue}if(i>=0){n=i+6;continue}break}return t}forceEnd(){if(!this.active)return null;this.clearTimer();let e=this.buffer;return this.buffer=``,this.active=!1,{type:`paste_timeout`,partialText:e}}reset(){this.clearTimer(),this.buffer=``,this.active=!1}destroy(){this.reset()}resetTimer(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.forceEnd(),this.timeoutMs)}clearTimer(){this.timer&&=(clearTimeout(this.timer),null)}flushPasteEnd(){let e=this.buffer,t=e.length===0;return this.buffer=``,this.active=!1,t&&this.onEmptyPaste?.(),{type:`paste_end`,text:e,isEmpty:t}}};const In=/^\x1b\[(\d+)(?:;(\d+))?u$/,Ln=/^\x1b\[27;(\d+);(\d+)~$/,Rn=/^\x1b\[(\d+)~$/;function zn(e){if(!e.startsWith(`\x1B[`)&&!e.startsWith(`\x1BO`))return null;let t=e.match(In);if(t){let n=parseInt(t[1],10),r=t[2]?parseInt(t[2],10):1,i=r>0?r-1:0;return{name:Bn(n),ctrl:!!(i&4),alt:!!(i&2),shift:!!(i&1),meta:!!(i&8),sequence:e}}let n=e.match(Ln);if(n){let t=parseInt(n[1],10),r=parseInt(n[2],10),i=!!(t&8);return{name:Bn(r),ctrl:!!(t&4),alt:i,shift:!!(t&2),meta:i,sequence:e}}if(e.startsWith(`\x1BO`)){let t=e[2],n={A:`up`,B:`down`,C:`right`,D:`left`,H:`home`,F:`end`,P:`f1`,Q:`f2`,R:`f3`,S:`f4`};return t&&t in n?{name:n[t],shift:!1,alt:!1,ctrl:!1,meta:!1,sequence:e}:null}let r=e.match(/^\x1b\[(?:\d+;)?(\d+)?([ABCD])$/);if(r){let t={A:`up`,B:`down`,C:`right`,D:`left`},n=r[1]?parseInt(r[1],10):1;return{name:t[r[2]],ctrl:!!(n&4),alt:!!(n&8),shift:!!(n&2),meta:!!(n&8),sequence:e}}let i=e.match(Rn);return i?{name:Vn(parseInt(i[1],10)),shift:!1,alt:!1,ctrl:!1,meta:!1,sequence:e}:null}function Bn(e){return e>=97&&e<=122?String.fromCharCode(e):e>=65&&e<=90?String.fromCharCode(e+32):e===13?`return`:e===9?`tab`:e===27?`escape`:e===32?`space`:e===127||e===8?`backspace`:String.fromCharCode(e)}function Vn(e){switch(e){case 1:case 7:return`home`;case 2:return`insert`;case 3:return`delete`;case 4:case 8:return`end`;case 5:return`pageup`;case 6:return`pagedown`;case 11:return`f1`;case 12:return`f2`;case 13:return`f3`;case 14:return`f4`;case 15:return`f5`;case 17:return`f6`;case 18:return`f7`;case 19:return`f8`;case 20:return`f9`;case 21:return`f10`;case 23:return`f11`;case 24:return`f12`;default:return`f${e}`}}function Hn(e){if(!process.stdout.isTTY)return;let t=Un(e);t&&process.stdout.write(`\x1b]0;${t}\x07`)}function Un(e){let t=e.replace(/[\x00-\x1f\x7f-\x9f]/g,``).replace(/[\u200b\u200c\u200e\u200f\u202a-\u202e\u2060-\u206f\ufeff]/g,``).replace(/\s+/g,` `).trim();return t.length>240?t.slice(0,240):t}function Wn(e,t,n){return t?`\x1b]8;${n?`id=${encodeURIComponent(n)}`:``};${encodeURIComponent(t)}\x1b\\${e}\x1b]8;;\x1b\\`:e}function Gn(e,t,n,r){let i=t.startsWith(`file://`)?t:`file://${t}`;return n!==void 0&&(i+=`#L${n}`),r!==void 0&&(i+=`:${r}`),Wn(e,i)}function Kn(e,t=`c`){let n=Buffer.from(e,`utf-8`).toString(`base64`);process.stdout.write(`\x1b]52;${t};${n}\x07`)}function qn(e=`c`){return`\x1b]52;${e};?\x07`}function Jn(){process.stdout.write(`\x1BP=1s\x1B\\`)}function Yn(){process.stdout.write(`\x1BP=2s\x1B\\`)}function Xn(e){Jn();try{return e()}finally{Yn()}}const Zn=RegExp(`\x1B\\[\\?2026[hl]`,`g`);function Qn(e){return e.includes(`\x1B[?2026`)?e.replace(Zn,``):e}function $n(e){return new Proxy(e,{get(e,t){if(t===`write`)return(t,...n)=>e.write(typeof t==`string`?Qn(t):t,...n);let n=Reflect.get(e,t);return typeof n==`function`?n.bind(e):n}})}function er(e=process.env){return!!e.TMUX&&e.OTTO_TUI_SYNC!==`1`}const tr=RegExp(`\x1B\\[3J`,`g`);function nr(e){return e.includes(`\x1B[3J`)?e.replace(tr,``):e}function rr(e){return new Proxy(e,{get(e,t){if(t===`write`)return(t,...n)=>e.write(typeof t==`string`?nr(t):t,...n);let n=Reflect.get(e,t);return typeof n==`function`?n.bind(e):n}})}function ir(e=50){let t=[],n=0;return{snapshot(r){let i=Date.now();if(i-n<1e3)return;n=i;let a=t[t.length-1];a&&a.text===r.text&&a.offset===r.offset||(t.push({text:r.text,offset:r.offset,timestamp:i}),t.length>e&&t.splice(0,t.length-e))},undo(){return t.length===0?null:(n=0,t.pop())},get depth(){return t.length},reset(){t.length=0,n=0}}}function ar(e,t){if(!e)return[];let n=[];for(let r=t.length-1;r>=0;r--){let i=t[r],a=Gt(e,i);a&&n.push({entry:i,index:r,score:a.score,highlightRanges:qt(a.positions)})}return n.sort((e,t)=>t.score-e.score||t.index-e.index),n.map(({entry:e,highlightRanges:t})=>{let n=t[0],r=t.at(-1);return{entry:e,matchStart:n?.start??0,matchEnd:r?.end??0,highlightRanges:t}})}function or(e={}){let t=e.maxSize??100,n=e.initialEntries?[...e.initialEntries]:[];n.length>t&&n.splice(0,n.length-t);let r=-1,i=``,a=!1,o=[],s=``;return{push(e){e.length!==0&&(n.length>0&&n[n.length-1]===e||(n.push(e),n.length>t&&n.shift()))},navigateUp(e){return n.length===0?null:r===-1?(i=e,r=n.length-1,n[r]):r<=0?null:(r--,n[r])},navigateDown(){return r===-1?null:(r++,r>=n.length?(r=-1,i):n[r])},resetNavigation(){r=-1,i=``},beginSearch(e){s=e,a=!0,o=[],r===-1&&(i=e)},search(e){return!a||!e?[]:(o=ar(e,n),o)},acceptSearch(e){if(e<0||e>=o.length)return null;let t=o[e].entry;return a=!1,r=n.indexOf(t),t},cancelSearch(){return a=!1,o=[],s},get size(){return n.length},get navState(){return r===-1?null:{position:n.length-r,total:n.length}},getAll(){return n},clear(){n.length=0,r=-1,i=``,a=!1,o=[]}}}function sr(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}const cr=sr(`OTTO_PASTE_STORE_MAX_ENTRIES`,64),lr=sr(`OTTO_PASTE_STORE_MAX_BYTES`,33554432),ur=sr(`OTTO_PASTE_STORE_PERSIST_MAX_BYTES`,8388608),dr={healthy:1,warning:2,critical:4},fr=/\[@paste:#(\d+)(?:\s+\+(\d+)\s+lines)?\]/g;function pr(e){let t=[];fr.lastIndex=0;let n;for(;(n=fr.exec(e))!==null;)t.push({start:n.index,end:n.index+n[0].length,id:Number.parseInt(n[1],10)});return t}function mr(e){return Buffer.byteLength(e,`utf-8`)}function hr(e){if(!(typeof e!=`number`||!Number.isFinite(e)))return Math.floor(e)}function gr(e={}){let{residencyGovernor:t}=e,n=new Map,r=1,i=0,a=0;function o(){return t?.currentLevel??`healthy`}function s(){return Math.max(1,Math.floor(cr/dr[o()]))}function c(){return Math.max(1,Math.floor(lr/dr[o()]))}function l(e){let t=s(),r=c();for(;n.size>0&&(n.size>=t||i+e>r);){let e=n.keys().next().value;if(e===void 0)break;let t=n.get(e);t&&(i-=t.byteLength),n.delete(e),a++}}return{foldIfLarge(e){let t=e.split(`
2
+ `);if(e.length<=800&&t.length<=20)return e;let a=mr(e);l(a);let o=r++;return n.set(o,{text:e,byteLength:a}),i+=a,t.length>1?`[@paste:#${o} +${t.length} lines]`:`[@paste:#${o}]`},expandAll(e){let t=pr(e);if(t.length===0)return{text:e,missingIds:[]};let r=[],s=o(),c=[...t].sort((e,t)=>t.start-e.start),l=e;for(let e of c){let t=n.get(e.id);if(t===void 0){r.push(e.id);continue}l=l.slice(0,e.start)+t.text+l.slice(e.end),s===`healthy`?(n.delete(e.id),n.set(e.id,t)):(n.delete(e.id),i-=t.byteLength,a++)}return{text:l,missingIds:r.sort((e,t)=>e-t)}},findMissingIds(e){let t=pr(e),r=[];for(let e of t)n.has(e.id)||r.push(e.id);return[...new Set(r)].sort((e,t)=>e-t)},peek(e){return n.get(e)?.text},truncateIfNeeded(e){return e.length<=1e4?e:e.slice(0,500)+`\n[...Truncated ${e.length-500-500} chars...]\n`+e.slice(e.length-500)},addImageRef(){return`[@paste:image #${r++}]`},afterSubmit(e){if(o()!==`healthy`)for(let t of pr(e)){let e=n.get(t.id);e!==void 0&&(n.delete(t.id),i-=e.byteLength,a++)}},toSnapshot(){let e=[...n.entries()].map(([e,t])=>({id:e,text:t.text,byteLength:t.byteLength})),t=e.reduce((e,t)=>e+t.byteLength,0),i=0;for(;i<e.length&&t>ur;)t-=e[i].byteLength,i++;return{entries:i>0?e.slice(i):e,nextId:r}},hydrate(e){n.clear(),i=0;let t=Math.max(1,Math.floor(hr(e?.nextId)??0));for(let n of e?.entries??[]){let e=hr(n?.id);e!==void 0&&(t=Math.max(t,e+1))}r=Math.max(r,t);for(let t of e?.entries??[]){let e=hr(t?.id);if(e===void 0||typeof t?.text!=`string`||n.has(e))continue;let r=mr(t.text);n.set(e,{text:t.text,byteLength:r}),i+=r}},get size(){return n.size},get bytesUsed(){return i},get evictionCount(){return a},clear(){n.clear(),i=0}}}function _r(e){let t=e?[...e]:[],n=new Map;return{register(e){for(let n of e)t.some(e=>e.name===n.name)||t.push(n);t.sort((e,t)=>(e.sortKey??e.name).localeCompare(t.sortKey??t.name))},search(e,n=50){return Jt(t.map(e=>({text:e.name,aliases:[...e.aliases??[],...e.description?[e.description]:[]],payload:e,sortKey:e.sortKey})),e,{maxResults:n}).map(e=>e.item.payload)},getAll:()=>t,find:e=>t.find(t=>t.name===e),registerArgumentSuggester(e,t){n.set(e,t)},getArgumentSuggester(e){return n.get(e)}}}function vr(e,t){let n=e.slice(0,t).trimStart();if(!n.startsWith(`/`))return null;let r=n.match(/^\/(.*)$/);return r?r[1]??``:null}function yr(e,t,n){let r=vr(e,t);if(r===null)return null;let i=r.indexOf(` `);if(i>0){let e=r.slice(0,i),t=r.slice(i+1),a=n.getArgumentSuggester(e);if(a){let n=Xt(a(t),t);if(n.length>0)return{suggestions:n,selectedIndex:0,prefix:`/${r}`,panelOpen:!0,argCommand:e}}return null}let a=n.search(r);return a.length===0?null:{suggestions:a,selectedIndex:0,prefix:`/${r}`,panelOpen:!0}}function br(e,t){switch(t){case`prev`:return{...e,selectedIndex:(e.selectedIndex-1+e.suggestions.length)%e.suggestions.length};case`next`:return{...e,selectedIndex:(e.selectedIndex+1)%e.suggestions.length};case`accept`:return`accept`;case`dismiss`:return`dismiss`}}function xr(e,t,n){let r=e.slice(0,t),i=r.lastIndexOf(`/`);if(i<0)return{text:e,offset:t};let a=r.slice(i+1),o=a.indexOf(` `),s=o>=0?a.slice(o):` `,c=`/${n.name}${s}`;return{text:e.slice(0,i)+c+e.slice(t),offset:i+c.length}}function Sr(e){return{text:e,offset:e.length}}function Cr(e,t,n,r){if(!e)return null;let i=t.slice(0,n),a=i.lastIndexOf(`
3
+ `)+1;return Ge(i.slice(a)+(t.slice(n).split(`
4
+ `)[0]??``))+Ge(e)>r?null:e}function wr(e){return e.startsWith(`!!`)?{prefix:`!!`,body:e.slice(2)}:e.startsWith(`!`)?{prefix:`!`,body:e.slice(1)}:{prefix:``,body:e}}function Tr(e){return e.startsWith(`!!`)?e.slice(2):e.startsWith(`!`)?e.slice(1):e}function Er(e,t,n){let{prefix:r,body:i}=wr(e);if(r.length>0){if(i.length===0)return null;let e=i.toLowerCase();for(let a=n.length-1;a>=0;a--){let o=Tr(n[a]);if(o.length<=i.length||!o.toLowerCase().startsWith(e))continue;let s=r+o;return{fullText:s,suffix:s.slice(t),kind:`history`}}return null}let a=e.toLowerCase();for(let r=n.length-1;r>=0;r--){let i=n[r];if(!(i.length<=e.length)&&i.toLowerCase().startsWith(a))return{fullText:i,suffix:i.slice(t),kind:`history`}}return null}function Dr(e,t,n){let r=vr(e,t);if(r===null||r.length===0)return null;let i=r.indexOf(` `);if(i>0){let a=r.slice(0,i),o=r.slice(i+1),s=n.getArgumentSuggester(a);if(!s)return null;let c=Xt(s(o),o,{maxResults:1});if(c.length===0)return null;let l=kr(e,t,a,c[0].name);return{fullText:l.text,suffix:l.text.slice(t),kind:`slash-arg`}}let a=n.search(r,1);if(a.length===0)return null;let o=xr(e,t,a[0]);return{fullText:o.text,suffix:o.text.slice(t),kind:`slash-command`}}function Or(e){let{text:t,offset:n,dismissedPrefix:r,history:i,registry:a}=e;if(n!==t.length||t.length===0||r!==void 0&&r===t)return null;if(a&&t.trimStart().startsWith(`/`)){let e=vr(t,n);if(e!==null&&e.length===0)return null;let r=Dr(t,n,a);if(r)return r}return Er(t,n,i)}function kr(e,t,n,r){let i=e.slice(0,t),a=i.lastIndexOf(`/`);if(a<0)return{text:e,offset:t};let o=i.slice(a+1).indexOf(` `);if(o<0)return{text:e,offset:t};let s=a+1+o+1;return{text:e.slice(0,s)+r+e.slice(t),offset:s+r.length}}function Ar(e){return(e.VISUAL||e.EDITOR||``).trim()||(process.platform===`win32`?`notepad`:`vi`)}function jr(e,t){let n=Ar(t.env),r=null;try{r=t.mkdtempSync(t.join(t.tmpdir(),`otto-edit-`));let i=t.join(r,`prompt.md`);t.writeFileSync(i,e);let a=n.split(/\s+/).filter(Boolean),o=a[0],s=[...a.slice(1),i],c=t.spawnSync(o,s,{stdio:`inherit`});return c.error?{ok:!1,error:`cannot launch editor "${n}": ${c.error.message}`}:c.status!=null&&c.status!==0?{ok:!1,error:`editor exited with code ${c.status}`}:{ok:!0,text:t.readFileSync(i).replace(/\n$/,``)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}finally{if(r)try{t.rmSync(r,{recursive:!0,force:!0})}catch{}}}function Mr(){let e=$e(`fs`),t=$e(`os`),n=$e(`path`),r=$e(`child_process`);return{env:process.env,tmpdir:()=>t.tmpdir(),join:(...e)=>n.join(...e),mkdtempSync:t=>e.mkdtempSync(t),writeFileSync:(t,n)=>e.writeFileSync(t,n),readFileSync:t=>e.readFileSync(t,`utf8`),rmSync:(t,n)=>e.rmSync(t,n),spawnSync:(e,t,n)=>{let i=r.spawnSync(e,t,n);return{status:i.status,error:i.error}}}}const Nr=`/overlay/toast`,Pr=`/overlay/pause`,Fr=`/overlay/retry`,Ir=`/overlay/error-retry`,Lr=`/overlay/pulse-survey`,Rr=`/overlay/forced-upgrade`,zr=`/overlay/paste-confirm`,Br=`/overlay/services`,Vr=`/overlay/chip-viewer`,Hr=[Nr,Pr,Fr,Ir,Lr,Rr,zr,Br,Vr];function Ur(e){return e.startsWith(`/overlay/`)}function Wr(e,t,n){e&&(n?e.ensure(t):e.dismiss(t))}const Gr=[/\bpassword\s*=/i,/\btoken\s*=/i,/export\s+\w*key\w*\s*=/i,/\bsecret\s*=/i];function Kr(e,t=Gr){return t.some(t=>t.test(e))}const qr=`zsh-histfile`,Jr=/^: (\d+):(\d+);(.*)$/s;function Yr(e){let t=[],n;for(let r of e){let e=n===void 0?r:`${n}\n${r}`;if(Xr(r)){n=e.slice(0,-1);continue}t.push(e),n=void 0}return n!==void 0&&t.push(n),t}function Xr(e){let t=0;for(let n=e.length-1;n>=0&&e[n]===`\\`;n--)t++;return t%2==1}function Zr(e,t={}){let{source:n=qr,sensitivePatterns:r,filterSensitive:i=!0}=t,a=[],o=0;for(let t of Yr(e.split(`
5
+ `))){if(!t)continue;let e=t.match(Jr);if(e){let t=e[3]??``;if(!t||i&&Kr(t,r))continue;a.push({command:t,timestamp:Number(e[1])*1e3,source:n});continue}if(t.startsWith(`:`))continue;let s=t.trim();s&&(i&&Kr(s,r)||(a.push({command:s,timestamp:o,source:n}),o++))}return Qr(a)}function Qr(e){let t=new Map;for(let n of e){let e=ei(n.command),r=t.get(e);(!r||$r(n)>=$r(r))&&t.set(e,n)}return[...t.values()].sort((e,t)=>$r(e)-$r(t))}function $r(e){return e.timestamp??0}function ei(e){return e.trim().replace(/\s+/g,` `)}const ti=`bash-histfile`;function ni(e,t={}){let{source:n=ti,sensitivePatterns:r,filterSensitive:i=!0}=t,a=e.split(`
6
+ `),o=[],s=0;for(let e=0;e<a.length;e++){let t=a[e];if(!t)continue;let c=t.match(/^#(\d+)$/);if(c){let t=a[e+1]?.trim();if(!t)continue;if(i&&Kr(t,r)){e++;continue}o.push({command:t,timestamp:Number(c[1])*1e3,source:n}),e++;continue}if(t.startsWith(`#`))continue;let l=t.trim();l&&(i&&Kr(l,r)||(o.push({command:l,timestamp:s,source:n}),s++))}return ri(o)}function ri(e){let t=new Map;for(let n of e){let e=ei(n.command),r=t.get(e);(!r||ii(n)>=ii(r))&&t.set(e,n)}return[...t.values()].sort((e,t)=>ii(e)-ii(t))}function ii(e){return e.timestamp??0}const ai=`fish-histfile`;function oi(e,t={}){let{source:n=ai,sensitivePatterns:r,filterSensitive:i=!0}=t,a=[],o,s,c=0,l=()=>{if(o){if(i&&Kr(o,r)){o=void 0,s=void 0;return}a.push({command:o,timestamp:s??c++,source:n}),o=void 0,s=void 0}};for(let t of e.split(`
7
+ `)){let e=t.match(/^\s*-\s*cmd:\s*(.+)$/);if(e){l(),o=si(e[1].trim());continue}let n=t.match(/^\s*when:\s*(\d+)\s*$/);if(n&&o){s=Number(n[1])*1e3;continue}!t.trim()&&!t.startsWith(`-`)&&l()}return l(),ci(a)}function si(e){return e.startsWith(`'`)&&e.endsWith(`'`)||e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e}function ci(e){let t=new Map;for(let n of e){let e=ei(n.command),r=t.get(e);(!r||li(n)>=li(r))&&t.set(e,n)}return[...t.values()].sort((e,t)=>li(e)-li(t))}function li(e){return e.timestamp??0}const ui=`otto-session`,di={[ui]:2};function fi(e,t,n={}){let r=t.reduce((e,t)=>Math.max(e,hi(t)),0),i=Math.max(n.ottoTimestampBase??0,r+1),a=e.map((e,t)=>({command:e,source:ui,timestamp:i+t})),o=[...t,...a],s=new Map;for(let e of o){let t=ei(e.command);if(!t)continue;let n=s.get(t);if(!n){s.set(t,e);continue}s.set(t,pi(n,e))}return[...s.values()].sort((e,t)=>hi(e)-hi(t))}function pi(e,t){let n=mi(e.source),r=mi(t.source);return n===r?hi(e)>=hi(t)?e:t:n>r?e:t}function mi(e){return di[e]??1}function hi(e){return e.timestamp??0}function gi(e){return e.map(e=>e.command)}function _i(e,t,n){let r=fi(e,t,n);return{getCommands:()=>gi(r),getEntries:()=>r}}function vi(e,t){let n=e.startsWith(`!!`)?2:e.startsWith(`!`)?1:0;if(n===0)return null;let r=e.slice(n),i=t-n;if(i<=0)return{word:``,start:n,source:`command`};let a=r.slice(0,i),o=r.slice(i),s=a.lastIndexOf(` `)+1,c=a.slice(s),l=o.search(/\s/),u=c+(l===-1?o:o.slice(0,l)),d=r.slice(0,s).trim()===``?`command`:`path`;return{word:u,start:s+n,source:d}}let yi=null;function bi(){if(yi)return yi;let e=(process.env.PATH??`/usr/local/bin:/usr/bin:/bin`).split(`:`).filter(Boolean),t=new Set,n=[];for(let r of e)try{let e=$t(r);for(let r of e)t.has(r)||(t.add(r),n.push(r))}catch{}return n.sort(),yi=n,n}function xi(e){let t=e.toLowerCase();return bi().filter(e=>e.toLowerCase().startsWith(t))}function Si(e,t){let n=un(t,e),r=e.endsWith(`/`)||e===``?n:cn(n),i=e.endsWith(`/`)||e===``?``:sn(n),a;try{a=$t(r)}catch{return[]}let o=i.toLowerCase(),s=[];for(let e of a){if(!e.toLowerCase().startsWith(o)||e.startsWith(`.`))continue;let t=un(r,e),n;try{n=en(t)}catch{continue}n.isDirectory()?s.push(e+`/`):s.push(e)}return s.sort(),s}function Ci(e){if(e.length===0)return``;if(e.length===1)return e[0];let t=0,n=e[0];for(;t<n.length;){let r=n[t];for(let i of e)if(t>=i.length||i[t]!==r)return n.slice(0,t);t++}return n}function wi(e,t){switch(t){case`prev`:return{...e,selectedIndex:(e.selectedIndex-1+e.completions.length)%e.completions.length};case`next`:return{...e,selectedIndex:(e.selectedIndex+1)%e.completions.length};case`accept`:return`accept`;case`dismiss`:return`dismiss`}}function Ti(e,t,n){let r=n.completions[n.selectedIndex];if(!r)return{text:e,offset:t};let{wordStart:i,prefix:a}=n,o=i+a.length+(e.slice(i+a.length).search(/\s|$/)===-1?e.length-i-a.length:Math.max(0,e.slice(i+a.length).search(/\s/))),s=e.slice(0,i),c=e.slice(o),l=r,u=i===1?` `:``;return{text:s+l+u+c,offset:i+l.length+u.length}}function Ei(e,t){let n=Ci(t.completions);if(n.length<=t.prefix.length)return{text:e,offset:e.length};let r=e.slice(0,t.wordStart),i=e.slice(t.wordStart+t.prefix.length);return{text:r+n+i,offset:t.wordStart+n.length}}function Di(e){return e.startsWith(`!!`)?`bash_async`:e.startsWith(`!`)?`bash`:e.startsWith(`#`)?`memory`:`send`}function Oi(e,t){return t===`bash_async`&&e.startsWith(`!!`)?e.slice(2):t===`bash`&&e.startsWith(`!`)||t===`memory`&&e.startsWith(`#`)?e.slice(1):e}const ki={send:`> `,bash:`! `,bash_async:`!! `,memory:`# `};function Ai({columns:n=80,placeholder:r=``,disabled:i=!1,reviewing:a=!1,commands:o=[],onSubmit:s,onInterrupt:c,onClear:l,onEscape:u,onHistorySearch:d,historySearchOpen:p=!1,sigilEnabled:m=!1,onSigilTrigger:_,onSigilClose:v,onChipReopen:y,onChipViewPaste:b,onToast:x,onDraftSave:S,keybindingOverrides:C,onPasteConfirm:w,cwd:E,historyInsertRef:D,pasteBridgeRef:ee,initialHistory:te,externalHistoryCommands:k,onHistoryPush:ie,onHistoryNavChange:A,residencyGovernor:ae,registryRef:oe,shellBackendRef:se}){let M=h(),[N,ce]=K(``),[P,le]=K(0),[ue,de]=K(`send`),[fe,me]=K(null),he=G(null),ge=he.current??=or({initialEntries:te}),[_e,ve]=K(0),ye=W(()=>k?.length?k.map(e=>({command:e,source:`external-shell`})):[],[k]),be=W(()=>{let e=ge.getAll();return ye.length?gi(fi(e,ye)):e},[ge,_e,ye]);D&&(D.current={fill:e=>Ke(e,e.length),append:e=>{let t=N+e;Ke(t,t.length)}});let xe=G(null),Se=xe.current??=ir(),Ce=G(null),we=Ce.current??=gr({residencyGovernor:ae});ee&&(ee.current={hydrate:e=>we.hydrate(e),export:()=>we.toSnapshot()});let I=G(!1),L=W(()=>_r(o),[o]);oe&&(oe.current=L);let{setRawMode:Ee}=zt(),De=G(0),Oe=G(null),ke=G(null),[je,Me]=K(null),Ne=G(!1),Pe=G(N),Fe=G(P);Pe.current=N,Fe.current=P;let[Le,Re]=K(void 0),ze=W(()=>p||je?.visible||Oe.current!==null?null:Or({text:N,offset:P,dismissedPrefix:Le,history:be,registry:L}),[N,P,Le,p,je,ue,fe,L,be]),Be=W(()=>{if(!ze)return;let e=Math.max(20,n-Ge(ki[ue]));return Cr(ze.suffix,N,P,e)??void 0},[ze,N,P,n,ue]),Ve=W(()=>new Set(we.findMissingIds(N)),[N,we]),He=At((e,t,n)=>{e!==N&&Re(void 0),Se.snapshot({text:N,offset:P});let r=Math.max(0,Math.min(t,e.length));if(ce(e),le(r),de(Di(e)),me(yr(e,t,L)),Me(null),!m||!_){ke.current=tn(ke.current,N,e),Oe.current=null;return}let i=an({source:n,oldText:N,newText:e,cursorOffset:r,dismissed:ke.current});if(ke.current=i.dismissed,i.action!==`open`){Oe.current=null,i.action===`close`&&v?.();return}let a=i.trigger;Oe.current={sigil:a.sigil,anchor:a.anchor,cursor:r},_(a.sigil,a.query,{select:t=>{let n=Oe.current;if(Oe.current=null,!n)return;let r=nn(e,n.cursor,n.anchor,t);He(r.text,r.offset,`completion`)},cancel:t=>{let n=Oe.current;if(Oe.current=null,n){if(!t){ke.current={sigil:n.sigil,anchor:n.anchor,tokenLength:n.cursor-n.anchor};return}He(e.slice(0,n.anchor)+e.slice(n.cursor),n.anchor,`completion`)}}})},[L,N,P,m,_,v]),We=At((e,t)=>{He(e,t,`typing`)},[He]),Ke=At((e,t)=>{He(e,t,`programmatic`)},[He]),qe=At((e,t)=>{let n=we.findMissingIds(e);if(n.length>0){x?.(B.t(`paste.titlePasteExpired`),B.t(`paste.expiredToast`,{count:n.length}));let t=n[0],r=/\[@paste:#(\d+)(?:\s+\+\d+\s+lines)?\]/g,i,a;for(;(i=r.exec(e))!==null;)if(Number.parseInt(i[1],10)===t){a=i.index;break}a!==void 0&&He(e,a,`programmatic`);return}let{text:r}=we.expandAll(e),i=Di(r),a=Oi(r,i);if(!a.trim()){ce(``),le(0),de(`send`),me(null),Me(null);return}e.trim()&&(ge.push(e),ve(e=>e+1),ie?.(ge.getAll())),ge.resetNavigation(),I.current=!1,A?.(null),we.afterSubmit(e),Se.reset(),s?.(a,i,t)!==`rejected`&&(ce(``),le(0),de(`send`),me(null),Me(null))},[s,we,x,He]),Je=At(e=>{De.current=Date.now();let t=Ze(e);if(!t)return;let n=t.split(`
8
+ `);if((t.length>800||n.length>20)&&w)w(t,{confirm:()=>{let e=we.foldIfLarge(t);He(N.slice(0,P)+e+N.slice(P),P+e.length,`paste`)},cancel:()=>{}});else{let e=we.foldIfLarge(t);He(N.slice(0,P)+e+N.slice(P),P+e.length,`paste`)}},[N,P,we,He,w]),{currentPath:Ye}=g(),Xe=Ye===`/`||Ye===`/home`,Qe=G(null),$e=(Xe||Ye===`/overlay/toast`)&&!i&&ue===`send`,tt=G(0);return Rt(Je,{isActive:Xe&&!i}),j(`prompt-input`,At((e,t)=>{if(t.ctrl&&e===`c`){c?.();return}if(t.ctrl&&e===`l`){l?.();return}if(pe(re,`prompt`,e,t,C)===`save-draft`)return N.trim()?(S?.(N),x?.(B.t(`draft.sLabel`),B.t(`draft.saved`)),!0):(x?.(B.t(`draft.sLabel`),B.t(`draft.saveEmpty`)),!0);if(i)return;if(t.tab&&Be&&ze){let e=Sr(ze.fullText);return He(e.text,e.offset,`completion`),!0}if(t.tab&&fe&&!fe.panelOpen&&fe.suggestions.length>0&&ue!==`bash`&&ue!==`bash_async`)return me({...fe,panelOpen:!0}),!0;if(t.ctrl&&e===`r`){d?.();return}if(t.ctrl&&e===`x`){try{Ee?.(!1)}catch{}let e=jr(N,Mr());try{Ee?.(!0)}catch{}e.ok&&e.text!=null?Ke(e.text,e.text.length):e.error&&x?.(B.t(`toast.editorError`),e.error);return}if(t.ctrl&&(e===`_`||e===``||e===`-`)){let e=Se.undo();e&&(He(e.text,e.offset,`programmatic`),me(null),Me(null));return}if(Be&&t.escape){Re(N);return}if(fe&&fe.panelOpen){if(t.escape){me({...fe,panelOpen:!1});return}if(t.upArrow||t.downArrow||t.tab||t.return){let e=br(fe,t.upArrow?`prev`:t.downArrow?`next`:`accept`);if(e===`accept`){let e=fe.suggestions[fe.selectedIndex];if(e&&!e.disabled){let n=fe.argCommand?kr(N,P,fe.argCommand,e.name):xr(N,P,e);return t.return?(qe(n.text,!1),!0):(He(n.text,n.offset,`completion`),!0)}return me(null),!0}return e===`dismiss`?(me({...fe,panelOpen:!1}),!0):(me(e),!0)}}let r=ue===`bash`||ue===`bash_async`;if(t.tab&&r&&se?.current){let e=se.current;if(je&&je.visible){let e=wi(je,`next`);if(e===`accept`){let e=Ti(N,P,je);return He(e.text,e.offset,`completion`),Me(null),!0}return e===`dismiss`?(Me(null),!0):(Me(e),!0)}if(Ne.current)return!0;let t=N,n=P;return Ne.current=!0,(async()=>{let r=await e.getCompletions({text:t,cursorOffset:n,cwd:E??process.cwd()});if(Ne.current=!1,Pe.current!==t||Fe.current!==n)return;let i=vi(t,n);if(!i||r.length===0)return;let{word:a,start:o}=i;if(r.length===1){let e=Ti(t,n,{completions:r,selectedIndex:0,prefix:a,wordStart:o,visible:!0,commonPrefixApplied:!1});He(e.text,e.offset,`completion`);return}let s=Ci(r);if(s.length>a.length){let e={completions:r,selectedIndex:0,prefix:a,wordStart:o,visible:!0,commonPrefixApplied:!1},n=Ei(t,e);He(n.text,n.offset,`completion`),Me({...e,prefix:s,commonPrefixApplied:!0});return}Me({completions:r,selectedIndex:0,prefix:a,wordStart:o,visible:!0,commonPrefixApplied:!1})})(),!0}if(t.escape&&N.length===0){u?.();return}if(e.length>1&&!t.ctrl&&!t.meta&&!t.return&&!t.escape&&!t.backspace&&!t.delete&&!t.tab&&!t.upArrow&&!t.downArrow&&!t.leftArrow&&!t.rightArrow){let t=Ze(e);if(t){let e=we.foldIfLarge(t);We(N.slice(0,P)+e+N.slice(P),P+e.length)}return}let a=I.current,o=N.trimStart().startsWith(`/`);if(t.downArrow&&o&&fe&&fe.suggestions.length>0&&!a&&!N.includes(`
9
+ `)){Re(N),me({...fe,panelOpen:!0});return}let s=Ue.fromText(N,n,P),f=s.up().offset!==s.offset,p=s.down().offset!==s.offset;if(t.upArrow&&(!f||a)){let e=ge.navigateUp(N);if(e!==null){I.current=!0,Ke(e,e.length);let t=ge.navState;t&&A?.({...t,entry:e})}return}if(t.downArrow&&(!p||a)){let e=ge.navigateDown();if(e!==null){I.current=!0,Ke(e,e.length);let t=ge.navState;A?.(t?{...t,entry:e}:null)}else I.current=!1;return}if(t.upArrow||t.downArrow){I.current=!1;let e=Ue.fromText(N,n,P),r=t.upArrow?e.up():e.down();We(r.text,r.offset);return}if(I.current&&(I.current=!1,A?.(null)),t.leftArrow){let e=Ue.fromText(N,n,P).left();We(e.text,e.offset);return}if(t.rightArrow||t.end){if(Be&&ze){let e=Sr(ze.fullText);He(e.text,e.offset,`completion`);return}if(t.end){We(N,N.length);return}let e=Ue.fromText(N,n,P).right();We(e.text,e.offset);return}if(t.return&&Date.now()-De.current<50)return;if(t.return){let e=Te(N,P);if(e){let t=Ae(e.text);if(t===`paste`){let t=et(e.text);if(t===void 0)return;let n=we.peek(t);n!==void 0&&b?b(e.text,n):x&&x(B.t(`paste.titlePasteExpired`),B.t(`paste.expiredToast`,{count:1}));return}if(y){let n={start:e.start,end:e.end};y(t,n,{select:e=>{let t=rn(N,n.start,n.end,e);He(t.text,t.offset,`completion`)},cancel:()=>{}});return}}}(t.backspace||t.delete)&&(tt.current=Date.now());let m={name:t.return?`return`:t.escape?`escape`:t.backspace?`backspace`:t.delete?`delete`:t.tab?`tab`:e||`unknown`,ctrl:t.ctrl??!1,shift:t.shift??!1,alt:t.meta??!1,meta:t.meta??!1},h=Ie(Ue.fromText(N,n,P),m);if(h){if(h.action===`submit`){qe(N,!1);return}if(h.action===`submit_force`){qe(N,!0);return}if(h.action===`clear_text`){We(h.cursor.text,h.cursor.offset);return}We(h.cursor.text,h.cursor.offset)}},[N,P,n,i,fe,je,se,ue,E,c,l,u,x,S,C,y,b,we,He,qe,We,Ke,Be,ze]),{isActive:Xe&&!i&&!a}),J(Y,{flexDirection:`column`,children:[fe&&fe.panelOpen&&fe.suggestions.length>0&&(()=>{let e=fe.suggestions.length,n=fe.selectedIndex,r=e<=10?0:Math.min(Math.max(0,n-5),e-10),i=fe.suggestions.slice(r,r+10);return J(Y,{flexDirection:`column`,...t,borderColor:M.panelBorder,children:[q(Y,{height:1,children:q(ne,{hasMore:r>0,count:r})}),i.map((e,t)=>{let i=r+t;return J(X,{color:i===n?M.selection:void 0,dimColor:i!==n||!!e.disabled,bold:i===n,children:[i===n?`${R.pointer} `:` `,`/`,e.name,e.aliases?.length?` (${e.aliases.join(`, `)})`:``,e.description?` — ${e.description}`:``]},e.name)}),q(Y,{height:1,children:q(f,{hasMore:r+10<e,count:e-r-10})}),q(Y,{marginTop:F.tight}),q(O,{items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[T.enter,B.t(`hint.confirm`)],[T.esc,B.t(`hint.close`)]]})]})})(),je&&je.visible&&je.completions.length>0&&(()=>{let e=je.completions.length,n=je.selectedIndex,r=e<=10?0:Math.min(Math.max(0,n-5),e-10),i=je.completions.slice(r,r+10);return J(Y,{flexDirection:`column`,...t,borderColor:M.panelBorder,children:[q(Y,{height:1,children:q(ne,{hasMore:r>0,count:r})}),i.map((e,t)=>{let i=r+t;return J(X,{color:i===n?M.selection:void 0,dimColor:i!==n,bold:i===n,children:[i===n?`${R.pointer} `:` `,e]},e)}),q(Y,{height:1,children:q(f,{hasMore:r+10<e,count:e-r-10})})]})})(),i&&q(X,{dimColor:!0,children:r||R.ellipsis}),!i&&q(e,{value:N,offset:P,columns:n,mode:ue,placeholder:a?B.t(`prompt.reviewingPlaceholder`):Xe?r||B.t(`prompt.fallback`):B.t(`prompt.unfocused`),focused:Xe&&!a,ghostSuffix:Be,invalidPasteIds:Ve,containerRef:Qe,physicalCursor:$e,deleteKeyAt:tt.current})]})}function ji({items:e}){let t=h();return e.length===0?null:J(Y,{children:[q(X,{color:t.special,children:`▸ `}),q(D,{type:`secondary`,children:B.t(`queue.label`)}),J(D,{type:`secondary`,children:[` `,e.length]}),J(D,{type:`secondary`,dim:!0,children:[` `,A(`q`)]})]})}function Mi(e){return`'`+e.replace(/'/g,`'\\''`)+`'`}function Ni(e,t,n){let r=Object.entries(t).map(([e,t])=>e+`=`+Mi(t)).join(` `);try{return dn(r+` `+e,{timeout:n,maxBuffer:100*1024}).toString(`utf-8`).split(`
10
+ `).filter(Boolean)}catch{return[]}}var Pi=class{name=`bash`;commandCache=null;async getCommands(e){if(this.commandCache&&e){let t=e.toLowerCase(),n=[];for(let[,e]of this.commandCache)for(let r of e)r.toLowerCase().startsWith(t)&&n.push(r);return n.map(e=>({value:e,type:`command`}))}let t=Ni(`bash -c 'compgen -ac'`,{},200),n=new Map;for(let e of t){let t=e.charAt(0).toLowerCase(),r=n.get(t)??[];r.push(e),n.set(t,r)}if(this.commandCache=n,!e)return t.map(e=>({value:e,type:`command`}));let r=e.toLowerCase();return t.filter(e=>e.toLowerCase().startsWith(r)).map(e=>({value:e,type:`command`}))}buildCompreplyScript(){return[`for compfile in /usr/share/bash-completion/bash_completion \\`,` /usr/local/share/bash-completion/bash_completion \\`,` "$HOME/.bash_completion"; do`,` [ -f "$compfile" ] && source "$compfile" 2>/dev/null && break`,`done`,`_init_completion -s 2>/dev/null || true`,`COMP_WORDS=($words)`,`COMP_CWORD=$cword`,`COMPREPLY=()`,`_command_completion 2>/dev/null`,'printf "%s\\n" "${COMPREPLY[@]}"'].join(`
11
+ `)}buildCompgenFileScript(e){return`bash -c 'compgen -A file -- `+Mi(e)+` 2>/dev/null; compgen -A directory -- `+Mi(e)+` 2>/dev/null'`}async getCompletions(e){let{words:t,wordIndex:n,cwd:r}=e;if(t.length===0)return[];let i=t[0]?.word??``,a=Ni(`bash -c '`+this.buildCompreplyScript()+`'`,{words:t.map(e=>e.word).join(` `),cword:String(n),cmd:i},500);if(a.length>0)return a.map(e=>({value:e,type:`arg`}));let o=t[n]?.word??``,s=Ni(this.buildCompgenFileScript(o),{},200);return s.length>0?s.map(e=>({value:e,type:e.endsWith(`/`)?`dir`:`file`})):Si(o,r).map(e=>({value:e,type:e.endsWith(`/`)?`dir`:`file`}))}destroy(){this.commandCache=null}},Fi=class{name=`zsh`;commandCache=null;async getCommands(e){if(this.commandCache&&e){let t=e.toLowerCase(),n=[];for(let[,e]of this.commandCache)for(let r of e)r.toLowerCase().startsWith(t)&&n.push(r);return n.map(e=>({value:e,type:`command`}))}let t=Ni("zsh -c 'autoload -Uz compinit; compinit -i 2>/dev/null; print -l ${(k)_comps}'",{},300),n=new Map;for(let e of t){let t=e.charAt(0).toLowerCase(),r=n.get(t)??[];r.push(e),n.set(t,r)}if(this.commandCache=n,!e)return t.map(e=>({value:e,type:`command`}));let r=e.toLowerCase();return t.filter(e=>e.toLowerCase().startsWith(r)).map(e=>({value:e,type:`command`}))}async getCompletions(e){let{words:t,wordIndex:n}=e,r=t[0]?.word??``,i=t[n]?.word??``,a=Ni("zsh -c 'autoload -Uz compinit; compinit -i 2>/dev/null; _comps[$cmd] $cmd ${(q)prefix}'",{cmd:r,prefix:i},500);if(a.length>0)return a.map(e=>({value:e,type:`arg`}));let o=Ni("zsh -c 'print -l ${(k)_commands} 2>/dev/null'",{},200);if(o.length>0){let e=i.toLowerCase();return o.filter(t=>t.toLowerCase().startsWith(e)).map(e=>({value:e,type:`command`}))}return[]}destroy(){this.commandCache=null}},Ii=class{name=`builtin`;async getCommands(e){if(!e)return bi().map(e=>({value:e,type:`command`}));let t=e.toLowerCase();return bi().filter(e=>e.toLowerCase().startsWith(t)).map(e=>({value:e,type:`command`}))}async getCompletions(e){let{words:t,wordIndex:n,cwd:r}=e,i=t[n]?.word??``;return n===0?this.getCommands(i):Si(i,r).map(e=>({value:e,type:e.endsWith(`/`)?`dir`:`file`}))}destroy(){}};const Li={enabled:!0,backend:`auto`,commandTimeoutMs:200,argTimeoutMs:500,maxResults:100};function Ri(){let e=process.env.SHELL??``;return e.includes(`zsh`)?`zsh`:e.includes(`bash`)||e.includes(`sh`)?`bash`:`other`}function zi(e){let t={...Li,...e};if(!t.enabled||t.backend===`disabled`)return null;let n=t.backend;switch(n===`auto`&&(n=Ri()===`zsh`?`zsh`:`bash`),n){case`bash`:return new Pi;case`zsh`:return new Fi;case`builtin`:return new Ii;default:return new Ii}}const Bi={commandTimeoutMs:200,argTimeoutMs:500,maxResults:100,commandCacheTtlMs:3e4,argCacheTtlMs:3e4,maxCacheEntries:50};function Vi(e){return Date.now()>e.expiresAt}function Hi(e,t){return e.slice(0,t).map(e=>e.value)}function Ui(e,t){let n=new Set,r=[];for(let i of[...e,...t])n.has(i)||(n.add(i),r.push(i));return r}var Wi=class{backend;opts;commandCache=null;argCache=new Map;abortController=null;constructor(e,t){this.backend=e,this.opts={...Bi,...t}}cancelPending(){this.abortController&&=(this.abortController.abort(),null)}getCommands(e){if(this.commandCache&&!Vi(this.commandCache)&&e){let t=e.toLowerCase();return Promise.resolve(this.commandCache.data.filter(e=>e.toLowerCase().startsWith(t)))}if(!this.backend){let t=xi(e);return this.commandCache={data:[...t],expiresAt:Date.now()+this.opts.commandCacheTtlMs},Promise.resolve(t)}return Promise.race([this.backend.getCommands(e).then(t=>{let n=Hi(t,this.opts.maxResults);return this.commandCache={data:[...n],expiresAt:Date.now()+this.opts.commandCacheTtlMs},Ui(n,xi(e))}).catch(()=>xi(e)),new Promise(t=>{setTimeout(()=>t(xi(e)),this.opts.commandTimeoutMs)})])}getCompletions(e){let{text:t,cursorOffset:n,cwd:r}=e,i=vi(t,n);if(!i)return Promise.resolve([]);let{word:a,source:o}=i;if(o===`command`)return this.getCommands(a);if(!this.backend)return Promise.resolve(Si(a,r));let s=t.startsWith(`!!`)?t.slice(2):t.startsWith(`!`)?t.slice(1):t,c=s.split(` `).filter(Boolean),l=n-(t.length-s.length),u=Math.max(0,s.slice(0,l).split(` `).filter(Boolean).length-1),d=c[0]??``,f=r+`|`+d+`|`+a,p=this.argCache.get(f);if(p&&!Vi(p))return Promise.resolve(p.data);let m={text:s,cursorOffset:l,words:c.map(e=>({word:e,offset:0})),wordIndex:u,cwd:r,signal:void 0};return Promise.race([this.backend.getCompletions(m).then(e=>{let t=Ui(Hi(e,this.opts.maxResults),Si(a,r));return this.setArgCache(f,t),t}).catch(()=>Si(a,r)),new Promise(e=>{setTimeout(()=>e(Si(a,r)),this.opts.argTimeoutMs)})])}setArgCache(e,t){if(this.argCache.size>=this.opts.maxCacheEntries){let e=[...this.argCache.entries()],t=Math.ceil(this.opts.maxCacheEntries/3);for(let n=0;n<t&&n<e.length;n++)this.argCache.delete(e[n][0])}this.argCache.set(e,{data:t,expiresAt:Date.now()+this.opts.argCacheTtlMs})}makeShellCompletion(e,t,n){return{completions:e,selectedIndex:0,prefix:n,wordStart:t,visible:!0,commonPrefixApplied:!1}}destroy(){this.cancelPending(),this.backend&&=(this.backend.destroy(),null),this.commandCache=null,this.argCache.clear()}};function Gi(e,t){if(t!==`send`)return``;let n=e.trimStart();return n.startsWith(`/`)?(n.slice(1).split(/\s+/)[0]??``).toLowerCase():``}function Ki(e,t){return e?.()??t}function qi(e,t){return e||t}function Ji(e,t){return e||t}function Yi(e,t){return e||t}function Xi(e,t,n,r){let i=Gi(e,t);return i&&r.isInterruptCommand?.(i)||i&&r.isImmediateCommand(i)?`command`:r.processing?n||t!==`send`||i?`queue`:`steer`:`send`}let Zi=null;function Qi(){return Zi||=Pn({indices:{}}),Zi}function $i(e,t){let n=Qi(),r=Z(n,t=>t.indices[e]??0),i=t>0?Math.min(r,Math.max(0,t-1)):r,a=G(e);a.current=e;let o=G(t);return o.current=t,U(()=>{i!==r&&n.setState(e=>({indices:{...e.indices,[a.current]:i}}))},[i,r,n]),[i,e=>{let t=n.getState().indices[a.current]??0,r=typeof e==`function`?e(t):e,i=Math.max(0,o.current-1),s=o.current>0?Math.min(r,i):r;s!==t&&n.setState(e=>({indices:{...e.indices,[a.current]:s}}))}]}function ea(e,t,n){let r=Math.max(1,Math.floor(t)),i=Math.max(0,e-r),a=Math.min(Math.max(0,Math.floor(n)),i),o=Math.min(e,a+r);return{offset:a,start:a,end:o,above:a,below:Math.max(0,e-o)}}function ta(){let e=Pn({offset:0,totalLines:0}),t=new Set;return{store:e,scrollBy(t){let n=e.getState();if(n.totalLines<=0)return;let r=n.totalLines-1;e.setState({offset:Math.min(r,Math.max(0,n.offset+t))})},page(t,n){let r=Math.max(1,Math.floor(n)-2),i=e.getState();if(i.totalLines<=0)return;let a=i.totalLines-1;e.setState({offset:Math.min(a,Math.max(0,i.offset+t*r))})},toTop(){e.setState({offset:2**53-1})},toBottom(){e.setState({offset:0})},setOffset(t){let n=e.getState();if(n.totalLines<=0)return;let r=n.totalLines-1;e.setState({offset:Math.min(r,Math.max(0,Math.floor(t)))})},setTotalLines(t){e.setState({totalLines:Math.max(0,Math.floor(t))})},registerWheel(e){return t.add(e),()=>{t.delete(e)}},dispatchWheel(e){if(t.size===0)return!1;let n=[...t];return n[n.length-1](e),!0}}}function na(e,t,n,r){let i=Math.max(0,n-Math.max(1,Math.floor(r)));return Math.min(i,Math.max(0,Math.floor(e)-t*3))}const ra=kt(void 0),ia=ra.Provider;function aa(){return jt(ra)}function oa(e,t,n){if(e<=t||t<=0)return null;let r=Math.max(1,Math.round(t/e*t)),i=e-t,a=t-r;return{start:Math.round(Math.min(Math.max(0,n),i)/i*a),size:r}}function sa(e,t,n){let r=oa(e,t,n),i=[];for(let e=0;e<t;e++)i.push(r&&e>=r.start&&e<r.start+r.size?R.scrollThumb:` `);return i}function ca(e,t){if(t<=0||e.length===0)return``;let n=R.sparkline,r=e.slice(-t),i=r.filter(e=>Number.isFinite(e));if(i.length===0)return n[0].repeat(r.length);let a=Math.min(...i),o=Math.max(...i),s=o-a,c=Math.max(Math.abs(a),Math.abs(o)),l=c===0||s/c<.05;return r.map(e=>Number.isFinite(e)?l?n[3]:n[Math.min(n.length-1,Math.floor((e-a)/s*n.length))]:n[0]).join(``)}function la(e,t){if(t<=0)return``;let n=Math.round(Math.min(1,Math.max(0,e))*t);return R.gaugeFilled.repeat(n)+R.gaugeRest.repeat(t-n)}const ua=`\x1B[43m`,da=`\x1B[49m`,fa=`\x1B[48;5;208m`,pa=`\x1B[49m`;function ma(e,t,n){if(t.length===0||e===``)return e;let r=[];for(let e of t){if(!e)continue;let[t,n]=e,i=r[r.length-1];i&&t<=i[1]?i[1]=Math.max(i[1],n):r.push([t,n])}let i;n&&n[0]!==void 0&&n[1]!==void 0&&(i=[n[0],n[1]]);let a=e=>i!==void 0&&e>=i[0]&&e<i[1],o=e=>r.some(([t,n])=>e>=t&&e<n),s=``,c=0,l=!1,u=!1,d=0,f=!1,p=``,m=()=>{let e=a(c),t=o(c);!l&&t?(s+=e?fa:ua,l=!0,u=e):l&&!t?(s+=u?pa:da,l=!1):l&&t&&e!==u&&(s+=u?pa:da,s+=e?fa:ua,u=e)};for(let t=0;t<e.length;t++){let n=e.charAt(t);if(n===`\x1B`&&t+1<e.length&&e.charAt(t+1)===`]`){let n=t+2;for(;n<e.length;){if(e.charAt(n)===`\x07`){n++;break}if(e.charAt(n)===`\x1B`&&n+1<e.length&&e.charAt(n+1)===`\\`){n+=2;break}n++}s+=e.slice(t,n),t=n-1;continue}if(n===`\x1B`&&t+1<e.length&&e.charAt(t+1)===`[`&&(d++,f=!1,p=``),!d)m(),s+=n,c++;else{if(m(),s+=n,f)f=!1;else{let e=n.charCodeAt(0);e>=64&&e<=126?(l&&n===`m`&&/^(?:0|0;.*|.*;0(?:;.*)?)$/.test(p)&&(s+=u?fa:ua),d=0,p=``):e>=32&&(p+=n)}n===`\x1B`&&d>0&&(f=!0)}}return l&&(s+=u?pa:da),s}function ha(e,t,n={}){if(!t)return[];if(n.regex){let r;try{r=new RegExp(t,n.caseSensitive?`g`:`gi`)}catch{return[]}let i=[],a;for(;(a=r.exec(e))!==null;)i.push([a.index,a.index+a[0].length]),a[0].length===0&&r.lastIndex++;return i}if(n.wholeWord){let r;try{let e=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);r=RegExp(`\\b${e}\\b`,n.caseSensitive?`g`:`gi`)}catch{return[]}let i=[],a;for(;(a=r.exec(e))!==null;)i.push([a.index,a.index+a[0].length]);return i}let r=n.caseSensitive?e:e.toLowerCase(),i=n.caseSensitive?t:t.toLowerCase(),a=[],o=0;for(;;){let e=r.indexOf(i,o);if(e===-1)break;a.push([e,e+t.length]),o=e+1}return a}const ga={keyword:`#C678DD`,built_in:`#56B6C2`,type:`#56B6C2`,literal:`#D19A66`,number:`#D19A66`,regexp:`#98C379`,string:`#98C379`,class:`#E5C07B`,function:`#61AFEF`,comment:`#5C6370`,doctag:`#5C6370`,meta:`#5C6370`,tag:`#E06C75`,name:`#E06C75`,attr:`#56B6C2`,addition:`#98C379`,deletion:`#E06C75`};let _a=null;function va(){if(!_a)return;let e={};for(let[t,n]of Object.entries(ga))e[t]=_a.hex(n);return e}let ya=null,ba=null,xa=null;function Sa(){return xa||(xa=Promise.all([import(`cli-highlight`),import(`chalk`)]).then(([e,t])=>{ya=e.highlight,ba=e.supportsLanguage,_a=t.default}).catch(()=>{}),xa)}function Ca(){return ya!==null}function wa(e,t){if(!ya)return Sa(),null;if(!t||e.length>524288||ba&&!ba(t))return null;try{let n=va();return n?ya(e,{language:t,ignoreIllegals:!0,theme:n}):ya(e,{language:t,ignoreIllegals:!0})}catch{return null}}const Ta=[`•`,`◦`,`▪`,`-`];function Ea(e){return e.every(e=>it(e)===1)}function Da(e,t,n){let r=e[t??n];if(typeof r==`string`&&r.length>0)return r;let i=e[n];return typeof i==`string`?i:``}function Oa(e=L,t,n){let r={...t,...n},i=r.listMarkers&&Ea(r.listMarkers)?r.listMarkers:Ta,a=r.listIndent===3?3:2;return{heading1:Da(e,r.heading1,`accent`),heading2:Da(e,r.heading2,`secondary`),headingWeak:Da(e,r.headingWeak,`inactive`),listMarkerPrimary:Da(e,r.listMarker,`secondary`),listMarkerMuted:Da(e,r.listMarkerMuted,`inactive`),quoteBar:Da(e,r.quoteBar,`accentDim`),quoteText:Da(e,r.quoteText,`secondary`),link:Da(e,r.link,`accentBright`),inlineCode:Da(e,r.inlineCode,`codeText`),codeFenceDivider:Da(e,r.codeFence,`inactive`),tableHeader:Da(e,r.tableHeader,`secondary`),tableDivider:Da(e,r.tableDivider,`inactive`),listIndent:a,listMarkers:i,codeBlockDivider:r.codeBlockDivider===`none`?`none`:`hr`,h1Divider:e.inactive,hr:e.inactive,codeGutter:e.inactive,codeLabel:e.suggestion,tableBody:e.text,taskChecked:e.success}}let ka;function Aa(e){ka=e}function ja(){return ka}function Ma(){return Oa(L,void 0,ka)}function Na(){return Ma()}function Q(e,t){if(!t||!e)return e;try{if(t.startsWith(`#`))return pn.hex(t)(e);let n=pn[t];return typeof n==`function`?n(e):e}catch{return e}}function Pa(e,t,n){return Wn(pn.underline(Q(e,n.link)),t)}const Fa=e=>e.replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#(?:39|x27);/gi,`'`);function Ia(e,t=!1,n=Na()){return La(_n.Lexer.lexInline(e),t,n)}function La(e,t,n){if(!e)return``;let r=``;for(let i of e)switch(i.type){case`text`:{let e=i;r+=e.tokens?La(e.tokens,t,n):Fa(e.text);break}case`escape`:r+=i.text;break;case`codespan`:{let e=Fa(i.text);r+=t?e:Q(e,n.inlineCode);break}case`strong`:{let e=La(i.tokens,t,n);r+=t?e:`\x1b[1m${e}\x1b[22m`;break}case`em`:{let e=La(i.tokens,t,n);r+=t?e:`\x1b[3m${e}\x1b[23m`;break}case`del`:{let e=La(i.tokens,t,n);r+=t?e:`\x1b[9m${e}\x1b[29m`;break}case`link`:{let e=i,a=La(e.tokens,t,n);r+=t?a:Pa(a,e.href,n);break}case`image`:r+=i.text||i.href;break;case`br`:r+=`
12
+ `;break;default:r+=Fa(i.text??``)}return r}function Ra(e,t,n=``){let r=Ot(e,Math.max(1,t),{hard:!1,trim:!1}),i=r.length===0?[``]:r.split(`
13
+ `);return n?i.map((e,t)=>t===0?e:n+e):i}const za=/\b(const|let|var|function|return|if|else|for|while|class|interface|type|export|import|from|async|await|try|catch|throw|new|this|super|extends|implements|static|public|private|readonly|enum|switch|case|break|default|continue|do|in|of|instanceof|typeof|void|delete)\b/g,Ba=/(\b\d+\b)/g,Va=/("[^"]*"|'[^']*'|`[^`]*`)/g,Ha=/(\/\/.*)/g;function Ua(e){let t=[],n=(n,r)=>{n.lastIndex=0;let i;for(;(i=n.exec(e))!==null;)t.push([i.index,i.index+i[0].length,r])};if(n(Ba,L.warning),n(za,L.codeText),n(Va,L.success),n(Ha,L.inactive),t.length===0)return e;t.sort((e,t)=>e[0]-t[0]||t[1]-e[1]);let r=[];for(let e of t){if(r.length===0){r.push(e);continue}let t=r[r.length-1];e[0]<t[1]?r[r.length-1]=e:r.push(e)}let i=``,a=0;for(let[t,n,o]of r)t>a&&(i+=e.slice(a,t)),i+=Q(e.slice(t,n),o),a=n;return a<e.length&&(i+=e.slice(a)),i}function Wa(e,t,n,r){let i=wa(e,t),a=(i??e).split(`
14
+ `),o=String(a.length).length,s=[];t&&(s.push(Q(` ${t}`,r.codeLabel)),r.codeBlockDivider!==`none`&&s.push(Q(R.hr.repeat(Math.min(40,Math.max(3,n))),r.codeFenceDivider)));for(let e=0;e<a.length;e++){let t=Q(String(e+1).padStart(o)+` `,r.codeGutter),n=`\x1b]9;cw=${o+1}\x07`,c=i?a[e]??``:Ua(a[e]);s.push(n+t+(c||` `))}return s}function Ga(e,t){if(it(e)<=t)return[e];let n=Ot(e,Math.max(1,t),{hard:!0,trim:!1});return n?n.split(`
15
+ `):[``]}const Ka=(e,t)=>e+` `.repeat(Math.max(0,t-it(e)));function qa(e,t,n,r){if(e.length===0)return[];let i=[e,...t],a=Math.max(...i.map(e=>e.length)),o=[];for(let e=0;e<a;e++)o[e]=Math.max(6,...i.map(t=>it(t[e]??``)));let s=[];if(a*6+(a-1)*2>n){let o=Math.max(6,...e.map(e=>it(e))),c=Math.max(6,n-o-2);return(t.length>0?t:i).forEach((t,n)=>{n>0&&s.push(``);for(let n=0;n<a;n++){let i=Q(pn.bold(Ka(e[n]??``,o)),r.tableHeader),a=Ga(t[n]??``,c);s.push(i+` `.repeat(2)+Q(a[0]??``,r.tableBody));for(let e=1;e<a.length;e++)s.push(` `.repeat(o+2)+Q(a[e],r.tableBody))}}),s}let c=Math.max(a*6,n-(a-1)*2),l=o.reduce((e,t)=>e+t,0),u=l>c?o.map(e=>Math.max(6,Math.floor(c/l*e))):o,d=` `.repeat(2),f=(e,t)=>{let n=u.map((t,n)=>Ga(e[n]??``,t)),i=Math.max(...n.map(e=>e.length));for(let e=0;e<i;e++){let i=u.map((i,a)=>{let o=Ka(n[a][e]??``,i);return t?Q(pn.bold(o),r.tableHeader):Q(o,r.tableBody)});s.push(i.join(d))}};f(e,!0);let p=u.reduce((e,t)=>e+t,0)+(a-1)*2;s.push(Q(R.hr.repeat(p),r.tableDivider));for(let e of t)f(e,!1);return s}function Ja(e){let t=e=>e.replace(/\x1b\[[0-9;]*m/g,``).trim().length===0,n=0,r=e.length;for(;n<r&&t(e[n]);)n++;for(;r>n&&t(e[r-1]);)r--;return e.slice(n,r)}function Ya(e){let t=e.split(`
16
+ `),n=[],r=0;for(;r<t.length;){let e=/^\/\*\*/.test(t[r]),i=[];for(e&&(i.push(t[r]),r++);r<t.length&&/^ {0,3}\* /.test(t[r]);)i.push(t[r]),r++;i.length>0&&r<t.length&&/^ {0,3}\*\//.test(t[r])&&(i.push(t[r]),r++),i.length>=2?(n.push("```"),n.push(...i),n.push("```")):(e&&i.length,n.push(...i)),r<t.length&&!e&&i.length===0&&(n.push(t[r]),r++)}return n.join(`
17
+ `)}function Xa(e,t=80,n=Na()){let r=Math.max(1,t),i=Ya(e);return Ja(Za(_n.lexer(i),r,0,n))}function Za(e,t,n,r){let i=[];for(let a of e){if(a.type===`space`)continue;let e=Qa(a,t,n,r);e.length!==0&&(i.length>0&&i[i.length-1]!==``&&i.push(``),i.push(...e))}return i}function Qa(e,t,n,r){switch(e.type){case`heading`:{let n=e,i=La(n.tokens,!1,r),a=La(n.tokens,!0,r),o=Ra(n.depth===1?pn.bold(Q(i,r.heading1)):n.depth===2?pn.bold(Q(i,r.heading2)):n.depth<=4?pn.bold(i):Q(pn.dim(pn.bold(i)),r.headingWeak),t);if(n.depth!==1)return o;let s=Math.max(3,Math.min(t,it(a)));return[...o,Q(R.hr.repeat(s),r.h1Divider)]}case`paragraph`:return Ra(La(e.tokens,!1,r),t);case`text`:{let n=e;return Ra(n.tokens?La(n.tokens,!1,r):Fa(n.text),t)}case`code`:return Wa(e.text,e.lang??``,t,r);case`hr`:return[Q(R.hr.repeat(Math.min(40,t)),r.hr)];case`blockquote`:{let i=Za(e.tokens,Math.max(1,t-2),n,r),a=Q(pn.italic(R.quoteBar),r.quoteBar);return i.map(e=>e===``?a:`${a} ${Q(pn.italic(e),r.quoteText)}`)}case`list`:return to(e,t,n,r);case`table`:{let n=e;return qa(n.header.map(e=>La(e.tokens,!1,r)),n.rows.map(e=>e.map(e=>La(e.tokens,!1,r))),t,r)}case`html`:return Ra(Q(Fa(e.text).replace(/\n+$/,``),L.inactive),t);default:return[]}}function $a(e,t){return t.listMarkers[Math.min(e,t.listMarkers.length-1)]}function eo(e,t){return e===0?t.listMarkerPrimary:t.listMarkerMuted}function to(e,t,n,r){let i=[],a=typeof e.start==`number`&&e.start>0?e.start:1;return e.items.forEach((o,s)=>{e.loose&&s>0&&i[i.length-1]!==``&&i.push(``);let c=o.task?o.checked?R.checkboxOn:R.checkboxOff:e.ordered?`${a+s}.`:$a(n,r),l=o.task?o.checked?r.taskChecked:r.listMarkerMuted:eo(n,r),u=`${Q(c,l)} `,d=it(c)+1,f=` `.repeat(d),p=Za(o.tokens,Math.max(1,t-d),n+1,r),m=o.loose?p:p.filter(e=>e!==``);if(m.length===0){i.push(Q(c,l));return}m.forEach((e,t)=>{i.push(t===0?u+e:e===``?``:f+e)})}),i}function no(e,t){let{filled:n,empty:r}=o(e.chars),i=mt(e),a=i.cells.map(e=>e.filled?n:r).join(``),s=`${i.pct}%`,c=e.labelPosition??`suffix`,l=e.color?t(a,e.color):a;return c===`none`?l:c===`prefix`?`${s} ${l}`:`${l} ${s}`}function ro(e,t){let n=/(\s+|\w+|[^\s\w]+)/g,r=e.match(n)??[e],i=t.match(n)??[t],a=[],o=0,s=0;for(;o<r.length||s<i.length;)o<r.length&&s<i.length&&r[o]===i[s]?(a.push({text:r[o],removed:!1,added:!1}),o++,s++):o<r.length&&(s>=i.length||r[o]!==i[s])?(a.push({text:r[o],removed:!0,added:!1}),o++):s<i.length&&(a.push({text:i[s],removed:!1,added:!0}),s++);return a}function io(e,t){let n=Math.max(e.length,t.length);return n===0?0:(e.length+t.length-2*ao(e,t))/n}function ao(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;let r=0;for(;r<e.length-n-1&&r<t.length-n-1&&e[e.length-1-r]===t[t.length-1-r];)r++;return n+r}function oo(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.type===`remove`&&n+1<e.length&&e[n+1].type===`add`){let i=r,a=e[n+1];if(io(i.content,a.content)<=.4){let e=ro(i.content,a.content);t.push({...i,wordSegments:e.filter(e=>!e.added).map(e=>({text:e.text,changed:e.removed}))}),t.push({...a,wordSegments:e.filter(e=>!e.removed).map(e=>({text:e.text,changed:e.added}))})}else t.push(i),t.push(a);n+=2}else t.push(r),n++}return t}function so(e,t,n=12,r=2){let i=e.split(`
18
+ `),a=t.split(`
19
+ `),o=0;for(;o<i.length&&o<a.length&&i[o]===a[o];)o++;let s=i.length,c=a.length;for(;s>o&&c>o&&i[s-1]===a[c-1];)s--,c--;let l=[],u=c-s,d=Math.min(r,o),f=Math.min(r,i.length-s);for(let e=o-d;e<o;e++)l.push({type:`context`,content:i[e],oldLine:e+1,newLine:e+1});for(let e=o;e<s;e++)l.push({type:`remove`,content:i[e],oldLine:e+1});for(let e=o;e<c;e++)l.push({type:`add`,content:a[e],newLine:e+1});for(let e=s;e<s+f;e++)l.push({type:`context`,content:i[e],oldLine:e+1,newLine:e+1+u});return l.every(e=>e.type===`context`)?[]:[{header:``,lines:l.slice(0,n)}]}function co(e){let t=0,n=0;for(let r of e)for(let e of r.lines)e.type===`add`?t++:e.type===`remove`&&n++;return{added:t,removed:n}}const lo=`__compacting__`;function uo(e,t){if(t)return t;let n=/^mcp__(.+?)__(.+)$/.exec(e);return n?`${n[1]} / ${n[2]}`:e.split(/[_-]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}const fo=[`job`,`bash`,`subagent`];function po(e){return(e.type??`process`)===`agent-session`?(e.origin??`user`)===`user`?`job`:`subagent`:`bash`}function mo(e){return e.map((e,t)=>({t:e,i:t})).sort((e,t)=>{let n=fo.indexOf(po(e.t))-fo.indexOf(po(t.t));return n===0?e.i-t.i:n}).map(e=>e.t)}function ho(e){return(e.type??`process`)===`agent-session`?e.agentStatus===`running`||e.agentStatus===`ready`||e.agentStatus===`needs_input`:e.status===`running`}function go(e){if(e<60)return`${e}s`;let t=Math.floor(e/60),n=e%60;return n===0?`${t}m`:`${t}m ${n}s`}function _o(e,t){let n=e.filter(ho);if(n.length===0)return null;let r=n.reduce((e,t)=>e.startedAt<=t.startedAt?e:t),i=go(Math.max(0,Math.floor((t-r.startedAt)/1e3))),a=`${R.pointer} ${B.t(`bg.jobsLabel`,{n:n.length})} · ${i}`,o=e.filter(e=>e.type===`agent-session`&&e.agentStatus===`ready`).length,s=e.filter(e=>e.type===`agent-session`&&e.agentStatus===`needs_input`).length;return o>0&&(a+=` · ${B.t(`prompt.readySuffix`,{n:o})}`),s>0&&(a+=` · ${B.t(`bg.needInputSuffix`,{n:s})}`),a}function vo(e){let t=e.filter(e=>(e.type??`process`)===`process`&&e.status===`running`&&e.detectedService);if(t.length===0)return null;let n=t.length;return`${R.service} ${n} ${B.t(`service.countLabel`,{count:n})}`}function yo(e){return e<1e3?String(e):`${(e/1e3).toFixed(1)}k`}function bo(e){let t=[];return e.toolUseCount&&t.push(`${e.toolUseCount} ${e.toolUseCount===1?`tool`:`tools`}`),e.tokenCount&&t.push(`${yo(e.tokenCount)} tokens`),t.length?` · ${t.join(` · `)}`:``}function xo(e,t){if((e.type??`process`)===`agent-session`){let n=e.agentStatus??`running`;if(n===`running`){let n=go(Math.max(0,Math.floor((t-e.startedAt)/1e3)));if(e.stall===`stalled`||e.stall===`warn`){let t=e.idleMs===void 0?`?`:go(Math.floor(e.idleMs/1e3));return`${n} · ${R.warn} idle ${t}${e.blockedOn?` (${e.blockedOn})`:``}`}return`${n}${bo(e)}`}return n===`ready`?e.diffStat?`${B.t(`bg.metaReady`)} · ${e.diffStat}`:B.t(`bg.metaReady`):n===`needs_input`?B.t(`bg.metaNeedsInput`):B.t(`bg.agentStatusLabel`,{st:n})}if(e.status===`running`){let n=[];return e.port&&n.push(`:${e.port}`),n.push(go(Math.max(0,Math.floor((t-e.startedAt)/1e3)))),n.join(` `)}return e.status===`exited`?e.exitCode===void 0?B.t(`bg.metaExited`):B.t(`bg.metaExited`,{context:`code`,code:e.exitCode}):B.t(`bg.procStatusLabel`,{s:e.status})}function So(e){let t=e.agentStatus;return t===`ready`||t===`applied`?`done`:t===`failed`?`error`:t===`canceled`?`killed`:t===`running`||t===`needs_input`?`running`:e.status===`exited`?`done`:e.status===`failed`?`error`:e.status===`killed`?`killed`:`running`}function Co(e){switch(e){case`done`:return{agentStatus:`applied`,status:`exited`};case`error`:return{agentStatus:`failed`,status:`failed`};case`killed`:return{agentStatus:`canceled`,status:`killed`};default:return{agentStatus:`running`,status:`running`}}}function wo(e){return{turnIndex:e.turnIndex,toolUseCount:e.toolUseCount,filesEdited:e.filesEdited,tokenCount:e.tokenCount,lastActivity:e.lastActivity,stall:e.stall,idleMs:e.idleMs,blockedOn:e.blockedOn,abortable:e.abortable,prompt:e.prompt,model:e.model,modelDecidedBy:e.modelDecidedBy}}function To(e){return e===`awaiting_gate`?`needs_input`:e===`done`?`applied`:e===`error`||e===`aborted`?`failed`:`running`}function Eo(e){return{id:e.id,command:`@${e.agentName}`,type:`agent-session`,origin:e.origin,status:`running`,agentStatus:To(e.status),startedAt:e.startedAt,...wo(e)}}function Do(e){let t=e/1e3;return t<60?`${t.toFixed(1)}s`:go(Math.floor(t))}function Oo(e,t){return e.map(e=>{let n=Do((e.endedAt??t)-e.startedAt),r=e.tools&&e.tools.length>0?e.tools.length<=3?e.tools.join(`, `):`${e.tools.slice(0,3).join(`, `)} +${e.tools.length-3}`:`${e.toolCount} ${e.toolCount===1?`tool`:`tools`}`;return e.endedAt===void 0?`▸ turn ${e.index} … (${r}, ${n})`:` turn ${e.index} ${R.check} (${r}, ${n})`})}function ko(e,t){if((e.type??`process`)!==`agent-session`||e.turnIndex===void 0&&e.toolUseCount===void 0&&e.tokenCount===void 0&&e.lastActivity===void 0&&e.stall===void 0)return null;let n=go(Math.max(0,Math.floor((t-e.startedAt)/1e3))),r=e.stall===`stalled`||e.stall===`warn`,i=e.idleMs===void 0?`?`:go(Math.floor(e.idleMs/1e3)),a=[{label:`activity`,value:e.lastActivity??`-`},{label:`blocked`,value:e.blockedOn??`-`,warn:r},{label:`last event`,value:r?`idle ${i}`:`live`,warn:r},{label:`tokens`,value:`${yo(e.tokenCount??0)} out · ${e.toolUseCount??0} tools · ${n}`},{label:`abortable`,value:e.abortable===!1?`NO (drops signal)`:`yes`,warn:e.abortable===!1}];return{header:`${e.command} · turn ${e.turnIndex??`-`} · ${e.agentStatus??`running`}`,rows:a}}function Ao(e,t){let n=ko(e,t);return n?[n.header,...n.rows.map(e=>` ${e.warn?`! `:` `}${e.label.padEnd(11)} ${e.value}`)]:[]}function jo(e,t,n){let r=Math.max(1,Math.floor(t));if(e<=r)return{start:0,end:e,above:0,below:0};let i=e-r,a=e-Math.min(Math.max(0,Math.floor(n)),i),o=a-r;return{start:o,end:a,above:o,below:e-a}}const Mo=new Map;let No=null,Po=null,Fo=null,Io=null,Lo=null,Ro=null;function zo(){No=null,Po=null,Fo=null,Lo=null,Io=null,Ro=null}function Bo(){if(No===null){let e=[];for(let t of Mo.values())t.renderers&&e.push(...t.renderers);No=e}if(Po===null){let e=[];for(let t of Mo.values())t.statusItems&&e.push(...t.statusItems);Po=e}if(Fo===null){let e=[];for(let t of Mo.values())t.panels&&e.push(...t.panels);Fo=e}if(Lo===null){let e=new Map;for(let t of Mo.values())if(t.a2uiComponents)for(let n of t.a2uiComponents)e.has(n.type)||e.set(n.type,n.render);Lo=e}if(Io===null){let e=[];for(let t of Mo.values())t.statusWidgets&&e.push(...t.statusWidgets);Io=e}if(Ro===null){let e=[];for(let t of Mo.values())t.fileViewers&&e.push(...t.fileViewers);Ro=e}}function Vo(e,t){Mo.set(e,t),zo()}function Ho(e){Mo.delete(e),zo()}function Uo(){Mo.clear(),zo()}function Wo(){return Mo}const Go=new Set([`cli-commands`,`cli-status`,`cli`]);function Ko(e,t){let n=[];for(let[r,i]of t)Go.has(i.pluginId)||e.has(r)||n.push(r);return n}function qo(){return Bo(),No??[]}function Jo(){return Bo(),Po??[]}function Yo(){return Bo(),Lo??new Map}function Xo(){return Bo(),Io??[]}function Zo(){return Bo(),Ro??[]}function Qo(e){Vo(`cli`,{pluginId:`cli`,renderers:[...e]})}function $o(){Ho(`cli`)}function es(e,t){let n=t;if(!n||typeof n!=`object`||e.role!=null&&n.role!==e.role||e.toolName!=null&&(n.name??n.toolName)!==e.toolName)return!1;if(e.contentType!=null){let t=n.content;if(!(Array.isArray(t)&&t.some(t=>t&&typeof t==`object`&&t.type===e.contentType)))return!1}return!0}function ts(e,t){for(let n of qo())if(es(n.matcher,e))try{let r=n.render(e,t);if(Array.isArray(r)&&r.length>0)return r}catch{}return null}function ns({innerWidth:e,title:t,paint:n=e=>e}){if(!t)return n(`┌${`─`.repeat(e)}┐`);let r=ae(t,e-4),i=it(r),a=Math.max(0,e-i-3);return n(`┌─ ${r} ─${`─`.repeat(a)}┐`)}function rs({innerWidth:e,paint:t=e=>e}){return t(`└${`─`.repeat(e)}┘`)}function is(e,t=e=>e){return t(`│ `)+e}function as(e){switch(e){case`accent`:return L.accent;case`green`:return L.success;case`amber`:return L.warning;case`red`:return L.error;case`gray`:return L.inactive;default:return`#888888`}}function os(e,t){let n=as(t);if(n.startsWith(`#`))return pn.hex(n)(e);let r=pn[n];return typeof r==`function`?r(e):e}const ss=e=>os(e,`accent`),cs=e=>os(e,`gray`);function ls(e){let t=new Map;for(let n of e)t.set(n.id,n);let n=new Set;for(let t of e){for(let e of t.children??[])n.add(e);for(let e of t.items??[])n.add(e)}let r=e.map(e=>e.id).filter(e=>!n.has(e));return r.length===0&&e.length>0&&r.push(e[0].id),{byId:t,roots:r}}function us(e,t,n,r,i,a){if(i.has(e.id))return[];switch(i.add(e.id),e.type){case`Text`:return fs(e);case`Card`:return ps(e,t,n,r,i,a);case`List`:return ms(e,t,n,r,i,a);case`Progress`:return hs(e,n);case`Chip`:return gs(e);case`Button`:return vs(e,a);case`Form`:return Cs(e,a);default:return ds(e,t,n,r,i,a)}}function ds(e,t,n,r,i,a){let o=Yo().get(e.type);if(!o)return ys(e);let s=e=>{if(i.has(e))return[];let o=t.byId.get(e);return o?us(o,t,n,r+1,i,a):[]};try{let t=o(e,n,s);return!Array.isArray(t)||!t.every(e=>typeof e==`string`)?ys(e):t}catch{return ys(e)}}function fs(e){let t=e.text??``;return t?t.split(`
20
+ `):[]}function ps(e,t,n,r,i,a){let o=Math.max(1,n-4),s=[];s.push(ns({innerWidth:o,title:e.title,paint:ss}));for(let n of e.children??[]){let e=t.byId.get(n);if(!e)continue;let c=us(e,t,o,r+1,i,a);for(let e of c)s.push(is(e,cs))}return s.push(rs({innerWidth:o,paint:ss})),s}function ms(e,t,n,r,i,a){let o=[],s=e.items??[];for(let c=0;c<s.length;c++){let l=t.byId.get(s[c]);if(!l)continue;let u=e.ordered?` ${c+1}. `:` • `,d=us(l,t,n-u.length,r+1,i,a);if(d.length>0){o.push(u+d[0]);for(let e=1;e<d.length;e++)o.push(` `+d[e])}}return o}function hs(e,t){let n=Math.min(20,Math.max(4,t-20)),r=Math.max(0,Math.min(100,e.value??0)),i=e.max??100,a=i>0?Math.round(r/i*100):0,o=e.label==null?``:`${e.label} `,s=a>=100?`green`:a>0?`accent`:`gray`,c=no({percent:a,width:n,chars:`block`,color:s},os);return[os(o,s)+c]}function gs(e){let t=e.color??`accent`;return[os(`[${e.text??``}]`,t)]}let _s=0;function vs(e,t){_s++;let n=e.text??e.action??e.id,r=String(_s),i=`${n}`;return t.push({key:r,label:i,componentId:e.id,action:e.action??`click`}),[ss(`[${r}] [ ${i} ]`)]}function ys(e){return[cs(e.text??`[${e.type}:${e.id}]`)]}function bs(e,t=80,n=0){if(!Array.isArray(e)||e.length===0)return{lines:[],buttons:[]};try{_s=n,Ss=0;let r=ls(e),i=[],a=[],o=new Set;for(let e of r.roots){let n=r.byId.get(e);n&&i.push(...us(n,r,t,0,o,a))}return{lines:i,buttons:a}}catch{return{lines:[],buttons:[]}}}function xs(e){if(!Array.isArray(e)||e.length===0)return[];try{let t=ls(e),n=[],r=0,i=new Set,a=e=>{if(!i.has(e.id)){i.add(e.id),e.type===`Button`&&(r++,n.push({key:String(r),label:e.text??e.action??e.id,componentId:e.id,action:e.action??`click`}));for(let n of e.children??[]){let e=t.byId.get(n);e&&a(e)}for(let n of e.items??[]){let e=t.byId.get(n);e&&a(e)}}};for(let e of t.roots){let n=t.byId.get(e);n&&a(n)}return n}catch{return[]}}let Ss=0;function Cs(e,t){let n=e.fields??[],r=[],i=e.formTitle??`表单`,a=Math.max(it(i)+4,30);r.push(ns({innerWidth:a,title:i,paint:ss}));for(let e of n){let t=e.required?` (必填)`:``;switch(e.type){case`text`:r.push(is(`${e.label}: ${e.defaultValue?String(e.defaultValue):`___________`}${t}`,cs));break;case`select`:{let n=e.options??[],i=e.defaultValue,a=n.find(e=>e.id===i)?.label??n[0]?.label??``;r.push(is(`${e.label}: ${a}${t}`,cs));break}case`toggle`:r.push(is(`${e.label}: ${e.defaultValue===!0?R.toggleOn:R.toggleOff}${t}`,cs));break;default:r.push(is(`${e.label}: ?${t}`,cs))}}Ss++;let o=e.action??`submit`;return t.push({key:String(Ss),label:`填写表单`,componentId:e.id,action:o}),r.push(is(`[${Ss}] 填写表单`,ss)),r.push(rs({innerWidth:a,paint:ss})),r}function ws(e){if(!Array.isArray(e)||e.length===0)return[];try{let t=e,n=[],r=xs(e).length;for(let e of t)e.type===`Form`&&(r++,n.push({key:String(r),label:`表单: ${e.formTitle??`表单`}`,componentId:e.id,action:e.action??`submit`}));return n}catch{return[]}}function Ts(e){return e.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,``).replace(/\x1b\[[\d;?]*[@-~]/g,``).replace(/\x1b\[[\d;?]*(?![\d;@-~])/g,``).replace(/(?:3[89]|4[0-9]);2;\d{1,3};\d{1,3};\d{1,3}m/g,``).replace(/(?:3[89]|4[0-9]);5;\d{1,3}m/g,``).replace(/(?:^|(?<=[\s;m]))(?:\d{1,3}(?:;\d{1,3})+|;\d{1,3})m/gi,``)}function Es(e){switch(e){case`file`:return L.suggestion;case`agent`:return L.accent;case`skill`:case`mcp`:case`plugin`:return L.special;case`person`:return L.success;default:return L.inactive}}function Ds(e){we.lastIndex=0;let t=``,n=0,r;for(;(r=we.exec(e))!==null;)r.index>n&&(t+=e.slice(n,r.index)),t+=Q(r[0],Es(Ae(r[0]))),n=r.index+r[0].length;return n<e.length&&(t+=e.slice(n)),t}const Os=(e,t=F.section)=>e.map(e=>{let n=/^\x1b]9;cw=(\d+)\x07/.exec(e);return n?`\x1b]9;cw=${parseInt(n[1],10)+t}\x07`+` `.repeat(t)+e.slice(n[0].length):` `.repeat(t)+e});function ks(e,t){let n=e>0?Math.max(0,Math.min(1,t/e)):0,r=Math.round(n*100),i=n>0?Math.max(1,Math.round(n*10)):0;return no({percent:r,width:10,segments:i>0?[{key:`ratio`,width:i}]:[],chars:`dot`,color:L.inactive},Q)}function As(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}`} ${`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}`}const js=/^[\s]*(❌|✗|⛔|🔴|🚫|❎)\s*/u,Ms=/^[\s]*(✅|✓|🟢|✔️?|☑️?)\s*/u;function Ns(e){return js.test(e)?{cleaned:e.replace(js,``)}:Ms.test(e)?{cleaned:e.replace(Ms,``)}:{cleaned:e}}function Ps(e,t){return e.length<=t?e:[...e.slice(0,t),B.t(`common.moreLinesLabel`,{n:e.length-t})]}function Fs(e,t){return Ps(Ts(e).split(`
21
+ `),t).map(e=>Q(e,L.toolText))}function Is(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function Ls(e){let t=process.env.HOME,n=t?e.replace(t,`~`):e,r=n.split(`/`);return r.length>3?`…/${r.slice(-2).join(`/`)}`:n}const Rs=new Set([`edit`,`Edit`,`str_replace`]),zs=new Set([`write`,`Write`,`create`]),Bs=new Set([`read`,`Read`,`view`,`cat`,`open`]),Vs=new Set([`write_todos`,`TodoWrite`]),Hs=new Set([...mn,`Task`]);function Us({name:e,argPreview:t,added:n,removed:r,isError:i,status:a}){let o=a??(i?`error`:`ok`),s=o===`error`?R.cross:o===`warn`?R.warn:R.check,c=o===`error`?L.error:o===`warn`?L.warning:L.success,l=Q(s+` `,c)+Q(Is(e),L.toolText),u=t!=null||n!=null||r!=null;return u&&(l+=Q(`(`,L.toolText)),t!=null&&(l+=Q(t,L.toolText)),n!=null&&(l+=Q((t==null?``:` `)+`+`+n,L.diffAdd)),r!=null&&(l+=Q(` -`+r,L.diffRemove)),u&&(l+=Q(`)`,L.toolText)),l}const Ws=()=>process.env.OTTO_TUI_DIFF_BG!==`0`;function Gs(e,t){if(!t||!Ws())return e;try{return pn.bgHex(t)(e)}catch{return e}}const Ks={ts:`typescript`,tsx:`typescript`,mts:`typescript`,cts:`typescript`,js:`javascript`,jsx:`javascript`,mjs:`javascript`,cjs:`javascript`,py:`python`,rb:`ruby`,go:`go`,rs:`rust`,java:`java`,kt:`kotlin`,c:`c`,h:`c`,cc:`cpp`,cpp:`cpp`,hpp:`cpp`,cs:`csharp`,swift:`swift`,php:`php`,sh:`bash`,bash:`bash`,zsh:`bash`,json:`json`,yaml:`yaml`,yml:`yaml`,toml:`ini`,ini:`ini`,xml:`xml`,html:`xml`,css:`css`,scss:`scss`,sql:`sql`,md:`markdown`,dockerfile:`dockerfile`,lua:`lua`};function qs(e){if(!e)return``;let t=e.split(`/`).pop()??``;return t.toLowerCase()===`dockerfile`?`dockerfile`:Ks[t.includes(`.`)?t.split(`.`).pop().toLowerCase():``]??``}function Js(e,t,n,r=2e3){let i=qs(t),a=e.split(`
22
+ `),o=((n&&i!==``&&a.length<=r?wa(e,i):null)??e).split(`
23
+ `),s=Math.max(2,String(o.length).length);return o.map((e,t)=>Ys(s+1)+Q(String(t+1).padStart(s)+` `,L.inactive)+(e||` `))}const Ys=e=>`\x1b]9;cw=${e}\x07`;function Xs(e,t={}){let n=e.reduce((e,t)=>e+t.lines.length,0)>200?void 0:t.highlight,r=t.lang??``,i=0;for(let t of e)for(let e of t.lines){let t=e.type===`remove`?e.oldLine:e.newLine??e.oldLine;t!=null&&t>i&&(i=t)}let a=Math.max(2,String(i).length),o=[];return e.forEach((e,t)=>{t>0&&o.push(Q(`⋮`.padStart(a),L.inactive));for(let t of oo(e.lines)){let e=t.type===`remove`?t.oldLine:t.newLine??t.oldLine,i=String(e??``).padStart(a),s=t.type===`add`?`+`:t.type===`remove`?`-`:` `,c=t.type===`add`?L.diffAdd:t.type===`remove`?L.diffRemove:void 0,l=c??L.inactive,u=t.type===`add`?L.diffAddBg:t.type===`remove`?L.diffRemoveBg:``,d=n&&r?n(t.content,r):null,f;if(d!=null)f=Q(i+` `,l)+Q(s+` `,c)+d;else if(t.wordSegments&&(t.type===`add`||t.type===`remove`)){let e=t.wordSegments.map(e=>Q(e.changed?pn.bold(e.text):e.text,c)).join(``);f=Q(i+` `,l)+Q(s+` `,c)+e}else f=Q(i+` `,l)+Q(s+` `+t.content,c);o.push(Ys(a+2)+Gs(f,u))}}),o}function Zs(e){let t=String(e.name??``),n=e.args==null?void 0:String(e.args),r=e.argsObj==null?{}:e.argsObj,i=e.result==null?void 0:String(e.result),a=e.isError==null?void 0:!!e.isError;if(Rs.has(t)&&typeof r.oldContent==`string`&&typeof r.newContent==`string`){let e=typeof r.path==`string`?r.path:``,t=e?Ls(e):``,n=so(r.oldContent,r.newContent),{added:i,removed:o}=co(n),s={highlight:wa,lang:qs(e)};return[Us({name:B.t(`tool.edit`),argPreview:t,added:i,removed:o,isError:a}),...Os(Xs(n,s))]}if(zs.has(t)&&typeof r.content==`string`){let e=typeof r.path==`string`?r.path:``,t=e?Ls(e):``,n=r.content.split(`
24
+ `),i=[{header:``,lines:n.map((e,t)=>({type:`add`,content:e,newLine:t+1})).slice(0,12)}],o={highlight:wa,lang:qs(e)};return[Us({name:B.t(`tool.write`),argPreview:t,added:n.length,isError:a}),...Os(Xs(i,o))]}if(Bs.has(t)){let e=typeof r.path==`string`?r.path:n?n.trim():``;return[Us({name:B.t(`tool.read`),argPreview:e,isError:a})]}if(Vs.has(t)&&Array.isArray(r.todos)){let e=r.todos,t=r.title;return[Us({name:t??B.t(`tool.tasks`),argPreview:B.t(`welcome.itemCountLabel`,{count:e.length}),isError:a}),...Os(e.map(e=>{let t=e.status===`done`?R.todoDone:e.status===`in_progress`?R.todoActive:R.todoPending,n=e.status===`done`?L.success:e.status===`in_progress`?L.accent:L.inactive,r=e.status===`done`||e.status===`skipped`,i=r?pn.strikethrough(e.title??``):e.title??``;return Q(t+` `,n)+Q(i,r?L.inactive:L.text)}))]}if(Hs.has(t)){let e=r.subagent??r.agent??r.category??r.team,t=typeof r.prompt==`string`?r.prompt.replace(/\n/g,` `):``,n=Q((a?R.cross:R.check)+` `,a?L.error:L.success)+Q(B.t(`tool.subagent`),L.toolText)+(e?Q(`(${e})`,L.special):``),o=[];return t&&o.push(...Os([Q(t,L.toolText)])),i&&o.push(...Os(Fs(i,5))),[n,...o]}return[Us({name:uo(t),argPreview:n?n.replace(/\n/g,` `):void 0,isError:a}),...i?Os(Fs(i,5)):[]]}function Qs(e){let t=[];for(let n of e){let e=n.function,r=e?.arguments?String(e.arguments).replace(/\n/g,` `):void 0;t.push(Us({name:e?.name?uo(e.name):B.t(`tool.unknown`),argPreview:r}))}return t}function $s(e,t=80){let n=ts(e,t);if(n)return n;let r=e,i=r.role??`unknown`,a=r.content,o=Array.isArray(a)?a:[],s=Array.isArray(a)?o.filter(e=>e.type===`text`).map(e=>Ts(String(e.text??``))).join(`
25
+ `):Ts(String(a??``)),c=r.tool_calls,l=Array.isArray(c)?c:[],u=Math.max(1,t-2),d=e=>Xa(e,u),f=0,p=[];for(let e of o){if(e.type!==`a2ui`)continue;let t=bs(e.components,u,f);p.push(...t.lines),f+=t.buttons.length}if(i===`summary`){let e=r.status===`error`?R.cross:r.status===`interrupted`?`⏹`:r.status===`incomplete`?`⏸`:R.check,t=r.status===`error`?L.error:r.status===`interrupted`||r.status===`incomplete`?L.warning:L.success,n=r.status===`error`?B.t(`status.failed`):r.status===`interrupted`?B.t(`status.interrupted`):r.status===`incomplete`?B.t(`status.stopped`):B.t(`status.done`),i=Math.floor(Number(r.elapsedMs??0)/1e3),a=i<60?`${i}s`:`${Math.floor(i/60)}m ${i%60}s`,o=Q(`${e} ${n}`,t)+Q(` · ${B.t(`tool.countLabel`,{count:Number(r.toolCount??0)})} · ${a}`,L.inactive),s=r.cacheHitRatio,c=typeof s==`number`?`(${Math.round(s*100)}%)`:``;if(r.tokensUsed==null?c&&(o+=Q(` · cache${c}`,L.inactive)):o+=Q(` · ${yo(Number(r.tokensUsed))} tokens${c}`,L.inactive),r.status===`incomplete`&&r.tasksTotal!=null){let e=Number(r.tasksDone??0),t=Number(r.tasksTotal),n=Number.isFinite(e)?e:0,i=Number.isFinite(t)?t:0,a=Math.max(0,i-n);o+=Q(` · ${B.t(`task.leftLabel`,{done:n,total:i,left:a})}`,L.warning)}if(r.model!=null){let e=r.effort==null?``:String(r.effort),t=e?e.toLowerCase()===`xhigh`?`XHigh`:e.charAt(0).toUpperCase()+e.slice(1):``,n=t?`${String(r.model)}·${t}`:String(r.model);o+=Q(` · ${n}`,L.inactive)}return r.completedAt!=null&&(o+=Q(` · ${As(Number(r.completedAt))}`,L.inactive)),p.length>0?[o,``,...p]:[o]}if(i===`assistant_stream`){let{cleaned:e}=Ns(Ts(String(r.text??``)));if(!e)return[];let t=r.lead===!0;return d(e).map((e,n)=>t&&n===0?`${Q(R.bullet,L.replyPrefix)} ${e}`:Ts(e).trim()===``?``:` ${e}`)}if(i===`tool`){let e=Ja(Zs(r));return p.length>0?[...e,``,...p]:e}if(i===`system`){let e=[Q(s,L.inactive)];return p.length>0?[...e,``,...p]:e}if(i===`panel`){let e=r.language==null?``:String(r.language),t=r.code==null?``:String(r.code),n=r.title==null?``:String(r.title),i="```"+e+`
26
+ `+t+"\n```",a=[];return n&&a.push(Q(pn.bold(n),L.accent)),a.push(...d(i)),p.length>0?[...a,``,...p]:a}if(i===`user`){let e=s.split(`
27
+ `),t=r.streaming===!0,n=e.map((e,n)=>{let r=Ds(e),i=t?pn.dim(r):r;return n===0?Q(`${R.userPrompt} `,L.inactive)+i:` `+i});return p.length>0?[...n,``,...p]:n}if(i===`tool_result`||r.type===`tool_result`){let e=Ps(s.split(`
28
+ `),5).map((e,t)=>Q((t===0?`${R.toolResult} `:` `)+e,L.inactive));return p.length>0?[...e,``,...p]:e}if(i===`command_echo`||r.type===`command_echo`){let e=r.command==null?``:String(r.command),t=r.status===`warn`||r.status===`error`?r.status:`ok`,n=t===`error`?R.cross:t===`warn`?R.warn:R.check,i=t===`error`?L.error:t===`warn`?L.warning:L.success,a=[Q(`${R.commandPrompt} `,L.inactive)+Q(e,L.inactive)],o=r.summary==null?void 0:String(r.summary);o!=null&&a.push(...Os([Q(`${n} `,i)+Q(o,L.toolText)]));let s=r.detail==null?void 0:String(r.detail);return s&&a.push(...Os(Ts(s).split(`
29
+ `).map(e=>Q(e,L.toolText)))),a}if(i===`compact_boundary`||r.type===`compact_boundary`){let e=r.before==null?void 0:Number(r.before),t=r.after==null?void 0:Number(r.after);if(!(e!=null&&t!=null&&!Number.isNaN(e)&&!Number.isNaN(t)))return[Us({name:B.t(`tool.compact`),argPreview:B.t(`compact.ed`)})];let n=`${e} → ${t} ${ks(e,t)}`;return[Us({name:B.t(`tool.compact`),argPreview:n})]}if(i===`prune_boundary`||r.type===`prune_boundary`)return[Us({name:B.t(`tool.prune`),argPreview:B.t(`compact.pruned`)})];if(i===`history_capped`||r.type===`history_capped`){let e=r.removedCount==null?0:Number(r.removedCount),t=typeof r.trigger==`string`?r.trigger:`count`;if(r.lossy===!0)return[Us({name:B.t(`tool.history`),argPreview:B.t(`history.cappedLossy`,{count:e}),status:`warn`})];let n=t===`bytes`?B.t(`history.cappedBytes`,{count:e}):t===`memory-pressure`?B.t(`history.cappedMemoryPressure`,{count:e}):B.t(`history.capped`,{count:e});return[Us({name:B.t(`tool.history`),argPreview:n})]}if(i===`write_lease_denied`||r.type===`write_lease_denied`)return[Us({name:B.t(`tool.session`),argPreview:B.t(`lease.denied`),status:`warn`})];if(i===`write_lease_restored`||r.type===`write_lease_restored`)return[Us({name:B.t(`tool.session`),argPreview:B.t(`lease.restored`)})];if(i===`run_paused`||r.type===`run_paused`){let e=r.toolCount==null?void 0:Number(r.toolCount),t=e==null?B.t(`run.messageBody`):B.t(`run.messageBody`,{context:`n`,n:e});return[Us({name:B.t(`tool.run`),argPreview:t}),...Os([Q(B.t(`run.messageFooter`),L.inactive)])]}if(i===`run_resumed`||r.type===`run_resumed`)return[Us({name:B.t(`tool.run`),argPreview:B.t(`run.resumedMessageBody`)})];if(i===`run_pause_cancelled`||r.type===`run_pause_cancelled`)return[Us({name:B.t(`tool.run`),argPreview:B.t(`run.pauseCancelledMessageBody`)})];if(i===`tool_completion`||r.type===`tool_completion`){let e=r.isError===!0;return[Q(`${R.toolResult} ${s}`,e?L.error:L.inactive)]}if(i===`model_switch`||r.type===`model_switch`){let e=r.label==null?``:String(r.label);return[Us({name:B.t(`tool.model`),argPreview:B.t(`model.switchedTo`,{label:e})})]}if(i===`effort_switch`||r.type===`effort_switch`){let e=r.label==null?``:String(r.label);return[Us({name:B.t(`tool.effort`),argPreview:B.t(`model.switchedTo`,{label:e})})]}if(i===`model_fallback`||r.type===`model_fallback`){let e=r.configured==null?``:String(r.configured),t=r.active==null?``:String(r.active);return[Us({name:B.t(`tool.model`),argPreview:`${B.t(`model.title`)}: ${e} → ${t}`,status:`warn`}),...Os([Q(B.t(`model.hint`),L.inactive)])]}let m=Array.isArray(a)&&o.some(e=>e.type===`thinking`);if(i===`assistant`&&m){let e=o.filter(e=>e.type===`thinking`).map(e=>String(e.thinking??``)).join(`
30
+ `).split(`
31
+ `),t=e.slice(0,30),n=e.length-t.length,r=[];if(r.push(Q(R.thinking,L.toolText)+Q(` `+B.t(`common.thoughtLines`,{n:e.length}),L.toolText)),r.push(...Os(t.map(e=>Q(pn.italic(e),L.toolText)))),n>0&&r.push(...Os([Q(B.t(`common.moreLinesLabel`,{n}),L.toolText)])),s){let{cleaned:e}=Ns(s);r.push(``,...Os(d(e)))}return l.length>0&&r.push(``,...Qs(l)),p.length>0?[...Ja(r),``,...p]:Ja(r)}let{cleaned:h}=Ns(s),g=[];return s&&g.push(...Os(d(h))),l.length>0&&(g.length&&g.push(``),g.push(...Qs(l))),p.length>0?[...Ja(g),``,...p]:Ja(g)}const ec=[`Aa`,`Ab`,`.*`],tc=[`input`,...ec],nc={input:``,Aa:`Aa`,Ab:`Ab|`,".*":`.*`};function rc({lines:e,rows:t,header:n,onDismiss:r,onKey:i,dismissOnEsc:a=!0,internalChromeRows:o=9,initialScroll:s=`bottom`,emptyMessage:c,active:l=!0,contentKey:u,columns:d=80,wrapMode:p=`pre-wrap`,extraHints:m,findActive:g,onFindModeChange:_,scrollStore:v}){let b=h(),x=aa(),S=v??x,[C,w]=K(s===`bottom`?2**53-1:0),[D,te]=K(!1),k=g??D,re=e=>{let t=typeof e==`function`?e(k):e;te(t),_?.(t)},[ie,ae]=K(``),oe=G(null),se=Ge(B.t(`find.inputLabel`))+1,[M,N]=K(0),[ce,P]=K(!1),[le,ue]=K(!1),[de,pe]=K(!1),[me,he]=K(`input`);De({active:k&&me===`input`,containerRef:oe,text:ie,inline:{column:se+Ge(ie),lineOffset:0},deleteKeyAt:0});let F=Math.max(10,d-fe.contentInset),ge=W(()=>p===`truncate`?e:Ce(e,F),[e,F,p]);U(()=>{if(S)return S.registerWheel(e=>{l&&w(n=>na(n,e,ge.length,t))})},[S,l,t,ge.length]);let _e=W(()=>({caseSensitive:ce,wholeWord:le,regex:de}),[ce,le,de]),ve=W(()=>{if(!k||!ie)return{byPhys:new Map,count:0,flat:[]};let e=new Map,t=[];for(let n=0;n<ge.length;n++){let r=ha(Ts(ge[n]),ie,_e);if(r.length>0){e.set(n,r);for(let e of r)t.push({physIdx:n,range:e})}}return{byPhys:e,count:t.length,flat:t}},[k,ie,_e,ge]);U(()=>{N(0)},[ie,_e]);let ye=u??`${e.length}:${e[0]??``}:${e[e.length-1]??``}`,be=G(ye);U(()=>{be.current!==ye&&(w(s===`bottom`?2**53-1:0),be.current=ye)},[ye,s]);let xe=o+(k?2:0),Se=Math.max(3,ee(ge.length+xe,t)-xe),we=ea(ge.length,Se,C),I=Math.max(0,ge.length-Se),L=we.offset,Te=ge.slice(we.start,we.end),Ee=A(`f`),Oe=At(e=>{he(t=>tc[(tc.indexOf(t)+e+tc.length)%tc.length])},[]),ke=At(e=>{switch(e){case`Aa`:P(e=>!e);break;case`Ab`:ue(e=>!e);break;case`.*`:pe(e=>!e);break;default:break}},[]);j(`file-content-viewer`,(e,t)=>{if(!l)return!1;if(t.escape)return k?ie?(ae(``),N(0),!0):(re(!1),!0):(a&&r(),!0);if(t.ctrl&&e===`f`)return re(e=>!e),k&&(ae(``),N(0),P(!1),ue(!1),pe(!1),he(`input`)),!0;if(k){if(t.tab)return Oe(t.shift?-1:1),!0;let n=E(t);if(n!==0)return Oe(n),!0;if(t.upArrow||t.downArrow)return ve.count>0&&N(e=>t.upArrow?(e-1+ve.count)%ve.count:(e+1)%ve.count),!0;if(t.return)return me===`input`?ve.count>0&&N(e=>(e+1)%ve.count):ke(me),!0;if(e===` `)return me===`input`?(ae(e=>e+` `),!0):(ke(me),!0);if(t.backspace||t.delete)return ae(e=>e.slice(0,-1)),!0;if(e&&e.length>1&&!t.ctrl&&!t.meta&&!t.return&&!t.escape&&!t.backspace&&!t.delete&&!t.tab){let t=Ze(e);return t&&(me!==`input`&&he(`input`),ae(e=>e+t)),!0}return e&&e.length===1&&e>=` `&&!t.ctrl&&!t.meta?(me!==`input`&&he(`input`),ae(t=>t+e),!0):!0}if(!i?.(e,t))return t.upArrow?(w(e=>Math.max(0,e-1)),!0):t.downArrow?(w(e=>Math.min(I,e+1)),!0):t.pageUp?(w(e=>Math.max(0,e-Se)),!0):t.pageDown?(w(e=>Math.min(I,e+Se)),!0):e===`g`?(w(0),!0):e===`G`?(w(I),!0):!1}),U(()=>{if(!k||ve.count===0)return;let e=ve.flat[M];if(!e)return;let t=e.physIdx;t<L?w(t):t>=L+Se&&w(t-Se+1)},[M,k]);let Ae=ve.flat[M]??null,je=e=>{let t=e===`Aa`&&ce||e===`Ab`&&le||e===`.*`&&de,n=me===e,r=nc[e];return n&&t?J(X,{inverse:!0,bold:!0,color:b.selection,children:[` `,r,` `]},e):n?J(X,{inverse:!0,children:[` `,r,` `]},e):t?J(X,{children:[` `,r,` `]},e):J(X,{dimColor:!0,children:[` `,r,` `]},e)};return J(y,{header:n,footer:k?q(O,{items:[...me===`input`?[[`${T.up}${T.down}`,`match`]]:[],[T.enter,me===`input`?`next`:`toggle`],[T.tab,`mode`],[T.esc,ie?`clear`:`close`],[Ee,`find`]]}):q(O,{items:[...m??[],[`${T.up}${T.down}/g/G`,B.t(`hint.scroll`)],[T.esc,B.t(`hint.close`)],[Ee,B.t(`hint.find`)]]}),children:[q(X,{children:` `}),k&&J(Mt,{children:[J(Y,{ref:oe,children:[J(X,{children:[B.t(`find.inputLabel`),` `]}),me===`input`?q(X,{inverse:!0,children:ie?ie+` `:` `}):q(X,{children:ie?ie+` `:` `}),ec.map(je),ve.count>0?J(X,{children:[` `,B.t(`find.matchCount`,{current:M+1,total:ve.count})]}):ie?q(X,{dimColor:!0,children:` 0/0`}):null]}),q(X,{children:` `})]}),e.length===0?q(X,{color:b.inactive,dimColor:!0,children:c??B.t(`common.noContentAvailable`)}):J(Y,{flexDirection:`row`,children:[q(Y,{flexDirection:`column`,flexGrow:1,children:Te.map((e,t)=>{let n=L+t,r=ve.byPhys.get(n),i=Ae?.physIdx===n?Ae.range:void 0,a=r?ma(e,r,i):e;return q(X,{wrap:`truncate-end`,children:a===``?` `:a},`${L+t}`)})}),q(Y,{flexDirection:`column`,width:1,children:sa(ge.length,Te.length,L).map((e,t)=>q(X,{color:b.panelBorder,children:e},t))})]}),q(X,{children:` `}),J(Y,{flexDirection:`row`,height:1,children:[q(ne,{hasMore:we.above>0,count:we.above}),q(f,{hasMore:we.below>0,count:we.below})]})]})}function ic(e){let t=[];for(let n of e.extensions??[])t.push(`*.${n}`);for(let n of e.filenames??[])t.push(n);for(let n of e.glob??[])t.push(n);return t}function ac(e){let t=e.split(`/`).pop()??e;return Zo().filter(n=>ic(n.matcher).some(n=>Kt(n,t)||Kt(n,e)))}const oc=5e4;function sc(e){let t=1,n=-1;for(;(n=e.indexOf(`
32
+ `,n+1))!==-1;)t++;return t}function cc(e,t){let n=-1,r=0;for(;r<2e3;){let t=e.indexOf(`
33
+ `,n+1);if(t===-1)break;n=t,r++}let i=n===-1?e:e.slice(0,n),a=t===`byte`?`[文件过大(超过 ${Wt/1024/1024}MB),仅显示前 ${r} 行]`:`[文件行数过多(超过 ${oc} 行),仅显示前 ${r} 行]`;return{id:`truncated`,label:`Truncated`,lines:[...i.split(`
34
+ `),``,a],wrapMode:`truncate`}}function lc(e,t,n,r){if(n.length>524288)return e;let i=ac(t);if(i.length===0)return e;let a=[];for(let e of i)try{let i=e.render(n,t,r);if(!i||!Array.isArray(i.lines))continue;a.push({id:e.id,label:e.label,lines:i.lines,wrapMode:i.wrapMode??`pre-wrap`})}catch{}return[...e,...a]}function uc(e){return(e.split(`/`).pop()??``).toLowerCase().endsWith(`.md`)}function dc(e,t,n){return{id:`plain`,label:`Plain`,lines:Js(e,t,n),wrapMode:`truncate`}}function fc(e,t,n,r){let i=[];try{i.push({id:`rendered`,label:`Rendered`,lines:Xa(e,n),wrapMode:`pre-wrap`})}catch{}let a=r?wa(e,`markdown`):null;return i.push({id:`raw`,label:`Raw`,lines:(a??e).split(`
35
+ `),wrapMode:`truncate`}),i}function pc(e,t,n,r,i=!1){if(i||t.length>Wt)return lc([cc(t,`byte`)],e,t,n);if(sc(t)>oc)return lc([cc(t,`line`)],e,t,n);let a;if(uc(e)){let i=fc(t,e,n,r);a=i.length>0?i:[dc(t,e,r)]}else a=qs(e)===``?[dc(t,e,r)]:[{id:`code`,label:`Code`,lines:Js(t,e,r),wrapMode:`truncate`}];return lc(a,e,t,n)}const mc=[`recent`,`shortcut`,`resource`,`extension`,`agent`,`person`,`file`,`hashtag`,`model`];function hc(e){switch(e){case`recent`:return B.t(`sigil.catRecent`);case`shortcut`:return B.t(`sigil.catShortcut`);case`resource`:return B.t(`sigil.catResource`);case`extension`:return B.t(`sigil.catExtension`);case`file`:return B.t(`sigil.catFile`);case`agent`:return B.t(`sigil.catAgent`);case`person`:return B.t(`sigil.catPerson`);case`hashtag`:return B.t(`sigil.catHashtag`);case`skill`:return B.t(`sigil.catSkill`);case`mcp`:return`MCP`;case`plugin`:return B.t(`sigil.catPlugin`);case`model`:return B.t(`sigil.catModel`);default:return String(e)}}function gc(e){let t=mc.indexOf(e);return t<0?mc.length:t}const _c=new Set([`skill`,`mcp`,`plugin`]);function vc(e){return _c.has(e.kind)?`extension`:e.kind}function yc(e){switch(e){case`hashtag`:return B.t(`sigil.catHashtag`);case`file`:return B.t(`sigil.catFile`);case`person`:return B.t(`sigil.catPerson`);case`agent`:return B.t(`sigil.catAgent`);case`skill`:return B.t(`sigil.catSkill`);case`mcp`:return`MCP`;case`plugin`:return B.t(`sigil.catPlugin`);case`model`:return B.t(`sigil.catModel`);case`resource`:return B.t(`sigil.catResource`);case`shortcut`:return B.t(`sigil.catShortcut`);default:return String(e)}}function bc(e,t=64){return ae(e.replace(/\s+/g,` `).trim(),t)}function xc({sigil:t,initialQuery:r,registry:i,active:a,rows:o,columns:s=60,viewerColumns:c=80,onSelect:l,onClose:u,onQueryChange:d,readFileContent:m,recentEntries:g,title:_}){let v=h(),y=G(a);U(()=>{y.current&&!a&&u({deleteSigil:!1}),y.current=a},[a,u]);let[x,S]=K(r),[C,w]=K(r.length),[E,O]=$i(`sigil`,0),[te,re]=K(null),[A,ae]=K(()=>i.search(x,t,50)),oe=G(0),[se,M]=K(null),[N,ce]=K(!1),[P,le]=K(!1),[ue,de]=K(Ca()),[fe,pe]=K(0),[me,he]=K(`filter`);U(()=>{if(ue)return;let e=!0;return Sa().then(()=>{e&&de(Ca())}),()=>{e=!1}},[ue]);let ge=G(!0);U(()=>()=>{ge.current=!1},[]),U(()=>{M(null),ce(!1),pe(0)},[te]);let _e=At(()=>{!te||te.kind!==`file`||!m||(le(!0),m(te.label).then(e=>{ge.current&&(M(e.content),ce(e.truncated),le(!1))}).catch(()=>{ge.current&&(M(null),ce(!1),le(!1))}))},[te,m]),[ve,ye]=K(!!i.searchAsync);U(()=>{let e=!0,n=i.searchAsync?i.searchAsync(x,t,50):Promise.resolve(i.search(x,t,50));return i.searchAsync&&ye(!0),n.then(t=>{e&&(ae(t),ye(!1))}).catch(()=>{e&&(ae([]),ye(!1))}),()=>{e=!1}},[i,x,t]);let be=W(()=>x===``&&g&&g.length>0?g.slice(0,5):[],[x,g]),Se=W(()=>{let e=[...A].sort((e,t)=>gc(vc(e))-gc(vc(t)));return be.length>0?[...be,...e]:e},[A,be]),Ce=Se.length===0?0:Math.min(E,Se.length-1),we=W(()=>{let e=[],t=null,n=0;return Se.forEach((r,i)=>{let a=i<be.length?`recent`:vc(r);a!==t&&(n>0&&e.push({type:`spacer`}),e.push({type:`header`,kind:a}),n++,t=a),e.push({type:`entry`,entry:r,index:i})}),e},[Se,be]),I=te?.kind===`file`&&se!==null,L=W(()=>!te||!se?[]:pc(te.label,se,c,ue,N),[te,se,ue,c,N]),Te=L[Math.min(fe,Math.max(0,L.length-1))],Ee=Te?.lines??[],De=At(()=>{re(null),M(null)},[]),Oe=At((e,t)=>{S(e),w(t),O(0),d?.(e)},[d]);j(`sigil-pane`,(e,t)=>{if(I)return;if(te){if(t.escape){re(null);return}if(t.return){l(te),re(null);return}if(e===`r`&&te.kind===`file`&&m&&!P){_e();return}return}if(t.tab){he(e=>e===`filter`?`list`:`filter`);return}if(me===`filter`&&e.length>1&&!t.ctrl&&!t.meta&&!t.return&&!t.escape&&!t.backspace&&!t.delete&&!t.tab&&!t.upArrow&&!t.downArrow&&!t.leftArrow&&!t.rightArrow){let t=Ze(e);t&&Oe(x.slice(0,C)+t+x.slice(C),C+t.length);return}if(t.leftArrow){let e=Ue.fromText(x,s,C).left();Oe(e.text,e.offset);return}if(t.rightArrow){let e=Ue.fromText(x,s,C).right();Oe(e.text,e.offset);return}if(b(`list-nav-up`,e,t,`sigilPane`)){if(me===`list`&&Ce===0){he(`filter`);return}O(e=>Math.max(0,e-1));return}if(b(`list-nav-down`,e,t,`sigilPane`)){if(me===`filter`){he(`list`),O(0);return}O(e=>Se.length===0?0:Math.min(Se.length-1,e+1));return}if(t.escape){if(x.length>0){Oe(``,0);return}u({deleteSigil:!1});return}if(t.return){let e=Se[Ce];if(!e)return;if(e.preview){re(e);return}l(e);return}if(me===`list`)return;if((t.backspace||t.delete)&&x.length===0){u({deleteSigil:!0});return}let n={name:t.backspace?`backspace`:t.delete?`delete`:e||`unknown`,ctrl:t.ctrl??!1,shift:!1,alt:t.meta??!1,meta:t.meta??!1},r=Ie(Ue.fromText(x,s,C),n);if(r){if(r.action===`clear_text`){Oe(``,0);return}r.action===`submit`||r.action===`submit_force`||Oe(r.cursor.text,r.cursor.offset)}},{isActive:a});let[ke,Ae]=K(12),je=G(!0);U(()=>{je.current&&(je.current=!1,Ae(ee(we.length+8,o)-8))},[we.length,o]);let Me=pt(we,we.findIndex(e=>e.type===`entry`&&e.index===Ce),ke,oe.current);oe.current=Me.scrollTop;let Ne=Me.rows;return I?q(rc,{lines:Ee,rows:o,columns:c,wrapMode:Te?.wrapMode??`truncate`,header:J(Y,{children:[q(X,{color:v.selection,children:te.label}),L.length>1&&Te?q(n,{leadingSpace:!0,children:Te.label}):null,J(D,{type:`secondary`,children:[` `,B.t(`diff.linesTotalLabel`,{count:Ee.length})]})]}),onDismiss:De,onKey:(e,t)=>e===`]`&&L.length>1?(pe(e=>(e+1)%L.length),!0):!1,extraHints:L.length>1?[[`]`,B.t(`hint.tabSwitchOutput`)]]:void 0,initialScroll:`top`,active:a,contentKey:`${te.label}:${Te?.id??``}`}):J(Y,{flexDirection:`column`,...ie,borderColor:v.panelBorder,backgroundColor:v.overlayBg,paddingX:F.tight,marginTop:F.tight,children:[q(p,{children:_??B.t(t===`@`?`sigil.titleMention`:`sigil.titleHashtag`)}),q(Y,{marginTop:F.tight}),P&&te&&J(Y,{flexDirection:`column`,children:[q(X,{color:v.selection,children:te.label}),J(D,{type:`secondary`,dim:!0,children:[` `,B.t(`sigil.loadingFile`)]})]}),!P&&te&&!I&&J(Y,{flexDirection:`column`,children:[q(X,{color:v.selection,children:te.label}),q(D,{type:`secondary`,children:R.hr.repeat(60)}),q(Y,{flexDirection:`column`,children:(te.preview||``).split(`
36
+ `).map((e,t)=>q(X,{color:v.secondary,children:e},t))}),q(D,{type:`secondary`,children:R.hr.repeat(60)}),te.kind===`file`&&m&&J(Y,{flexDirection:`row`,children:[q(X,{color:v.suggestion,children:`r `}),q(D,{type:`secondary`,dim:!0,children:B.t(`sigil.readFullFile`)})]}),J(Y,{flexDirection:`row`,children:[J(k,{children:[T.enter,` `]}),q(X,{children:B.t(`hint.confirm`)}),q(X,{children:` `}),J(k,{children:[T.esc,` `]}),q(X,{children:B.t(`hint.cancel`)})]})]}),!te&&J(Mt,{children:[q(Y,{marginBottom:F.tight,flexDirection:`row`,children:q(e,{value:x,offset:C,columns:s,mode:`dialog`,placeholder:B.t(`sigil.filterPlaceholder`),focused:a&&me===`filter`,physicalCursor:a&&me===`filter`})}),Se.length===0&&!ve&&J(D,{type:`secondary`,dim:!0,children:[` `,B.t(`sigil.noMatches`)]}),ve&&J(D,{type:`secondary`,dim:!0,children:[` `,B.t(`sigil.searching`)]}),q(Y,{height:1,children:q(ne,{hasMore:Me.hasMoreAbove,indent:` `})}),Ne.map((e,t)=>{if(e.type===`spacer`)return q(X,{children:` `},`spacer-${t}`);if(e.type===`header`)return q(Y,{flexDirection:`column`,children:q(xe,{label:hc(e.kind)})},`h:${e.kind}`);let n=e.index===Ce,r=e.index<be.length;return J(Y,{flexDirection:`row`,children:[J(X,{color:n&&me===`list`?v.selection:v.inactive,bold:n&&me===`list`,dimColor:n&&me!==`list`,children:[n?`${R.pointer} `:` `,String(e.index+1).padStart(2),`. `,e.entry.label]}),r&&J(D,{type:`secondary`,dim:!0,children:[` [`,yc(e.entry.kind),`]`]}),e.entry.description&&J(D,{type:`secondary`,dim:!0,children:[` — `,bc(e.entry.description)]})]},`row:${e.index}`)}),Array.from({length:Me.fillerCount},(e,t)=>q(X,{children:` `},`filler-${t}`)),q(Y,{height:1,children:q(f,{hasMore:Me.hasMoreBelow,indent:` `})}),q(Y,{marginTop:F.tight,children:J(D,{type:`secondary`,children:[T.up,T.down,` `,B.t(`hint.select`),` · `,T.enter,` `,B.t(`hint.confirm`),` · `,T.tab,` `,B.t(`hint.tabZone`),` · `,T.esc,` `,B.t(`hint.cancel`)]})})]})]})}function Sc(e){let t=e.length;for(;t>0;){let n=e.lastIndexOf(`
37
+
38
+ `,t);if(n<0)return 0;let r=n+2;if((e.slice(0,r).match(/```/g)??[]).length%2==0)return r;t=n-1}return 0}function Cc(){return{prev:``,committedLen:0,led:!1}}function wc(e,t){let{prev:n,committedLen:r,led:i}=e,a=[],o=e=>{let t=e.replace(/\s+$/,``);t.trim()&&(a.push({text:t,lead:!i}),i=!0)},s=()=>{n.length>r&&o(n.slice(r)),n=``,r=0,i=!1};if(t===``)return s(),{chunks:a,tail:``,state:{prev:n,committedLen:r,led:i}};let c=n.slice(0,r);t.startsWith(c)||s(),n=t;let l=Sc(t);return l>r&&(o(t.slice(r,l)),r=l),{chunks:a,tail:t.slice(r),state:{prev:n,committedLen:r,led:i}}}function Tc(e){return e>0?Math.max(1,Math.ceil(1e3/e)):1}const Ec=Tc(30);function Dc(e,t=Ec){let n=null,r=null,i=0,a=()=>{if(r===null)return;let t=r;r=null,i=Date.now(),e(t)};return{push(o,s){if(s){n&&=(clearTimeout(n),null),a(),i=Date.now(),e(o);return}r=o;let c=Date.now()-i;c>=t?(n&&=(clearTimeout(n),null),a()):n||=setTimeout(()=>{n=null,a()},t-c)},cancel(){n&&=(clearTimeout(n),null),r=null}}}function Oc(e){let{listener:t,intervalMs:n}=e,r=null,i=!1,a={coalescedCalls:0,coalescedFires:0,immediateCalls:0,flushFires:0},o=()=>{i=!1,a.coalescedFires++,t()};return{coalesced(){a.coalescedCalls++,!i&&(i=!0,r=setTimeout(()=>{r=null,o()},n))},immediate(){a.immediateCalls++,r&&=(clearTimeout(r),null),i=!1,t()},flush(){i&&(r&&=(clearTimeout(r),null),a.flushFires++,o())},cancel(){r&&=(clearTimeout(r),null),i=!1},getStats(){return{...a}}}}function kc(){let e=`idle`,t=0,n=new Set,r=()=>{for(let e of n)e()};return{reserve(){return e===`idle`?(e=`dispatching`,r(),!0):!1},tryStart(){return e===`dispatching`?(e=`running`,t++,r(),t):-1},end(n,i){n===t&&(e=`idle`,i?.(),r())},cancelReservation(){e===`dispatching`&&(e=`idle`,r())},forceEnd(){e!==`idle`&&(e=`idle`,r())},get state(){return e},get generation(){return t},get isRunning(){return e===`running`},subscribe(e){return n.add(e),()=>{n.delete(e)}},reset(){e=`idle`,t=0,n.clear()}}}function Ac(e){let t=e.tool_calls;return Array.isArray(t)&&t.length>0}function jc(e,t=3){let n=[],r=0;for(;r<e.length;){let i=e[r];if(Ac(i)){let a=[i],o=r+1;for(;o<e.length&&Ac(e[o]);)a.push(e[o]),o++;if(a.length>=t){let e=a.flatMap(e=>(e.tool_calls??[]).map(e=>e.function?.name).filter(Boolean));n.push({type:`collapsed`,messages:a,summary:B.t(`tool.chainSummary`,{count:a.length,names:e.join(`, `)}),collapsed:!0}),r=o;continue}}n.push(i),r++}return n}function Mc(e){return{...e,collapsed:!e.collapsed}}function Nc(e){return e.flatMap(e=>e.type===`collapsed`?e.messages:[e])}function Pc({message:e,columns:t=80}){let n=$s(e,t);return n.length===0?q(Mt,{}):q(Y,{marginTop:F.tight,flexDirection:`column`,children:q(X,{children:n.join(`
39
+ `)})})}const Fc=V.memo(Pc),Ic=new Set([`tool`,`tool_result`,`compact_boundary`,`prune_boundary`,`history_capped`,`write_lease_denied`,`write_lease_restored`,`run_paused`,`run_resumed`,`run_pause_cancelled`,`model_switch`,`effort_switch`,`model_fallback`,`command_echo`]);function Lc(e,t){return t?!1:!Ic.has(e)}function Rc(e,t){let n=``,r=t;for(let{role:t,lines:i}of e){if(i.length===0)continue;let e=!r;r=!0,n+=(Lc(t,e)?`
40
+ `:``)+i.join(`
41
+ `)+`
42
+ `}return{text:n,hasHistory:r}}const zc=ta();function Bc(e){return`… ${e} 行更早历史(回看加载)`}const Vc=V.memo(function({content:e}){return q(X,{wrap:`truncate-end`,children:e===``?` `:e})}),Hc=new WeakMap;function Uc(e,t){let n=e,r=B.language??``;if(typeof n==`object`&&n){let i=Hc.get(n);if(i&&i.columns===t&&i.lang===r)return i.lines;let a=$s(e,t);return Hc.set(n,{columns:t,lang:r,lines:a}),a}return $s(e,t)}function Wc(e,t,n=2e4,r=!1){let i=Math.max(1,t),a=[],o=r;for(let t of e){let e=Uc(t,i);e.length!==0&&(Lc(String(t.role??`unknown`),!o)&&a.push(``),a.push(...e),o=!0)}if(a.length<=n)return{lines:a,folded:0};let s=a.length-n,c=a.slice(s);return c[0]=Bc(s),{lines:c,folded:s}}function Gc({messages:e,columns:t,rows:n,scroll:r=0,scrollStore:i,frozenNewCount:a=0,earlierLoading:o=!1,earlierEnded:s=!1,onNeedEarlier:c,onPrepend:l,findQuery:u,findActiveMatch:d,onFindNavigateTo:f,onFindCountChange:p,onReviewHintChange:m,renderReviewHint:h=!0,maxLines:g}){let _=V.useRef(null),v=V.useRef(0),y=V.useMemo(()=>{let n=_.current,r=g??2e4;if(n&&n.columns===t&&e.length>=n.len&&(n.len===0||e[n.len-1]===n.lastMsg)){let i=Wc(e.slice(n.len),t,1/0,n.lines.length>0),a=[...n.lines,...i.lines],o=a.length>r?a.length-r:0;if(o>0){let r=a.slice(o),i=n.folded+o-1;return r[0]=Bc(i),_.current={len:e.length,columns:t,lines:r,lastMsg:e[e.length-1],firstMsg:e[0],folded:i},{lines:r,folded:i}}return _.current={len:e.length,columns:t,lines:a,lastMsg:e[e.length-1],firstMsg:e[0],folded:n.folded},{lines:a,folded:n.folded}}let i=Wc(e,t,1/0),a=0,o=i.lines;return i.lines.length>r&&(a=i.lines.length-r,o=[Bc(a),...i.lines.slice(a)]),n!==null&&n.firstMsg!==void 0&&e[0]!==n.firstMsg&&e.length>n.len&&(v.current=Math.max(0,i.lines.length-n.lines.length)),_.current={len:e.length,columns:t,lines:o,lastMsg:e[e.length-1],firstMsg:e[0],folded:a},{lines:o,folded:a}},[e,t,g,l]),b=Math.max(1,Math.floor(n)-((u?1:0)+1+(h?1:0))),x=Z((i??zc).store,e=>e.offset),S=i?x:r,C=jo(y.lines.length,b,S),w=y.lines.slice(C.start,C.end);y.folded>0&&C.start===0&&w.length>0&&(s?w=w.slice(1):o&&(w=[B.t(`transcript.loadingEarlier`),...w.slice(1)]));let T=C.above===0&&S>0;V.useEffect(()=>{T&&!o&&!s&&c&&c()},[T,o,s,c]),V.useEffect(()=>{i?.setTotalLines(y.lines.length)},[y.lines.length,i]);let E=s&&C.above===0&&S>0;V.useEffect(()=>{if(v.current>0&&l){let e=v.current;v.current=0,l(e)}},[y,l]);let D=V.useMemo(()=>{if(!u)return{byLine:new Map,flat:[]};let e=new Map,t=[];for(let n=0;n<y.lines.length;n++){let r=ha(Ts(y.lines[n]),u);if(r.length>0){e.set(n,r);for(let e of r)t.push({line:n,range:e})}}return{byLine:e,flat:t}},[u,y]);V.useEffect(()=>{p?.(D.flat.length)},[D,p]),V.useEffect(()=>{if(!f||d==null||d<0)return;let e=D.flat[d];if(!e)return;let t=Math.max(1,Math.floor(n)),r=Math.max(0,y.lines.length-t);f(Math.min(r,Math.max(0,y.lines.length-e.line-Math.floor(t/2))))},[d,D]);let O=y.folded>0&&C.start===0&&w.length>0&&(s||o),ee=w.map((e,t)=>{let n=O&&s?C.start+t+1:C.start+t;if(O&&o&&t===0)return e;let r=D.byLine.get(n);if(!r||r.length===0)return e;let i;if(d!=null&&d>=0){let e=D.flat[d];e&&e.line===n&&(i=e.range)}return ma(e,r,i)}),te=S>0||C.above>0||a>0,ne=a>0?C.below>0?`⏸ ${a} ${B.t(`transcript.frozenNew`)} · ↓ ${C.below} ${B.t(`transcript.escToLive`)}`:`⏸ ${a} ${B.t(`transcript.frozenNew`)} · ${B.t(`transcript.escToLive`)}`:C.below>0?`↓ ${C.below} · ${B.t(`transcript.escToLive`)}`:null;return V.useEffect(()=>{m?.(te&&ne?ne:null)},[te,ne,m]),J(Y,{flexDirection:`column`,children:[u&&q(X,{bold:!0,children:B.t(`transcript.findBar`,{query:u,count:D.flat.length})}),C.above>0&&q(X,{dimColor:!0,children:`↑ ${C.above}`}),E&&q(X,{dimColor:!0,children:B.t(`transcript.emptyEarlier`)}),ee.map((e,t)=>q(Vc,{content:e},C.start+t)),h&&te&&ne&&q(X,{dimColor:!0,children:ne})]})}function Kc(e,t){let n=Math.max(1,t);if(it(e)<=n)return e;let r=n-1,i=``,a=0;for(;a<e.length&&r>0;){if(e.charCodeAt(a)===27&&a+1<e.length&&e[a+1]===`[`){let t=a+2;for(;t<e.length&&e.charCodeAt(t)>=32&&e.charCodeAt(t)<=63;)t++;for(;t<e.length&&e.charCodeAt(t)>=32&&e.charCodeAt(t)<=47;)t++;t<e.length&&e.charCodeAt(t)>=64&&e.charCodeAt(t)<=126&&t++,i+=e.slice(a,t),a=t;continue}if(e.charCodeAt(a)===27&&a+1<e.length&&e[a+1]===`]`){let t=a+2;for(;t<e.length&&e[t]!==`\x07`&&!(e[t]===`\x1B`&&e[t+1]===`\\`);)t++;t<e.length&&e[t]===`\x07`?t++:t+1<e.length&&e[t]===`\x1B`&&e[t+1]===`\\`&&(t+=2),i+=e.slice(a,t),a=t;continue}let t=e[a],n=it(t);if(n>r)break;i+=t,r-=n,a++}return i+R.ellipsis}function qc(e){let t=e.split(`
43
+ `);if(t.length<=120)return e;let n=t.length-120,r=(t.slice(0,n).join(`
44
+ `).match(/```/g)??[]).length,i=t.slice(n).join(`
45
+ `);return r%2==1?"```\n"+i:i}function Jc(e,t,n){if(!e)return[];let r=e.split(`
46
+ `),i=r.length;for(;i>0&&r[i-1].trim()===``;)i--;if(i===0)return[];let a=Math.max(0,i-Math.max(1,n));return r.slice(a,i).map(e=>Kc(e,t))}function Yc(e,t,n=1){let r=[],i=``,a=null;for(let o=0;o<e.length;o++){let s=Math.abs(o-t)<=n;a===null||s===a?(i+=e[o],a=s):(r.push({text:i,bright:a}),i=e[o],a=s)}return i&&r.push({text:i,bright:a??!1}),r}function Xc(e,t){return e%Math.max(1,t+4)}function Zc(e,t){if(!(t>0))return L.inactive;let n=e/t;return n>=.9?L.error:n>=.8?L.warning:L.inactive}function Qc(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function $c({tokens:e=0,toolTurnCount:t=0,maxToolTurns:n=0,promptOutputTokens:r=0,promptOutputTokenBudget:i=0}){let a=h(),[o,s]=K(0),[c,l]=K(0),u=G(Date.now()),d=G(-1),f=je();Me(160,e=>s(e%qe.length)),U(()=>{let e=setInterval(()=>{let e=Date.now()-u.current,t=Math.floor(e/1e3);t!==d.current&&(d.current=t,l(e))},1e3);return()=>clearInterval(e)},[]);let p=[{text:go(Math.floor(c/1e3))}];e>0&&p.push({text:`↓ ${B.t(`budget.tokensLabel`,{count:e})}`}),n>0&&p.push({text:B.t(`tool.budgetLabel`,{used:t,max:n}),color:Zc(t,n)}),i>0&&p.push({text:B.t(`budget.tokenBudgetLabel`,{used:Qc(r),budget:Qc(i)})});let m=B.t(`inspText.thinkingLabel`),g=f?null:Yc(m,Xc(o,m.length));return J(Y,{flexDirection:`row`,children:[q(X,{color:a.secondary,children:qe[o]}),q(X,{children:` `}),g?g.map((e,t)=>q(X,{italic:!0,color:e.bright?a.secondary:a.inactive,children:e.text},t)):q(X,{italic:!0,color:a.secondary,children:m}),q(X,{color:a.inactive,children:` (`}),p.map((e,t)=>J(V.Fragment,{children:[t>0&&q(X,{color:a.inactive,children:` · `}),q(X,{color:e.color??a.inactive,children:e.text})]},t)),q(X,{color:a.inactive,children:`)`})]})}function el(e){return[{color:e.accentBright,ch:R.breatheBright},{color:e.accentDim,ch:R.breatheDim}]}function tl({name:e}){let t=h(),[n,r]=K(0),i=el(t).length;Me(500,e=>r(e%i));let a=el(t)[n];return J(Y,{flexDirection:`row`,children:[J(X,{color:a.color,children:[a.ch,` `]}),J(X,{color:t.text,children:[e,`…`]})]})}function nl(){return{streamingText:``,streamingThinking:``,streamCommit:Cc(),lastTail:void 0,spinnerMode:null,outputTokensThisTurn:0,maxOutputTokens:void 0,toolTurnCount:0,maxToolTurns:0,promptOutputTokens:0,promptOutputTokenBudget:0,processing:!1,activeTool:null}}function rl(){let e=Pn(nl());return{store:e,reset(){e.setState(nl())}}}function il(e,t){let n=null,r=null,i=0,a=()=>{if(r===null)return;let t=r;r=null,i=Date.now(),e.setState({outputTokensThisTurn:t})};return{push(e){r=e;let o=Date.now()-i;o>=t?(n&&=(clearTimeout(n),null),a()):n||=setTimeout(()=>{n=null,a()},t-o)},cancel(){n&&=(clearTimeout(n),null),r=null}}}function al(e){return e.spinnerMode===`responding`&&e.maxOutputTokens!==void 0&&e.maxOutputTokens>0?Math.min(100,e.outputTokensThisTurn/e.maxOutputTokens*100):void 0}function ol(e){return Math.floor((e.streamingText.length+e.streamingThinking.length)/4)}function sl({streamStore:e,completedMessages:t,columns:n=80,rows:r,maxPreviewRows:i,suppressLive:a=!1,pendingEcho:o=null,scrollbackMode:s=!1,pendingSteers:c=[],windowMode:l=!1,scrollStore:u,earlierLoading:d=!1,earlierEnded:f=!1,onNeedEarlier:p,onPrepend:m,findQuery:g,findActiveMatch:_,onFindNavigateTo:v,onFindCountChange:y,onReviewHintChange:b,renderReviewHint:x=!0}){let S=h(),C=Z(e.store,e=>e.streamingText),w=Z(e.store,e=>e.streamingThinking),T=Z(e.store,e=>e.processing),E=Z(e.store,e=>e.streamCommit.led),D=Z(e.store,e=>e.activeTool),O=Z(e.store,e=>e.toolTurnCount),ee=Z(e.store,e=>e.maxToolTurns),te=Z(e.store,e=>e.promptOutputTokens),ne=Z(e.store,e=>e.promptOutputTokenBudget),k=Z(e.store,ol),re=C,ie=w,A=i??1,ae=A>0?Jc(re,n-fe.borderInset,A):[],j=A>0?Jc(ie,n-5,A):[],oe=Z(u.store,e=>e.offset>0),se=V.useRef(null);oe&&se.current===null&&(se.current=t),oe||(se.current=null);let M=oe?se.current??t:t,N=oe?Math.max(0,t.length-(se.current?.length??t.length)):0,ce=o&&!a&&s,P=!a&&s,le=(ce?1:0)+(P?c.length:0)+(T&&!a?(ie?2:0)+(D?1:0)+ae.length:0),ue=Math.max(1,(r??0)-le);return J(Y,{flexDirection:`column`,children:[l?q(Gc,{messages:M,columns:n,rows:ue,scrollStore:u,frozenNewCount:N,earlierLoading:d,earlierEnded:f,onNeedEarlier:p,onPrepend:m,findQuery:g,findActiveMatch:_,onFindNavigateTo:v,onFindCountChange:y,onReviewHintChange:b,renderReviewHint:x}):q(Pt,{items:t,children:e=>q(Fc,{message:e,columns:n},e.id??`m-${JSON.stringify(e).slice(0,16)}`)}),ce&&J(X,{dimColor:!0,children:[`> `,o.text]}),P&&c.map(e=>J(X,{dimColor:!0,children:[`> `,e.text]},e.id)),T&&!a&&J(Y,{flexDirection:`column`,children:[ie&&J(Y,{flexDirection:`column`,marginTop:F.tight,children:[q($c,{tokens:k,toolTurnCount:O,maxToolTurns:ee,promptOutputTokens:te,promptOutputTokenBudget:ne}),j.length>0&&q(Y,{marginLeft:F.section,flexDirection:`column`,children:j.map((e,t)=>J(X,{color:S.inactive,italic:!0,children:[` `,e]},t))})]}),D&&q(tl,{name:uo(D)}),ae.length>0&&q(Y,{flexDirection:`column`,children:ae.map((e,t)=>J(Y,{flexDirection:`row`,children:[q(X,{color:S.replyPrefix,children:t===0&&!E?`${R.bullet} `:` `}),q(X,{children:e})]},t))})]})]})}function cl(e){return e<1e3?`${e}`:e<1e6?`${(e/1e3).toFixed(1)}K`:`${(e/1e6).toFixed(1)}M`}function ll(e){switch(e){case`done`:return B.t(`status.done`);case`failed`:return B.t(`status.failed`);case`interrupted`:return B.t(`status.interrupted`);default:return e}}function ul(e){return e.split(`
47
+ `).map(e=>` ${e}`).join(`
48
+ `)}function dl(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function fl(e,t=``){let n=[];for(let t of e)switch(t.role){case`user`:t.content.trim()&&n.push(`▸ ${B.t(`transcript.you`)}\n${ul(t.content)}`);break;case`assistant`:{let e=t.content.map(e=>e.type===`thinking`?`${R.thinking} ${e.thinking}`:e.type===`a2ui`?`[a2ui: ${e.components.length} component(s)]`:e.text).filter(e=>e.trim());e.length&&n.push(`⏺ ${B.t(`transcript.assistant`)}\n${ul(e.join(`
49
+ `))}`);break}case`assistant_stream`:t.text.trim()&&n.push(`⏺ ${B.t(`transcript.assistant`)}\n${ul(t.text)}`);break;case`tool`:{let e=t.args?`${t.name}(${dl(t.args,60)})`:t.name,r=t.result?` → ${t.isError?`${R.cross} `:``}${dl(t.result,200)}`:t.isError?` → ${R.cross}`:``;n.push(` ${R.toolResult} ${e}${r}`);break}case`summary`:{let e=t.status===`incomplete`?B.t(`status.stopped`):ll(t.status),r=Number(t.tasksDone??0),i=Number(t.tasksTotal??0),a=Number.isFinite(r)?r:0,o=Number.isFinite(i)?i:0,s=t.status===`incomplete`&&t.tasksTotal!=null?` · ${B.t(`task.leftLabel`,{done:a,total:o,left:Math.max(0,o-a)})}`:``,c=typeof t.cacheHitRatio==`number`?`(${Math.round(t.cacheHitRatio*100)}%)`:``,l=t.tokensUsed==null?c?` · cache${c}`:``:` · ${cl(t.tokensUsed)}${c}`;n.push(`— ${e} · ${B.t(`tool.countLabel`,{count:t.toolCount})} · ${Math.round(t.elapsedMs/1e3)}s${l}${s}`);break}}return t.trim()&&n.push(`⏺ ${B.t(`transcript.assistant`)} (${B.t(`prompt.streaming`)})\n${ul(t)}`),n.join(`
50
+
51
+ `)}function pl(e){let t=e.filter(e=>e!==null),n=Math.max(0,...t.map(e=>it(e.label)));return e.map(e=>{if(e===null)return``;let t=` `.repeat(Math.max(0,n-it(e.label))+1);return`${e.label}:${t}${e.value}`})}function ml(e,t){let n=/^- \[(.+?)\]\(memory\/(.+?)\.md\)(?: — (.+))?$/gm,r=[],i;for(;(i=n.exec(e))!==null;)r.push({name:i[1]??``,slug:i[2]??``,description:(i[3]??``).trim(),source:t});return r}function hl({projectIndex:e,userIndex:t,onViewEntry:n,onForget:r,onDismiss:i,rows:a=24,columns:o=80}){let[s,c]=K(()=>ml(e,`project`)),[l,u]=K(()=>ml(t,`user`)),[d,f]=K({mode:`list`}),[p,m]=K(void 0),h=s.length>0||l.length>0;function g(e){e.source===`project`?c(t=>t.filter(t=>t.slug!==e.slug)):u(t=>t.filter(t=>t.slug!==e.slug))}function _(e){m(`${e.source}:${e.slug}`),f({mode:`detail`,entry:e,content:null,loading:!0}),n(e).then(t=>{f(n=>n.mode===`detail`&&n.entry.slug===e.slug?{...n,content:t,loading:!1}:n)})}async function v(e){await r(e),g(e),f({mode:`list`})}return d.mode===`confirm-forget`?q(yl,{entry:d.entry,onConfirm:()=>void v(d.entry),onCancel:()=>f({mode:`list`})}):d.mode===`detail`?q(_l,{entry:d.entry,content:d.content,loading:d.loading,onForget:()=>f({mode:`confirm-forget`,entry:d.entry}),onBack:()=>f({mode:`list`}),rows:a,columns:o}):q(gl,{projEntries:s,userEntries:l,hasAny:h,defaultValue:p,onView:_,onForget:e=>f({mode:`confirm-forget`,entry:e}),onDismiss:i,rows:a})}function gl({projEntries:e,userEntries:t,hasAny:n,defaultValue:r,onView:i,onForget:a,onDismiss:o,rows:s}){let c=new Map;for(let n of[...e,...t])c.set(`${n.source}:${n.slug}`,n);return n?q(z.Root,{rows:s,title:B.t(`cmd.titleMemory`),defaultValue:r,onCancel:o,onKey:(e,t,n)=>{if(e===`d`&&n){let e=c.get(n.value);return e&&a(e),!0}return!1},onValueChange:e=>{let t=c.get(e);t&&i(t)},footer:q(O,{items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[T.enter,B.t(`cmd.memoryDialogHintView`)],[`d`,B.t(`cmd.memoryDialogHintForget`)],[T.esc,B.t(`hint.close`)]]}),children:J(z.Content,{children:[J(z.Group,{children:[q(z.Label,{children:B.t(`cmd.memoryDialogProjGroup`,{count:e.length})}),e.map(e=>q(z.Item,{value:`project:${e.slug}`,detail:e.description||void 0,marker:`number`,children:e.name},`project:${e.slug}`))]}),q(z.Separator,{}),J(z.Group,{children:[q(z.Label,{children:B.t(`cmd.memoryDialogUserGroup`,{count:t.length})}),t.map(e=>q(z.Item,{value:`user:${e.slug}`,detail:e.description||void 0,marker:`number`,children:e.name},`user:${e.slug}`))]})]})}):q(y,{header:q(p,{children:B.t(`cmd.titleMemory`)}),footer:q(O,{items:[[T.esc,B.t(`hint.close`)]]}),children:q(Y,{marginTop:F.tight,children:q(X,{dimColor:!0,children:B.t(`cmd.memoryDialogEmptyHint`)})})})}function _l({entry:e,content:t,loading:n,onForget:r,onBack:i,rows:a,columns:o}){let s=h(),c=e.source===`project`?B.t(`cmd.memoryDialogDetailSourceProject`):B.t(`cmd.memoryDialogDetailSourceUser`),l=B.t(`cmd.memoryDialogDetailTitle`,{name:e.name,source:c}),u=W(()=>(t??``).split(`
52
+ `),[t]);return n?q(vl,{title:l,onForget:r,onBack:i}):q(rc,{lines:u,rows:a,columns:o,wrapMode:`pre-wrap`,header:q(Y,{children:q(X,{color:s.selection,children:l})}),onDismiss:i,initialScroll:`top`,contentKey:e.slug,emptyMessage:B.t(`cmd.memoryDialogDetailEmpty`),onKey:e=>e===`d`?(r(),!0):!1,extraHints:[[`d`,B.t(`cmd.memoryDialogHintForget`)]]})}function vl({title:e,onForget:t,onBack:n}){return j(`memory-dialog-detail-loading`,(e,r)=>{if(r.escape){n();return}e===`d`&&t()}),q(y,{header:q(p,{children:e}),footer:q(O,{items:[[T.esc,B.t(`cmd.memoryDialogHintBack`)]]}),children:q(Y,{marginTop:F.tight,children:q(X,{dimColor:!0,children:`…`})})})}function yl({entry:e,onConfirm:t,onCancel:n}){let r=h(),[i,a]=K(0);return j(`memory-dialog`,(e,r)=>{if(r.escape){n();return}if(r.leftArrow||r.rightArrow||r.tab){let e=E(r);e!==0&&a(t=>Le(t,e,2));return}r.return&&(i===1?t():n())}),q(y,{header:q(p,{children:B.t(`cmd.memoryDialogConfirmForgetTitle`)}),children:J(Y,{marginTop:F.tight,flexDirection:`column`,children:[q(X,{color:r.warning,children:B.t(`cmd.memoryDialogConfirmForgetMessage`,{name:e.name})}),J(Y,{marginTop:F.section,flexDirection:`row`,gap:F.section,children:[q(I,{variant:`solid`,brackets:!0,label:B.t(`common.genericCancelButton`),focused:i===0,color:`gray`}),q(I,{variant:`solid`,brackets:!0,label:B.t(`hint.delete`),focused:i===1,color:`red`})]})]})})}function bl(e,t=80){return ae(e.replace(/\s+/g,` `).trim(),t)}function xl({req:e,rows:t=24}){let{entries:n,menuContributions:r=[],onSelect:i,onCancel:a}=e,o=n.filter(e=>e.enabled).length,s=n.length>0?B.t(`cmd.extListTitle`,{enabled:o,total:n.length}):B.t(`cmd.extListEmptyTitle`),c=r.find(e=>e.id===`__discover__`),l=r.filter(e=>e.id!==`__discover__`),u=c?{hint:B.t(`cmd.extDiscoverHint`),label:B.t(`cmd.extDiscoverButton`),onPress:()=>i(`contrib:${c.id}`)}:void 0;if(n.length===0)return q(z.Root,{title:s,headerAction:u,onCancel:a,rows:t,extensionHeightBudget:!0,children:q(z.Content,{children:q(z.Item,{value:``,children:B.t(`cmd.extListEmptyOption`)})})});let d=new Map;for(let e of n){let t=B.t(`cmd.extCategoryLabel`,{category:e.category}),n=d.get(t);n?n.push(e):d.set(t,[e])}return q(z.Root,{title:s,headerAction:u,onValueChange:i,onCancel:a,rows:t,extensionHeightBudget:!0,defaultValue:e.lastSelectedValue,children:J(z.Content,{children:[[...d.entries()].map(([e,t])=>J(z.Group,{children:[q(z.Label,{children:e}),t.map(e=>{let t=[];e.description&&t.push(e.description),e.applies&&e.applies!==`live`&&t.push(e.applies);let n=t.length>0?bl(t.join(` · `)):void 0;return q(z.Item,{value:`${e.category}:${e.id}`,detail:n,children:e.enabled?e.name:`${R.toggleOff} ${e.name}`},`${e.category}:${e.id}`)})]},e)),l.length>0&&J(z.Group,{children:[q(z.Label,{children:B.t(`cmd.extCategoryLabel`,{category:`plugin`})}),l.map(e=>q(z.Item,{value:`contrib:${e.id}`,children:e.title},`contrib:${e.id}`))]},`contrib`)]})})}const Sl={y:0,n:1,a:2};function Cl({tool:e,input:t,risk:n,onApprove:r,onDeny:i}){let a=h(),[o,s]=K(0),c=ke(n),l=e=>{e===0?r(`once`):e===1?i():r(`always`)};return j(`permission-dialog-buttons`,(e,t)=>{if(t.escape)return i(),!0;let n=E(t);if(n!==0)return s(e=>Le(e,n,3)),!0;if(t.return)return s(e=>(l(e),e)),!0;let r=Sl[e.toLowerCase()];return r===void 0?!1:(l(r),!0)}),J(y,{header:J(p,{children:[B.t(`permission.allowTool`),` `,q(X,{color:a.permission,children:e}),` `,J(X,{color:c,children:[`(`,B.t(`permission.riskLabel`,{context:n}),`)`]})]}),footer:q(O,{items:[[`${T.left}${T.right}`,B.t(`hint.switch`)],[T.enter,B.t(`hint.confirm`)],[`y/n/a`,B.t(`hint.shortcut`)],[T.esc,B.t(`hint.cancel`)]]}),children:[q(Y,{marginTop:F.tight,children:q(X,{dimColor:!0,children:ae(t,200)})}),J(Y,{marginTop:F.tight,flexDirection:`row`,gap:F.section,children:[q(I,{variant:`solid`,brackets:!0,color:`accent`,label:B.t(`permission.approve`),focused:o===0}),q(I,{variant:`solid`,brackets:!0,color:`red`,label:B.t(`permission.deny`),focused:o===1}),q(I,{variant:`solid`,brackets:!0,color:`amber`,label:B.t(`permission.alwaysAllow`),focused:o===2})]})]})}function wl(e){let t=/^\s*cd\s+(.+?)\s*&&\s*(.*)$/s.exec(e);return t?{workDir:t[1]}:{workDir:null}}const Tl={y:0,n:1,a:2},El={y:0,n:1};function Dl({command:e,risk:t,description:n,alwaysAllowLabel:r,onApprove:i,onDeny:a}){let o=h(),[s,c]=K(0),l=ke(t),u=r!=null,d=u?3:2,f=u?Tl:El,m=e=>{e===0?i(`once`):e===1?a():i(`always`)};j(`bash-permission-dialog-buttons`,(e,t)=>{if(t.escape)return a(),!0;let n=E(t);if(n!==0)return c(e=>Le(e,n,d)),!0;if(t.return)return c(e=>(m(e),e)),!0;let r=f[e.toLowerCase()];return r===void 0?!1:(m(r),!0)});let{workDir:g}=wl(e),_=ae(e,500);return J(y,{header:J(p,{children:[B.t(`permission.bashCommand`),` `,J(X,{color:l,children:[`(`,B.t(`permission.riskLabel`,{context:t}),`)`]})]}),footer:q(O,{items:[[`${T.left}${T.right}`,B.t(`hint.switch`)],[T.enter,B.t(`hint.confirm`)],[u?`y/n/a`:`y/n`,B.t(`hint.shortcut`)],[T.esc,B.t(`hint.cancel`)]]}),children:[q(Y,{marginTop:F.tight,children:q(X,{color:o.suggestion,children:_})}),(g||n)&&J(Y,{marginTop:F.tight,flexDirection:`column`,children:[g&&q(X,{dimColor:!0,children:g}),n&&q(X,{dimColor:!0,children:n})]}),r&&J(Y,{marginTop:F.tight,children:[J(X,{dimColor:!0,children:[B.t(`permission.alwaysAllow`),`: `]}),q(X,{color:o.suggestion,children:r})]}),J(Y,{marginTop:F.tight,flexDirection:`row`,gap:F.section,children:[q(I,{variant:`solid`,brackets:!0,color:`accent`,label:B.t(`permission.approve`),focused:s===0}),q(I,{variant:`solid`,brackets:!0,color:`red`,label:B.t(`permission.deny`),focused:s===1}),u&&q(I,{variant:`solid`,brackets:!0,color:`amber`,label:B.t(`permission.alwaysAllow`),focused:s===2})]})]})}function Ol({title:e,message:t,okLabel:n,onOk:r}){let i=Array.isArray(t)?t:[t];return Re({tabIndex:0,id:`alert-ok`,onAction:()=>(r(),!0),onEscape:()=>(r(),!0)}),j(`alert-dialog`,(e,t)=>t.return||t.escape?(r(),!0):!1),J(y,{header:q(p,{children:e}),footer:q(O,{items:[[`${T.enter}/${T.esc}`,B.t(`hint.close`)]]}),children:[q(Y,{marginTop:F.tight,flexDirection:`column`,children:i.map((e,t)=>q(X,{wrap:`truncate-end`,children:e===``?` `:e},t))}),q(Y,{marginTop:F.tight,children:q(I,{variant:`solid`,brackets:!0,color:`accent`,label:n??B.t(`common.okButton`),focused:!0})})]})}function kl({title:t,message:n,placeholder:r,initialValue:i=``,submitLabel:a,cancelLabel:o,columns:s=60,onSubmit:c,onCancel:l}){let[u,d]=K(i),[f,m]=K(i.length),[h,g]=K(`input`),_=n?Array.isArray(n)?n:[n]:[],v=(e,t)=>{d(e),m(t)};return j(`prompt-dialog`,(e,t)=>{if(t.escape){l();return}if(t.return&&h===`input`){u.trim()!==``&&g(`submit`);return}if(t.return){h===`submit`&&u.trim()!==``?c(u):l();return}if(t.tab||t.ctrl&&e===`n`){g(e=>e===`input`?`submit`:e===`submit`?`cancel`:`input`);return}if(t.leftArrow&&h!==`input`){g(e=>`submit`);return}if(t.rightArrow&&h!==`input`){g(e=>`cancel`);return}if(h!==`input`)return;if(e.length>1&&!t.ctrl&&!t.meta&&!t.return&&!t.escape&&!t.backspace&&!t.delete&&!t.tab&&!t.upArrow&&!t.downArrow&&!t.leftArrow&&!t.rightArrow){let t=Ze(e);t&&v(u.slice(0,f)+t+u.slice(f),f+t.length);return}if(t.leftArrow){let e=Ue.fromText(u,s,f).left();v(e.text,e.offset);return}if(t.rightArrow){let e=Ue.fromText(u,s,f).right();v(e.text,e.offset);return}let n={name:t.backspace?`backspace`:t.delete?`delete`:e||`unknown`,ctrl:t.ctrl??!1,shift:!1,alt:t.meta??!1,meta:t.meta??!1},r=Ie(Ue.fromText(u,s,f),n);if(r){if(r.action===`clear_text`){v(``,0);return}r.action===`submit`||r.action===`submit_force`||v(r.cursor.text,r.cursor.offset)}}),J(y,{header:q(p,{children:t??B.t(`prompt.defaultTitle`)}),footer:q(O,{items:[[T.enter,B.t(`hint.confirm`)],[T.esc,B.t(`hint.cancel`)]]}),children:[_.length>0&&q(Y,{marginTop:F.tight,flexDirection:`column`,children:_.map((e,t)=>q(X,{wrap:`truncate-end`,children:e===``?` `:e},t))}),q(Y,{marginTop:F.tight,flexDirection:`row`,children:q(e,{value:u,offset:f,columns:s,mode:`dialog`,placeholder:r,focused:h===`input`,physicalCursor:h===`input`})}),J(Y,{marginTop:F.tight,flexDirection:`row`,gap:F.section,children:[q(I,{variant:`solid`,brackets:!0,color:`accent`,label:a??B.t(`prompt.submitButton`),focused:h===`submit`,disabled:u.trim()===``}),q(I,{variant:`solid`,brackets:!0,color:`gray`,label:o??B.t(`common.genericCancelButton`),focused:h===`cancel`})]})]})}function Al(){return{toast:null,retryCountdown:null,errorRetry:null,providerUsage:null,notifications:[],paused:!1,pauseDialog:null,pausePending:null,pulseSurvey:null}}function jl(){let e=Pn(Al()),t,n={};return{store:e,reset(){e.setState(Al())},setNotify(e){t=e},setEffects(e){n=e},setProviderUsage(n){e.setState({providerUsage:n}),t?.()},setPausePending(n){e.setState({pausePending:n}),t?.()},setPaused(r){e.setState({paused:r}),r||n.drainQueueOnResume?.(),t?.()},setPulseSurvey(r){e.setState({pulseSurvey:r}),n.syncPulseSurveyRoute?.(r!==null),t?.()}}}function Ml(e,t){return{role:`history_capped`,removedCount:e,trigger:t}}const Nl=e=>{try{return JSON.stringify(e).length}catch{return 0}};function Pl(e,t=gn,n=hn){let r=e.filter(e=>e.role!==`history_capped`);if(r.length===0)return e;let i=0,a=null;r.length>t&&(i+=r.length-t,r.splice(0,i),a=`count`);let o=r.map(Nl),s=o.reduce((e,t)=>e+t,0);if(s>n){let e=0;for(;e<o.length-1&&s>n;)s-=o[e],e++,i++;r.splice(0,e),a=`bytes`}return i===0?e:[...r,Ml(i,a??`count`)]}function Fl(){let e=Pn({messages:[]}),t=t=>{e.setState({messages:Pl(t)})};return{store:e,append(n,r,i){t([...e.getState().messages,{...n,id:n.id??r,...i==null?{}:{seq:i}}])},appendMany(n,r){n.length!==0&&t([...e.getState().messages,...n.map(e=>({...e,id:e.id??r()}))])},prependMany(n){if(n.length===0)return;let r=e.getState();t([...n.map(e=>({...e})),...r.messages])},patchLast(n){let r=e.getState();if(r.messages.length===0)return;let i=r.messages[r.messages.length-1];t([...r.messages.slice(0,-1),{...i,...n}])},patchById(n,r){let i=e.getState(),a=i.messages.findIndex(e=>e.id===n);if(a===-1)return;let o=i.messages[a],s=[...i.messages];s[a]={...o,...r},t(s)},removeLast(){let n=e.getState();n.messages.length!==0&&t(n.messages.slice(0,-1))},removeById(n){let r=e.getState(),i=r.messages.findIndex(e=>e.id===n);if(i===-1)return;let a=[...r.messages];a.splice(i,1),t(a)},reset(){e.setState({messages:[]})}}}const Il=[{label:`Tool guidance`,lane:`stable`,priority:20},{label:`Environment`,lane:`stable`,priority:25},{label:`Memory index`,lane:`stable`,priority:35},{label:`Skill catalog`,lane:`stable`,priority:38},{label:`Lesson`,lane:`stable`,priority:40},{label:`Memory delta`,lane:`volatile`,priority:60},{label:`TODO reminder`,lane:`volatile`,priority:62}];function Ll(e){let t=Il.length,n=Math.round(e/t);return Il.map(e=>({label:e.label,lane:e.lane,estimatedTokens:n}))}function Rl(){let e=Pn({open:!1,conversationTurns:[],systemSections:[],modelName:``,contextWindow:0,contextPercent:0,totalUsed:0,free:0});return{store:e,toggle(t){e.setState({open:t??!e.getState().open})},reset(){e.setState({open:!1,conversationTurns:[],systemSections:[],modelName:``,contextWindow:0,contextPercent:0,totalUsed:0,free:0})},addTurn(t){let n=[...e.getState().conversationTurns,t];e.setState({conversationTurns:n.length>gn?n.slice(n.length-gn):n})},markTurns(t){let{turnIndex:n,...r}=t,i=e.getState().conversationTurns.map(e=>e.turnIndex===n?{...e,...r}:e);e.setState({conversationTurns:i})},setBudget(t){e.setState({modelName:t.modelName,contextWindow:t.contextWindow,contextPercent:t.contextPercent,totalUsed:t.totalUsed,free:t.free,systemSections:Ll(t.overheadTokens)})}}}const zl=kt(void 0),Bl=zl.Provider;function Vl(){let e=jt(zl);if(!e)throw Error(`useAppStoresContext must be used within <AppStoresProvider>`);return e}function Hl(){let{currentPath:e}=g();return e===`/`?`prompt`:e===`/home`?`home`:e===`/pane/delegates`||e===`/pane/delegates/output`?`background`:e===`/pane/edited-files`?`editedFiles`:e.startsWith(`/pane/edited-files/`)?`editedFileFull`:e===`/subagent`?`subagentContext`:e===`/pane/subagents`?`subagents`:e===`/pane/clipboard`?`clipboard`:e===`/pane/schedule`?`schedule`:e===`/pane/tasks`?`taskFocus`:e.startsWith(`/pane/tasks/`)?`taskDetail`:e===`/pane/draft`?`draft`:e===`/pane/queue`?`queue`:e.startsWith(`/pane/queue/`)?`queueEdit`:e===`/pane/shell`?`shell`:e===`/pane/sigil`?`sigilPane`:e===`/pane/perf`?`perf`:e===`/pane/cache`?`cacheStats`:e===`/pane/compaction-log`?`compactionLog`:e===`/pane/gallery`?`gallery`:e===`/pane/notifications`?`notifications`:e===`/pane/proxy`?`proxy`:e===`/pane/prompts`?`prompts`:e===`/pane/context`?`info`:(e.startsWith(`/dialog/`)||e.startsWith(`/viewer/`),`prompt`)}const Ul=`onA2uiAction.onAlertResolve.onBackToContextPane.onBackgroundApply.onBackgroundClose.onBackgroundDelete.onBackgroundKill.onBackgroundOutputClose.onBackgroundSwitch.onBackgroundViewOutput.onCacheDismiss.onCancelUpgrade.onCloseNotifications.onCompactionLogDismiss.onContextDismiss.onConfirmResolve.onCyclePermissionMode.onDelegateSupply.onDismissNotification.onDismissToast.onDraftDelete.onDraftDeleteMany.onDraftSave.onErrorRetryFocusChange.onExitSubagentContext.onFocusOwnerChange.onScrollActiveChange.onGalleryDismiss.onHistoryPush.onInfoDismiss.onInputAction.onInputResolve.onOnboardingResolve.onInterrupt.onKeybindingPanelDismiss.onMemoryDismiss.onPaneOwnsViewportChange.onPerfDismiss.onPerfRefresh.onPermissionDecision.onPopQueued.onPromptResolve.onProxyClear.onProxyTest.onProxyDismiss.onProxyOpenModal.onProxySubmitUrl.onProxyToggleEnabled.onPulseSurveyChange.onQuestionsResolve.onQueueDelete.onQueueEditText.onQueueMove.onQueueSendNow.onSelectResolve.onSessionSelect.onShellAbort.onShellAskAi.onShellCopyOutput.onShellDismiss.onShortcutsDialogDismiss.onSigilSelect.onSubmit.onToast.onToggleDelegates.onToggleDraftPane.onToggleEditedFiles.onToggleNotifications.onToggleQueuePane.onTogglePrompts.onToggleSchedule.onToggleSubagents.onUpgrade.onViewDetails.onWithdrawPending.onWithdrawSteer`.split(`.`);function Wl(e){let t={};for(let n of Ul)t[n]=e[n];return t}const Gl=kt(null),Kl=Gl.Provider;function ql(){let e=jt(Gl);if(!e)throw Error(`useAppCallbacks must be used within AppCallbacksProvider`);return e}function Jl(e){let{editedFilesLength:t,queuedItemsLength:n,subagentContext:r,backgroundOutput:i}=e,{onPaneOwnsViewportChange:a}=ql(),{currentPath:o}=g(),[s,c]=K(null),[l,u]=K(null),[d,f]=K(null),p=At(e=>{f(e),e?M()?.navigate(`/viewer/shell-output`):M()?.goBack()},[]),[m,h]=K(null),[_,v]=K(!1),[y,b]=K(!1),[x,S]=K(!1),[C,w]=K(!1),[T,E]=K(``),D=!!r||s!==null||!!i||l!=null,O=At(e=>{a?.(!0),c(e),M()?.navigate(`/pane/edited-files/${e}`)},[a]),ee=At(()=>{a?.(l!=null),c(null),M()?.goBack()},[a,l]),te=At(e=>{a?.(!0),u(e),M()?.navigate(`/pane/tasks/${e}`)},[a]),ne=At(()=>{a?.(s!==null),u(null),M()?.goBack()},[a,s]);return U(()=>{let e=o.startsWith(`/pane/edited-files/`)?s:null,t=o.startsWith(`/pane/tasks/`)?l:null;e!==s&&c(e),t!==l&&u(t),(e!==s||t!==l)&&a?.(e!==null||t!=null),m!==null&&o!==`/pane/queue/edit`&&(h(null),v(!1),b(!1)),d&&!o.startsWith(`/viewer/shell-output`)&&f(null)},[o,s,a,m,d,l]),U(()=>{s!==null&&s>=t&&(a?.(l!=null),c(null),M()?.goBack())},[s,t,l,a]),U(()=>{m!==null&&m>=n&&(h(null),v(!1),b(!1),o===`/pane/queue/edit`&&M()?.goBack())},[o,m,n]),{editedFileFullIndex:s,openEditedFileFull:O,closeEditedFileFull:ee,taskDetailTurn:l,openTaskDetail:te,closeTaskDetail:ne,shellFullOutput:d,setShellFullOutput:p,queueEditIndex:m,setQueueEditIndex:h,queueCloseConfirm:_,setQueueCloseConfirm:v,queueEscSuppress:y,setQueueEscSuppress:b,interruptConfirm:x,setInterruptConfirm:S,popQueuedConfirm:C,setPopQueuedConfirm:w,supplyDraft:T,setSupplyDraft:E,fullScreenPaneActive:D}}function Yl(){M()?.navigate(`/`,{reset:!0})}let Xl=null;function Zl(e){Xl=e}function Ql(){let e=Xl;return e?.hasSelection()?(e.clear(),!0):!1}function $l(e,t){let n=e.getState().offset;return e.subscribe(()=>{let r=e.getState().offset;r!==n&&(n=r,t())})}function eu(e){let{showHome:t,tasksLength:n,backgroundTasksLength:r,editedFilesLength:i,subagentsLength:a,draftsLength:o,draftOpen:c,queuedItemsLength:l,queueOpen:u,clipboardHasContent:f,shellExecutionRunning:p,routeDerivedOwner:m,currentPath:h,backgroundOutput:g,a2uiButtons:_,scrollOffset:v,editedFilesOpen:y,subagentsOpen:b,setTasksCollapsed:x,keybindingOverrides:S}=e,{onToggleDelegates:C,onToggleEditedFiles:w,onToggleSubagents:T,onToggleDraftPane:E,onToggleQueuePane:D,onShellAbort:O,onInterrupt:ee,onA2uiAction:te,onCyclePermissionMode:ne,onToggleNotifications:k,onSubmit:ie}=ql(),A=At(()=>{let e=M();e&&e.currentPath!==`/`&&e.navigate(`/`,{reset:!0})},[]),ae=At(e=>{let o=M();if(!o)return!1;let s=[{path:`/`,activate:()=>A()},...t?[{path:`/home`,activate:()=>o.navigate(`/home`,{replace:!0})}]:[],...n>0?[{path:`/pane/tasks`,activate:()=>o.navigate(`/pane/tasks`,{replace:!0})}]:[],...r>0?[{path:`/pane/delegates`,activate:()=>{C?.()}}]:[],...i>0?[{path:`/pane/edited-files`,activate:()=>{w?.()}}]:[],...a>0?[{path:`/pane/subagents`,activate:()=>{T?.()}}]:[],...f?[{path:`/pane/clipboard`,activate:()=>{o.navigate(`/pane/clipboard`,{replace:!0})}}]:[]];return s.length<=1?!1:(s[(Math.max(0,s.findIndex(e=>o.currentPath===e.path||o.currentPath.startsWith(e.path+`/`)))+e+s.length)%s.length]?.activate(),!0)},[r,A,c,o,i,C,E,w,D,T,u,l,t,a,n,f]);ht(`app-global-prelude`,(e,t)=>t.ctrl&&e===`c`?p?(O?.(),!0):(ee?.(),!0):!1),d(`selection-escape`,(e,t)=>!t.escape||t.ctrl||t.meta||t.shift?!1:Ql()),_t(`app-prompt-global`,(e,t)=>{if(t.tab&&!t.ctrl&&!t.meta&&!t.shift)return h.startsWith(`/dialog/`)||h.startsWith(`/viewer/`)||Ur(h)||![`prompt`,`home`,`taskFocus`,`background`,`editedFiles`,`subagents`,`schedule`,`draft`,`queue`].includes(m)||h===`/pane/delegates`&&g?!1:ae(t.shift?-1:1);if(v===0&&_&&_.length>0&&e>=`1`&&e<=`9`&&!t.ctrl&&!t.meta){let t=_.find(t=>t.key===e);if(t&&te)return te(t.componentId,t.action,t.payload),!0}if(h===`/`&&t.ctrl&&e===`k`)return!1;let r=pe(re,m,e,t,S);if(r===`smart-close`)return h===`/pane/tasks`?(Yl(),!0):y?(w?.(),!0):b?(T?.(),!0):(n>0?(x(()=>!1),M()?.navigate(`/pane/tasks`,{replace:!0})):x(e=>!e),!0);let i={"cycle-permission-mode":()=>{ne?.()},"toggle-notifications":()=>{k?.()},"toggle-edited-files":()=>{w?.()},"toggle-subagents":()=>{T?.()},"toggle-delegates":()=>{C?.()},"toggle-draft-pane":()=>{E?.()},"toggle-queue-pane":()=>{D?.()},"open-keybinding-panel":()=>{ie?.(`/keybindings`,`send`)}};return r&&i[r]?(i[r](),!0):!1});let j=s();Lt((e,t)=>{j.dispatch(e,t)})}function tu(e){let t=e>=60,n=e>=76,r=e>=100;return{modelName:!0,occupancyBar:!0,hintText:!0,permissionMode:t,perfIndicator:t,notificationBell:t,backgroundTaskIndicator:t,scheduleIndicator:t,serviceIndicator:t,cost:n,providerUsage:n,language:n,pluginStatusItems:r,liveClock:r}}const nu={narrow:0,medium:1,low:2};function ru(e){return e.map((e,t)=>({entry:e,index:t})).sort((e,t)=>{let n=nu[e.entry.tier]-nu[t.entry.tier];if(n!==0)return n;if(e.entry.isHost!==t.entry.isHost)return e.entry.isHost?-1:1;let r=(e.entry.order??0)-(t.entry.order??0);return r===0?e.index-t.index:r}).map(e=>e.entry)}const iu=new Map;function au(e){let t=iu.get(e);return t||(t={consecutiveSlowCalls:0,tripped:!1},iu.set(e,t)),t}function ou(){iu.clear()}function su(e,t){let n=au(e.id);if(n.tripped)return null;let r=Date.now(),i=null;try{i=e.render(t)}catch{i=null}if(Date.now()-r>5){if(n.consecutiveSlowCalls+=1,n.consecutiveSlowCalls>=3)return n.tripped=!0,null}else n.consecutiveSlowCalls=0;return i}function cu(e){let t;for(let n of e){if(n.tickMs===void 0)continue;let e=Math.max(1e3,n.tickMs);(t===void 0||e<t)&&(t=e)}return t}function lu(e){let{columns:t,permissionMode:n,cost:r,providerUsage:i,pluginStatusItems:a,statusWidgets:o,modelName:s}=e,[c,l]=K(0);U(()=>{if(!i)return;let e=setInterval(()=>l(e=>e+1),3e4);return()=>clearInterval(e)},[i]);let[u,d]=K(0);U(()=>{let e=cu(o);if(e===void 0)return;let t=setInterval(()=>d(e=>e+1),e);return()=>clearInterval(t)},[o]);let f=W(()=>tu(t),[t]);return{footerVisible:f,badgeEntries:W(()=>{let e=[];if(f.permissionMode&&n&&e.push({id:`host:permission-mode`,text:B.t(`pref.permModeLabel`,{context:n}),color:n===`bypass`?`warning`:`inactive`,separator:`dot`,tier:`narrow`,isHost:!0}),f.cost&&r&&e.push({id:`host:cost`,text:r,separator:`space`,tier:`medium`,isHost:!0}),f.providerUsage&&i){let t=Date.now(),n=An(i,t);n&&e.push({id:`host:provider-usage`,text:n,color:Nn(i.status,i.limitType,i.usedPercent,i.resetsAt,t,i.overageStatus),separator:`dot`,tier:`medium`,isHost:!0})}if(f.pluginStatusItems&&a)for(let t of a)e.push({id:t.id,text:t.text,separator:`space`,tier:`low`,isHost:!1});if(f.pluginStatusItems&&o.length>0){let n={nowMs:Date.now(),model:s,providerUsage:i,columns:t};for(let t of o){let r=su(t,n);r&&e.push({id:t.id,text:r.text,color:r.color,separator:`space`,tier:`low`,isHost:!1,order:t.order})}}return ru(e)},[f,n,r,i,c,a,o,u,s,t])}}function uu(e){let{shellExecution:t,subagentContext:n,agentProcessing:r,queuedItems:i,pendingEcho:a,pendingSteers:o,onRequestPopQueuedConfirm:s}=e,{onExitSubagentContext:c,onPopQueued:l,onInterrupt:u,onWithdrawPending:d,onWithdrawSteer:f}=ql();return At(()=>{if(!t){if(n){c?.();return}if(r){if(i.length>0){s?s():l?.();return}if(o&&o.length>0){let e=o[o.length-1];e&&f?.(e.id);return}if(a){d?.(a.text,a.mode);return}u?.();return}}},[t,n,c,r,i,a,o,l,u,d,f,s])}let du=null;function fu(e){du=e}function pu(){return du}function mu(){let[e,t]=K(null),n=G(null),r=At(e=>{n.current=e,t(e),!e&&M()?.currentPath===`/pane/sigil`&&M()?.goBack()},[]),i=G(null),[a,o]=K(null),s=G(!1),[c,l]=K(null),u=G(null),d=At((e,t,n)=>{i.current=n,r({sigil:e,query:t,mode:`sigil`}),M()?.navigate(`/pane/sigil`)},[]),f=At(()=>{if(n.current?.mode===`history`){r(null);return}i.current=null,r({sigil:`#`,query:``,mode:`history`}),M()?.navigate(`/pane/sigil`)},[]);return U(()=>(fu(f),()=>fu(null)),[f]),{sigilState:e,setSigilState:r,sigilApplyRef:i,hadSigilFocusRef:s,chipContentViewerRequest:a,pasteContent:c,handleSigilTrigger:d,handleHistorySearch:f,handleChipReopen:At((e,n,r)=>{i.current={select:r.select,cancel:()=>r.cancel()},t({sigil:`@`,query:``}),M()?.navigate(`/pane/sigil`)},[]),handleChipViewPaste:At((e,t)=>{Wr(M(),Vr,!0),o({label:e,content:t,onDismiss:()=>{o(null),Wr(M(),Vr,!1)}})},[]),handleSigilClose:At(()=>{r(null)},[]),handlePasteConfirmRequest:At((e,t)=>{u.current=t,l(e),Wr(M(),zr,!0)},[]),handlePasteConfirm:At(()=>{u.current?.confirm(),u.current=null,l(null),Wr(M(),zr,!1)},[]),handlePasteCancel:At(()=>{u.current?.cancel(),u.current=null,l(null),Wr(M(),zr,!1)},[])}}function hu(e){let{sigilState:t,setSigilState:n,sigilApplyRef:r,hadSigilFocusRef:i,focusOwner:a,preempted:o}=e;U(()=>{if(!t){i.current=!1;return}if(a===`sigilPane`&&!o){i.current=!0;return}i.current&&=(n(null),r.current?.cancel(!1),!1)},[t,a,o])}function gu(){let e=Pn({budget:null});return{store:e,setBudget(t){e.setState({budget:t})},reset(){e.setState({budget:null})}}}function _u(e,t){return e.toolCallId&&t.toolCallId&&e.toolCallId===t.toolCallId?{...e,...t}:{...e,...t,oldContent:e.oldContent??t.oldContent,newContent:t.newContent??e.newContent,addedLines:e.addedLines+t.addedLines,removedLines:e.removedLines+t.removedLines,timestamp:Math.max(e.timestamp,t.timestamp),turnId:t.turnId??e.turnId,toolCallId:t.toolCallId??e.toolCallId}}function vu(e){let t=e.split(`/`);return t.length<=3?e:`…/${t.slice(-2).join(`/`)}`}function yu(e){switch(e){case`edit`:return`~`;case`write`:return`+`;case`delete`:return`-`}}function bu(e,t){switch(e){case`edit`:return t.accent;case`write`:return t.success;case`delete`:return t.error}}function xu({files:e,focused:t,onDismiss:n,onOpenFileFull:r,fullOpenIndex:i=null,rows:a=24}){let o=h(),[s,c]=$i(`editedFiles`,e.length),l=G(0);if(j(`edited-files-pane`,(t,a)=>a.escape?i===null?(M()?.navigate(`/`,{reset:!0}),n?.(),!0):!0:b(`list-nav-up`,t,a,`editedFiles`)?(c(e=>Math.max(0,e-1)),!0):b(`list-nav-down`,t,a,`editedFiles`)?(c(t=>Math.min(e.length-1,t+1)),!0):a.return?(r?.(s),!0):!1,{isActive:t}),e.length===0)return null;let u=e.reduce((e,t)=>e+t.addedLines,0),d=e.reduce((e,t)=>e+t.removedLines,0),f=Math.min(s,e.length-1),p=pt(e,f,ze(e.length,a,3),l.current);return l.current=p.scrollTop,J(Y,{flexDirection:`column`,marginTop:F.tight,children:[J(Y,{children:[q(X,{color:o.special,children:`▸ `}),q(X,{color:t?o.text:o.inactive,children:B.t(`panelTitle.editedFilesTitle`)}),J(D,{type:`secondary`,children:[` `,B.t(`diff.fileCountLabel`,{count:e.length})]}),u>0&&J(X,{color:o.diffAdd,children:[` +`,u]}),d>0&&J(X,{color:o.diffRemove,children:[` -`,d]}),!t&&J(D,{type:`secondary`,dim:!0,children:[` `,A(`v`)]}),t&&q(Y,{marginLeft:F.tight,children:q(O,{dim:!0,items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[T.enter,B.t(`hint.view`)],[T.esc,B.t(`hint.close`)],[T.tab,B.t(`hint.tabFocus`)]]})})]}),J(Y,{marginLeft:F.section,flexDirection:`column`,children:[p.hasMoreAbove&&q(X,{dimColor:!0,children:B.t(`scroll.above`,{n:1})}),p.rows.map((e,n)=>{let r=p.scrollTop+n===f,i=r&&t?o.selection:o.inactive;return J(Y,{flexDirection:`row`,children:[q(X,{color:i,children:r?`${R.pointer} `:` `}),J(X,{color:bu(e.operation,o),children:[yu(e.operation),` `]}),q(X,{color:i,children:vu(e.path)}),e.addedLines>0&&J(X,{color:o.diffAdd,children:[` +`,e.addedLines]}),e.removedLines>0&&J(X,{color:o.diffRemove,children:[` -`,e.removedLines]})]},`${e.path}-${e.timestamp}`)}),p.hasMoreBelow&&q(X,{dimColor:!0,children:B.t(`scroll.below`,{n:1})})]})]})}function Su(e={}){return{tasks:[],tasksTitle:void 0,turnBoundaries:[],editedFiles:[],backgroundTasks:[],subagentsAccum:new Map,scheduleTasks:[],drafts:e.drafts??[],queued:[],pendingPermission:null,clipboardChars:0,clipboardText:``,clipboardFailed:!1,backgroundOutput:null,subagentContext:null,forcedUpgrade:null,pendingEcho:null,pendingSteers:[],modelName:e.modelName??``,pluginStatusItems:[],statusWidgets:[],needsSetup:e.needsSetup??!1,permissionMode:e.permissionMode??`auto`,commands:e.commands??[],paneOwnsViewportFlag:!1,shellExecution:null,recentMentions:e.recentMentions??[],sessionList:[],sessionTitle:``}}function Cu(e={}){let t=Pn(Su(e)),n,r={},i=()=>n?.();return{store:t,reset(){t.setState(Su(e))},setNotify(e){n=e},setEffects(e){r=e},actions:{setTasks(e,n){t.setState({tasks:e}),t.setState({tasksTitle:n}),i()},setEditedFiles(e){t.setState({editedFiles:e.sort((e,t)=>t.timestamp-e.timestamp)}),i()},addEditedFile(e){let n=[...t.getState().editedFiles],r=n.findIndex(t=>t.path===e.path);r>=0?n[r]=_u(n[r],e):n.push(e),n.sort((e,t)=>t.timestamp-e.timestamp),t.setState({editedFiles:n}),i()},setBackgroundTasks(e){if(t.setState({backgroundTasks:e}),e.some(e=>e.type===`agent-session`)){let n=new Map(t.getState().subagentsAccum);for(let t of e)t.type===`agent-session`&&n.set(t.id,t);t.setState({subagentsAccum:n})}i()},setTurnBoundaries(e){t.setState({turnBoundaries:[...e]})},addTurnBoundary(e){t.setState({turnBoundaries:[...t.getState().turnBoundaries,e]})},setDrafts(e){t.setState({drafts:e}),i()},setScheduleTasks(e){t.setState({scheduleTasks:e}),i()},setRecentMentions(e){t.setState({recentMentions:e}),i()},setModelName(e){t.setState({modelName:e}),i()},setSessionList(e){t.setState({sessionList:e}),i()},setSessionTitle(e){t.setState({sessionTitle:e}),i()},setNeedsSetup(e){t.getState().needsSetup!==e&&(t.setState({needsSetup:e}),i())},setPermissionMode(e){t.setState({permissionMode:e}),i()},setForcedUpgrade(e){t.setState({forcedUpgrade:e}),r.syncForcedUpgradeRoute?.(!!e),i()},setPluginStatusItems(e){t.setState({pluginStatusItems:e}),r.registerStatusItems?.(e),i()},setBackgroundOutput(e){t.setState({backgroundOutput:e}),r.backgroundOutputRoute?.(e!==null),r.flushScrollbackIfIdle?.(),i()}}}}function wu(){let e=Pn({memory:void 0,memoryHistory:[],notify:void 0,indicatorLevel:`healthy`,pluginMetrics:[]});return{store:e,reset(){e.setState({memory:void 0,memoryHistory:[],notify:void 0,indicatorLevel:`healthy`,pluginMetrics:[]})},setMemory(t){let n=[...e.getState().memoryHistory,t.heapUsed].slice(-32);e.setState({memory:t,memoryHistory:n})},setNotify(t){e.setState({notify:t})},setIndicatorLevel(t){e.setState({indicatorLevel:t})},setPluginMetrics(t){e.setState({pluginMetrics:t})}}}function Tu(){let e=Pn({view:null});return{store:e,setView(t){e.setState({view:t})}}}function Eu(){return{view:{configPath:`~/.otto/config.json`}}}function Du(){let e=Pn(Eu());return{store:e,setView(t){e.setState({view:t})}}}function Ou(e=Date.now){let t=Pn({entries:[]}),n=1,r=r=>{let i=[{...r,id:n++,timestamp:e()},...t.getState().entries].slice(0,20);t.setState({entries:i})};return{store:t,recordCompaction(e,t,n){r({kind:`compact`,before:e,after:t,summary:n})},recordPrune(e,t){r({kind:`prune`,tokensSaved:e,prunedCount:t})},recordHistoryCapped(e){r({kind:`history_capped`,removedCount:e})}}}const ku={categoryIndex:0,itemIndex:0,variantIndex:0};function Au(){let e=Pn({...ku});return{store:e,reset(){e.setState({...ku})},setCategoryIndex(t){e.setState({categoryIndex:t,itemIndex:0,variantIndex:0})},setItemIndex(t){e.setState({itemIndex:t,variantIndex:0})},setVariantIndex(t){e.setState({variantIndex:t})}}}function ju(e){let{taskStore:t,budgetStore:n,perfStore:r,cacheStore:i,proxyStore:a,compactionLogStore:o,galleryStore:s,streamStore:c}=e;return{taskStore:W(()=>t??Cu(),[t]),budgetStore:W(()=>n??gu(),[n]),perfStore:W(()=>r??wu(),[r]),cacheStore:W(()=>i??Tu(),[i]),proxyStore:W(()=>a??Du(),[a]),compactionLogStore:W(()=>o??Ou(),[o]),galleryStore:W(()=>s??Au(),[s]),streamStore:W(()=>c??rl(),[c])}}const Mu=[{en:`Use ↑/↓ for input history; Ctrl+R opens fuzzy history search.`,zh:`输入框里按 ↑/↓ 浏览历史输入,Ctrl+R 模糊搜索历史。`},{en:`Use /feedback to report a bug or request a feature via GitHub.`,zh:`输入 /feedback 可通过 GitHub 提交 bug 或功能建议。`},{en:`During a run, press Esc on an empty prompt to interrupt and steer.`,zh:`运行时输入框为空按 Esc 可中断,otto 停下来让你接管方向。`},{en:`During a run, Shift+Enter queues a follow-up; Ctrl+Q manages it.`,zh:`运行中按 Shift+Enter 排队追加消息(本回合后执行),Ctrl+Q 管理队列。`},{en:`While otto works, plain Enter steers the current turn.`,zh:`otto 工作中按普通 Enter 可注入引导消息到当前回合。`},{en:`Type /model then Tab to pick a model and switch mid-session.`,zh:`输入 /model 后按 Tab 自动补全可用模型,会话中途即可切换。`},{en:`Use /install for skills/plugins/MCP; manage them in /extension.`,zh:`/install 从文件或 URL 安装技能/插件/MCP,/extension 面板管理。`},{en:`Reasoning streams inline; /effort changes its intensity.`,zh:`推理过程实时内联在对话流中生成,/effort 调节推理强度。`},{en:`Type /open then Tab to browse and open files in the viewer.`,zh:`输入 /open 按 Tab 浏览目录,在内置查看器打开文件。`},{en:`Ctrl+S saves the current input as a draft; Ctrl+O lists and loads drafts.`,zh:`Ctrl+S 把当前输入存为草稿,Ctrl+O 打开草稿面板选择载入。`},{en:`Ctrl+R or /history searches session and shell history.`,zh:`Ctrl+R(或 /history)搜索会话与 shell 历史,选中即回填。`},{en:`Large pastes become chips; press Enter on a chip to view it.`,zh:`大段粘贴自动折叠成占位标记,光标停在标记上按 Enter 查看原文。`},{en:`Use /compact to free context; /compact log shows pruned items.`,zh:`长会话用 /compact 释放上下文,/compact log 查看裁剪明细。`},{en:"Run `otto doctor` in another terminal for a full health check.",zh:"在另一个终端运行 `otto doctor` 做完整环境健康诊断。"},{en:`Otto can fall back to another model after failure or rate limits.`,zh:`当前模型失败或限流时,otto 自动回退到已配置的其他模型。`},{en:`Use /schedule add with cron syntax for recurring tasks.`,zh:`/schedule add 用 cron 表达式设定期任务(如日报)。`},{en:`Use /queue to reorder or remove queued follow-ups.`,zh:`/queue 面板管理排队消息,move 调顺序,remove 删除。`},{en:`Tab completes slash commands and arguments: /model gpt<Tab>.`,zh:`Tab 补全斜杠命令及其参数(试试 /model gpt<Tab>)。`},{en:`Ctrl+P opens Delegates; press Enter to view job output.`,zh:`Ctrl+P 打开委派面板查看后台任务,Enter 实时查看其输出。`},{en:`Use /job <directive> to run work in a background worktree.`,zh:`/job <指令> 在后台 worktree 跑任务,不阻塞当前会话。`},{en:`Language, model, and permission mode persist across sessions.`,zh:`语言、模型、权限模式跨会话自动持久化。`},{en:`Ctrl+V lists edited files; Enter opens a full-screen diff.`,zh:`Ctrl+V 列出本会话修改的文件及 +/- 统计,Enter 打开全屏 diff。`},{en:`Scroll with Alt+↑/↓ or PgUp/PgDn; press / in review to search.`,zh:`Alt+↑/↓ 或 PageUp/PageDown 滚动对话流,回看态按 / 搜索。`},{en:`Use /perf for memory and rendering health; /diagnose for failures.`,zh:`/perf 查看内存占用与渲染健康度,/diagnose 汇总反复出现的失败并给改进建议。`},{en:`Use /preference to switch theme or language.`,zh:`/preference theme 切 dark/light/system 主题,/preference lang 切中英文。`},{en:`Wheel scrolling works by default; drag to select, release to copy.`,zh:`滚轮/触控板开箱即用,拖拽即选中、松手自动复制。`},{en:`Use /upgrade for otto updates; /upgrade --check checks extensions.`,zh:`/upgrade 检查 otto 更新,/upgrade --check 检查扩展更新。`},{en:`Use /resume for recent sessions; /pin keeps favorites on top.`,zh:`/resume 切换最近会话,/pin 把常用会话置顶。`}];function Nu({active:e,resetKey:t,isZh:n,delayMs:r=6e4,rotateMs:i=2e4}){let[a,o]=K(!1),[s,c]=K(()=>Pu()),l=G(e);l.current=e;let u=G(0),[d,f]=K(0);if(se(`idle-tip-activity`,()=>{u.current+=1,f(u.current)},{isActive:e}),U(()=>{if(!e){o(!1);return}o(!1);let t=setTimeout(()=>{l.current&&o(!0)},r);return()=>{clearTimeout(t)}},[e,t,r,d]),U(()=>{if(!a)return;let e=setInterval(()=>{c(e=>(e+1)%Mu.length)},i);return()=>clearInterval(e)},[a,i]),!e||!a)return null;let p=Mu[s%Mu.length];return p?n?p.zh:p.en:null}function Pu(){let e=new Date,t=`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`,n=0;for(let e=0;e<t.length;e++)n=(n<<5)-n+t.charCodeAt(e)|0;return Math.abs(n)%Mu.length}function Fu(){return q(Y,{children:q(X,{color:h().warning,children:`🕶 ${B.t(`welcome.shadowChip`)}`})})}function Iu(){let e=h();return J(Y,{flexDirection:`column`,marginBottom:1,children:[q(X,{bold:!0,color:e.warning,children:`🕶 ${B.t(`welcome.shadowBannerTitle`)}`}),q(X,{color:e.suggestion,children:B.t(`welcome.shadowGuarantee`)}),J(Y,{marginTop:1,flexDirection:`column`,children:[q(X,{color:e.inactive,children:B.t(`welcome.shadowNotGuaranteedTitle`)}),q(X,{color:e.inactive,children:` • ${B.t(`welcome.shadowNg1`)}`}),q(X,{color:e.inactive,children:` • ${B.t(`welcome.shadowNg2`)}`}),q(X,{color:e.inactive,children:` • ${B.t(`welcome.shadowNg3`)}`}),q(X,{color:e.inactive,children:` • ${B.t(`welcome.shadowNg4`)}`})]})]})}const Lu=[`#E06C75`,`#D19A66`,`#E5C07B`,`#98C379`,`#61AFEF`,`#C678DD`],Ru=[`#B5403A`,`#B45F1F`,`#96740F`,`#4E7A34`,`#2364A8`,`#7B4FC4`];function zu(e){let t=2*e;return 375+t+188+t}function Bu(e){return 2*e}function Vu(e,t){return Math.min(t,Math.floor(e/2)+1)}function Hu(e,t){let n=Bu(t),r=e%zu(t);if(r<375)return{phase:`brand`,progress:0,t:r};let i=r-375;if(i<n)return{phase:`entering`,progress:Vu(i,t),t:i};let a=i-n;if(a<188)return{phase:`hold`,progress:t,t:a};let o=a-188;return o<n?{phase:`exiting`,progress:Vu(o,t),t:o}:{phase:`brand`,progress:0,t:r}}function Uu(e){let t=e%16;return t<=8?t/8:(16-t)/8}function Wu(e){return Math.floor(e/3)%Lu.length}function Gu(e,t,n){let r=n===`light`?Ru:Lu,i=Wu(t),a=[];for(let t=0;t<e;t++)a.push(r[(t+i)%r.length]);return a}function Ku(e,t){let n=parseInt(e.slice(1),16),r=n>>16&255,i=n>>8&255,a=n&255,o=e=>Math.round(e+(255-e)*t),s=e=>e.toString(16).padStart(2,`0`).toUpperCase();return`#${s(o(r))}${s(o(i))}${s(o(a))}`}function qu(e,t,n,r,i,a,o){let s=i===`light`?Ru:Lu,c=a.phase===`hold`?Uu(a.t):0,l=[];for(let i=0;i<e.length;i++){let u=a.phase===`hold`||a.phase===`entering`&&i<a.progress||a.phase===`exiting`&&i>=a.progress,d=Math.abs(i-t)<=n,f;if(u){let e=s[(i+r)%s.length];f=Ku(e,d?.5+.25*c:.5*c)}else f=d?o.brandShimmer:o.brand;let p=l[l.length-1];p&&p.color===f?p.text+=e[i]:l.push({text:e[i],color:f})}return l}const Ju=[`✦`,`✧`,`·`,`⋆`],Yu=[`~`,`°`,`·`,`˘`,`∼`],Xu=[`▄▀▀▄ ▀█▀ ▀█▀ ▄▀▀▄`,`▀▄▄▀ █ █ ▀▄▄▀`],Zu=[{left:2,phase:0},{left:8,phase:11},{left:13,phase:22}],Qu=[{left:1,phase:16}],$u=[{left:1,phase:0},{left:5,phase:10},{left:9,phase:20},{left:14,phase:30}],ed=[{left:3,phase:15},{left:10,phase:35}];function td(e,t){let n=(e+t)%32,r=n<=16?n/16:(32-n)/16;return r<.15?0:r<.5?1:r<.85?2:3}function nd(e,t){let n=(e+t)%70,r=(Math.sin(n/70*Math.PI*2)+1)/2;return r<.1?0:r<.4?1:r<.75?2:3}function rd(e,t){return Yu[Math.floor((e+t)/8)%Yu.length]}function id({isNight:e=!1}){let t=h(),{resolvedTheme:n}=C(),[r,i]=V.useState(0),a=je();Me(80,i);let o=e&&!a,s=!e&&!a,c=a?null:Hu(r,Xu[0].length),l=Wu(r),u={brand:t.brand,brandShimmer:t.brandShimmer},d=e=>e===1?t.accentDim:e===3?t.accentBright:t.accent,f=(e,t,n)=>{let i=td(r,e.phase);return i===0?null:q(Y,{position:`absolute`,top:t,left:e.left,children:q(X,{color:d(i),children:Ju[n%Ju.length]})},`${t}-${e.left}`)},p=(e,t,n)=>{let i=nd(r,e.phase);return i===0?null:q(Y,{position:`absolute`,top:t,left:e.left,children:q(X,{color:d(i),children:rd(r,e.phase)})},`ripple-${n}`)};return J(Y,{position:`relative`,flexDirection:`column`,children:[Xu.map((e,i)=>{let a=Xc(r+i*3,e.length);return q(Y,{flexDirection:`row`,children:c&&c.phase!==`brand`?qu(e,a,2,l,n,c,u).map((e,t)=>q(X,{bold:!0,color:e.color,children:e.text},t)):Yc(e,a,2).map((e,n)=>q(X,{bold:!0,color:e.bright?t.brandShimmer:t.brand,children:e.text},n))},i)}),o&&Zu.map((e,t)=>f(e,-1,t)),o&&Qu.map((e,t)=>f(e,Xu.length,t)),s&&$u.map((e,t)=>p(e,-1,t)),s&&ed.map((e,t)=>p(e,Xu.length,t))]})}const ad=[`provider`,`authentication`,`model`],od={provider:{titleKey:`recovery.titleProvider`,ctaKey:`recovery.ctaProvider`,hintKey:`recovery.hintProvider`},authentication:{titleKey:`recovery.titleAuth`,ctaKey:`recovery.ctaAuth`,hintKey:`recovery.hintAuth`},model:{titleKey:`recovery.titleModel`,ctaKey:`recovery.ctaModel`,hintKey:`recovery.hintModel`}};function sd(e,t){if(e===`ready`||e===`first-prompt`)return null;let n=od[e],r=ad.indexOf(e)+1,i=t<80;return{titleKey:n.titleKey,ctaKey:n.ctaKey,...i?{}:{hintKey:n.hintKey},step:r,totalSteps:ad.length}}function cd({version:e=`0.1.0`,buildId:t,cwd:n,width:r,nickname:i,updateAvailable:a,weather:o,ftueStage:s,shadow:c=!1}){let l=h(),u=n?n.replace(process.env.HOME??`~`,`~`):void 0,d=r??process.stdout.columns??80,f=d>=60,p=V.useMemo(()=>{let e=new Date().getHours();return e<5?`late`:e<9?`earlyMorning`:e<12?`morning`:e<18?`afternoon`:e<22?`evening`:`night`},[]),m=p===`night`||p===`late`,[g]=V.useState(()=>{let e=new Date,t=B.language===`zh`?[`日`,`一`,`二`,`三`,`四`,`五`,`六`]:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],n=t[e.getDay()]??t[0],r=i?B.language===`zh`?`,${i}`:`, ${i}`:``;return B.t(`welcome.greeting`,{context:p,wday:n,who:r})}),_=g,v=B.t(`welcome.version`),y=B.t(`welcome.workspace`),b=Math.max(it(v),it(y))+4,x=s?sd(s,d):null;return q(Y,{flexDirection:`column`,children:J(Y,{flexDirection:`column`,paddingX:F.tight,paddingTop:F.section,...Ee,borderColor:l.panelBorder,children:[f&&J(Y,{marginBottom:F.tight,flexDirection:`row`,children:[q(id,{isNight:m}),J(Y,{flexDirection:`column`,marginLeft:F.loose,children:[J(Y,{flexDirection:`row`,children:[q(D,{type:`secondary`,children:gt(v,b)}),J(D,{type:`secondary`,children:[`v`,e]}),t!=null&&J(D,{type:`secondary`,dim:!0,children:[` `,`(build `,t,`)`]}),a&&a.newer&&J(X,{color:a.forced?l.warning:l.accent,children:[` `,a.forced?B.t(`update.forcedBanner`,{latest:a.latest}):B.t(`update.availableBanner`,{latest:a.latest})]})]}),u&&J(Y,{flexDirection:`row`,children:[q(D,{type:`secondary`,children:gt(y,b)}),q(D,{type:`secondary`,children:u})]})]})]}),!f&&J(Y,{flexDirection:`column`,marginBottom:F.tight,children:[J(Y,{flexDirection:`row`,children:[Yc(`otto`,1).map((e,t)=>q(X,{bold:!0,color:e.bright?l.brandShimmer:l.brand,children:e.text},t)),q(D,{type:`secondary`,children:` ${gt(v,b)}`}),J(D,{type:`secondary`,children:[`v`,e]}),t!=null&&J(D,{type:`secondary`,dim:!0,children:[` `,`(build `,t,`)`]})]}),u&&J(Y,{flexDirection:`row`,children:[q(D,{type:`secondary`,children:` ${gt(y,b)}`}),q(D,{type:`secondary`,children:u})]})]}),q(Y,{marginBottom:F.tight,children:i&&_.includes(i)?J(X,{color:l.text,bold:!0,children:[_.slice(0,_.indexOf(i)),q(X,{color:l.accent,children:i}),_.slice(_.indexOf(i)+i.length)]}):q(X,{color:l.text,bold:!0,children:_})}),x&&J(Y,{flexDirection:`column`,marginBottom:F.tight,children:[J(Y,{children:[q(X,{color:l.warning,bold:!0,children:B.t(x.titleKey)}),q(D,{type:`secondary`,children:` ${x.step}/${x.totalSteps}`})]}),x.hintKey&&q(D,{type:`secondary`,children:B.t(x.hintKey)}),q(X,{color:l.accent,children:B.t(x.ctaKey)})]}),c&&q(Iu,{}),o&&J(Y,{marginBottom:F.tight,children:[J(X,{color:l.accent,children:[o.condition,` `,o.temp,`°C`]}),J(D,{type:`secondary`,children:[` `,o.location]})]})]})})}function ld(e,t){let n=aa();U(()=>{if(n)return n.registerWheel(e)},[n,...t])}function ud({title:e,status:t,messages:n,streamText:r=``,rows:i=24,columns:a=80,onDismiss:o}){let s=h(),c=yt();j(`subagent-context-view`,(e,t)=>t.escape?(o?.(),!0):t.upArrow?(p(e=>x(e+1)),!0):t.downArrow?(p(e=>x(e-1)),!0):t.pageUp?(p(e=>x(e+v)),!0):t.pageDown?(p(e=>x(e-v)),!0):e===`g`&&!t.ctrl&&!t.meta?(p(b),!0):e===`G`&&!t.ctrl&&!t.meta?(p(0),!0):!1,{isActive:c?c.currentPath===`/subagent`:!0});let l=[];for(let e of n){let t=$s(e,a);t.length>0&&l.push(t)}let d=[];for(let e=0;e<l.length;e++)e>0&&d.push(``),d.push(...l[e]);let[f,p]=K(0),m=f===0,g=Jc(r,a-fe.borderInset,3);if(m&&g.length>0){d.length>0&&d.push(``),d.push(`⏺ assistant (streaming)`);for(let e of g)d.push(` ${e}`)}let _=u(i),v=Math.max(1,_-7),b=Math.max(0,d.length-v),x=e=>Math.min(b,Math.max(0,e)),S=b-x(f),C=d.slice(S,S+v);return ld(e=>p(t=>x(t+e*3)),[b]),J(y,{maxHeight:_,header:J(Y,{flexDirection:`column`,children:[q(X,{color:s.secondary,italic:!0,children:B.t(`subagent.header`,{title:e,status:t})}),q(X,{children:` `})]}),footer:q(O,{items:[...b>0?[[`${T.up}${T.down}`,B.t(`hint.scroll`)]]:[],[T.esc,B.t(`hint.back`)]]}),children:[q(Y,{height:1,children:S>0&&q(D,{type:`secondary`,dim:!0,children:B.t(`subagent.contextEarlierLines`,{n:S})})}),q(Y,{flexDirection:`column`,children:C.map((e,t)=>q(X,{children:e},`${S+t}`))})]})}const dd=[{thresholdSec:0,stage:{labelKey:`analyze`,capPercent:30}},{thresholdSec:3,stage:{labelKey:`summarize`,capPercent:80}},{thresholdSec:8,stage:{labelKey:`finalize`,capPercent:92}}];function fd(e){let t=Number.isFinite(e)?e:0,n=dd[0].stage;for(let{thresholdSec:e,stage:r}of dd)if(t>=e)n=r;else break;return n}const pd=qe,md=3e3;function hd(e){let t=100*(1-Math.exp(-Math.max(0,e)/8));return Math.min(92,Math.round(t))}function gd({verb:e,elapsed:t=!0,paused:n=!1,responseLength:r=0,hasActiveTools:i=!1,tokens:a=0,mode:o,progressPercent:s,toolTurnCount:c=0,maxToolTurns:l=0,estimatedProgress:u=!1}){let d=h(),[f,p]=K(0),[m,g]=K(0),[_,v]=K(0),y=G(Date.now()),b=G(0),x=G(r),S=G(null),C=G(-1),w=G(e??(()=>{let e=B.t(`spinner.verbs`,{returnObjects:!0});return e[Math.floor(Math.random()*e.length)]})()),T=G(r),E=G(i);T.current=r,E.current=i;let D=je(),O=G(n);O.current=n,Me(160,()=>{if(O.current)return;let e=Date.now()-y.current-b.current;p(Math.floor(e/160)%pd.length)}),U(()=>{let e=setInterval(()=>{if(n)return;let e=Date.now()-y.current-b.current,t=Math.floor(e/1e3);t!==C.current&&(C.current=t,g(e));let r=T.current,i=x.current;if(i>0&&i===r&&!E.current)if(S.current===null)S.current=Date.now();else{let e=Date.now()-S.current;e>=md&&v(Math.min(1,(e-md)/2e3))}else x.current=r,S.current=null,v(0)},160);return()=>clearInterval(e)},[n]),U(()=>{n?b.current=Date.now()-y.current:(y.current=Date.now()-b.current,b.current=0)},[n]);let ee=_>0,te=pd[f],ne=Math.floor(m/1e3),k=[];if(t&&k.push({text:go(ne)}),a>0&&k.push({text:`↓ ${B.t(`budget.tokensLabel`,{count:a})}`}),o===`responding`&&s!==void 0&&Number.isFinite(s)){let e=Math.max(0,Math.min(100,Math.round(s)));k.push({text:B.t(`spinner.outputPercent`,{pct:e})})}let re=u?fd(ne):null;if(re){let e=Math.min(re.capPercent,hd(ne));k.push({text:B.t(`spinner.estimatedPercent`,{pct:e})})}l>0&&k.push({text:B.t(`tool.budgetLabel`,{used:c,max:l}),color:Zc(c,l)});let ie=ee?d.error:d.accent,A=re?`${B.t(`compact.ionStageLabel`,{context:re.labelKey})}…`:`${e??w.current}…`,ae=ee||D?null:Yc(A,Xc(f,A.length)),j=o===`requesting`?R.requesting:o===`responding`?R.responding:null;return J(Y,{flexDirection:`row`,marginTop:F.tight,children:[q(X,{color:ie,children:te}),q(X,{children:` `}),j&&J(Mt,{children:[q(X,{dimColor:!0,color:d.inactive,children:j}),q(X,{children:` `})]}),ae?ae.map((e,t)=>q(X,{color:e.bright?d.text:d.inactive,bold:e.bright,children:e.text},t)):q(X,{color:ee?d.error:d.text,children:A}),k.length>0&&J(Mt,{children:[q(X,{color:d.inactive,children:` (`}),k.map((e,t)=>J(V.Fragment,{children:[t>0&&q(X,{color:d.inactive,children:` · `}),q(X,{color:e.color??d.inactive,children:e.text})]},t)),q(X,{color:d.inactive,children:`)`})]})]})}function _d({streamStore:e,pendingPermission:t}){let n=Z(e.store,e=>e.streamingText),r=Z(e.store,e=>e.streamingThinking),i=Z(e.store,e=>e.spinnerMode),a=Z(e.store,e=>e.toolTurnCount),o=Z(e.store,e=>e.maxToolTurns),s=Z(e.store,e=>e.processing),c=Z(e.store,e=>e.activeTool),l=Z(e.store,ol),u=Z(e.store,al);if(!s||t||r)return null;let d=c===lo,f=d?B.t(`compact.ingVerb`):c?B.t(`bg.runningVerb`,{tool:c}):void 0;return q(gd,{hasActiveTools:!!c,responseLength:n.length,tokens:l,verb:f,mode:i??void 0,progressPercent:u,toolTurnCount:a,maxToolTurns:o,estimatedProgress:d})}function vd(e,t,n=60){if(e.length===0)return null;let r=Math.max(0,Math.min(t,e.length-1));for(let t=r;t>=0;t--){let r=e[t];if(!r||r.role!==`user`)continue;let i=yd(r.content);if(i)return xd(i,n)}return null}function yd(e){return typeof e==`string`?e.trim():Array.isArray(e)?e.map(e=>typeof e==`string`?e:bd(e)?e.text:``).filter(Boolean).join(` `).trim():bd(e)?String(e.text).trim():``}function bd(e){return!!e&&typeof e==`object`&&typeof e.text==`string`}function xd(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,Math.max(1,t-1))}…`}function Sd({sessionTitle:e,reviewing:t,turnPrompt:n}){return t&&n?n:e??``}function Cd(e){return typeof e==`string`&&/^[a-f\d]{8}$/i.test(e)}function wd(e){let t=ql(),{taskStore:n}=Vl(),r=Z(n.store,e=>e.sessionTitle),i=Z(n.store,e=>e.sessionList),a=Z(n.store,e=>e.needsSetup),o=Z(n.store,e=>e.pendingPermission),s=Z(n.store,e=>e.subagentContext),c=Z(n.store,e=>e.pendingEcho),l=Z(n.store,e=>e.pendingSteers),u=Z(e.scrollStore.store,e=>e.offset>0),[d,f]=V.useState(null);V.useEffect(()=>{s&&f(null)},[s]);let p=Z(e.scrollStore.store,e=>e.offset),m=V.useMemo(()=>{if(!u)return null;let t=Math.max(0,e.messages.length-1-Math.floor(p/3));return vd(e.messages,t)},[u,p,e.messages]),h=a?`model`:void 0;if(e.welcome&&e.showHome)return q(cd,{version:e.welcome.version,buildId:e.welcome.buildId,cwd:e.welcome.cwd,width:e.columns,nickname:e.welcome.nickname,updateAvailable:e.welcome.updateAvailable,weather:e.welcome.weather,sessionList:i,onSessionSelect:t.onSessionSelect,ftueStage:h,shadow:e.shadow});let g=Sd({sessionTitle:r,reviewing:u,turnPrompt:m}),_=g.length>0&&!Cd(g),v=Math.max(1,e.rows-(_?1:0)-(d?1:0));return J(Y,{flexDirection:`column`,flexGrow:1,justifyContent:`flex-end`,children:[_&&q(Y,{height:1,flexShrink:0,flexDirection:`row`,children:q(X,{dimColor:!0,children:`${R.userPrompt} ${g}`})}),s?(()=>{let n=s;return q(ud,{title:n.title,status:n.status,messages:n.messages,streamText:n.streamText,rows:v,columns:e.columns,onDismiss:t.onExitSubagentContext})})():J(Mt,{children:[q(sl,{streamStore:e.streamStore,completedMessages:e.messages,columns:e.columns,rows:v,maxPreviewRows:e.fullScreenPaneActive?0:e.maxPreviewRows,suppressLive:e.fullScreenPaneActive||u,pendingEcho:c??null,scrollbackMode:e.scrollbackMode??!1,pendingSteers:l??[],windowMode:e.windowMode,scrollStore:e.scrollStore,earlierLoading:e.earlierLoading,earlierEnded:e.earlierEnded,onNeedEarlier:e.onNeedEarlier,onPrepend:e.onPrepend,findQuery:e.findQuery,findActiveMatch:e.findActiveMatch,onFindNavigateTo:e.onFindNavigateTo,onFindCountChange:e.onFindCountChange,onReviewHintChange:f,renderReviewHint:!1}),!e.fullScreenPaneActive&&q(_d,{streamStore:e.streamStore,pendingPermission:o??null})]}),d&&q(Y,{height:1,flexShrink:0,flexDirection:`row`,children:q(X,{dimColor:!0,children:d})})]})}function Td(e,t,n,r){let i=e.map((e,n)=>({item:e,index:n,label:t(e)}));if(e.length===0)return{items:[],hiddenLeft:0,hiddenRight:0};if(r===void 0||!Number.isFinite(r)||r<=0)return{items:i,hiddenLeft:0,hiddenRight:0};let a=Math.max(0,Math.min(n,e.length-1)),o=e=>it(i[e].label)+2;if(i.reduce((e,t,n)=>e+o(n),0)+(i.length-1)*3<=r)return{items:i,hiddenLeft:0,hiddenRight:0};let s=Math.max(6,r-10),c=a,l=a+1,u=Math.min(o(a),s);for(;;){let e=l<i.length,t=c>0;if(!e&&!t)break;let n=!1;if(e){let e=o(l)+3;u+e<=s&&(u+=e,l++,n=!0)}if(t){let e=o(c-1)+3;u+e<=s&&(u+=e,c--,n=!0)}if(!n)break}return{items:i.slice(c,l).map(e=>{let t=Math.max(1,s-2);return it(e.label)>t?{...e,label:ae(e.label,t)}:e}),hiddenLeft:c,hiddenRight:i.length-l}}function Ed({label:e,active:t,disabled:n,color:r=`accent`}){return q(I,{variant:`ghost`,color:r,label:e,focused:t,disabled:n})}function Dd({items:e,activeKey:t,color:n=`accent`,tabIndex:r=-1,onSelect:i,availableWidth:a,enableDigitAccess:o=!1}){let s=h(),{focused:c}=Re({tabIndex:r,disabled:r<0}),u=(n,r)=>{if(!i||e.length===0)return!1;let a=e.findIndex(e=>e.key===t);if(r.leftArrow||r.rightArrow)return i(e[(a+(r.leftArrow?-1:1)+e.length)%e.length].key),!0;if(o&&n>=`1`&&n<=`9`){let t=n.charCodeAt(0)-49;return t<e.length&&!e[t].disabled?(i(e[t].key),!0):!1}return!1};l(c,u),j(`segmented-${e.map(e=>e.key).join(`-`)}`,u,{isActive:!!i&&!c});let d=Td(e,e=>e.label,e.findIndex(e=>e.key===t),a);return J(Y,{flexDirection:`row`,gap:F.tight,children:[d.hiddenLeft>0&&q(X,{color:s.inactive,children:`←${d.hiddenLeft}`}),d.items.map((e,r)=>J(V.Fragment,{children:[r>0&&q(X,{color:s.inactive,children:`·`}),q(Ed,{label:e.label,active:e.item.key===t,disabled:e.item.disabled,color:n})]},e.item.key)),d.hiddenRight>0&&q(X,{color:s.inactive,children:`→${d.hiddenRight}`})]})}const Od={running:R.todoActive,exited:R.check,killed:R.cross,failed:R.cross};function kd(e,t){return e===`running`?t.special:e===`exited`?t.success:t.error}function Ad(e){if((e.type??`process`)===`agent-session`)switch(e.agentStatus){case`running`:return R.todoActive;case`ready`:return R.attention;case`needs_input`:return R.attention;case`applied`:return R.check;default:return R.cross}return Od[e.status]}function jd(e,t){if((e.type??`process`)===`agent-session`){if(e.stall===`stalled`)return t.error;if(e.stall===`warn`)return t.warning;switch(e.agentStatus){case`running`:return t.special;case`ready`:return t.selection;case`needs_input`:return t.warning;case`applied`:return t.success;default:return t.error}}return kd(e.status,t)}function Md({tasks:e,columns:t=80,onClose:n,onKill:r,onViewOutput:i,onApply:a,onSwitch:o,onDelete:s,active:c=!0,rows:l=24}){let u=h(),[d,f]=$i(`delegates`,e.length),p=G(0),m=e.some(e=>(e.type??`process`)===`agent-session`?e.agentStatus===`running`:e.status===`running`),[,g]=K(0);U(()=>{if(!m)return;let e=setInterval(()=>g(e=>(e+1)%1e6),1e3);return()=>clearInterval(e)},[m]),j(`delegates-pane`,(t,c)=>{if(c.escape||t===`q`)return n?.(),!0;if(b(`list-nav-up`,t,c,`background`))return f(e=>Math.max(0,e-1)),!0;if(b(`list-nav-down`,t,c,`background`))return f(t=>Math.max(0,Math.min(e.length-1,t+1))),!0;let l=e[d],u=l?ho(l):!1;return t===`k`&&u&&l?(r?.(l.id),!0):(t===`o`||c.return)&&l?(i?.(l.id),!0):t===`a`&&l?.type===`agent-session`&&l.agentStatus===`ready`&&l.diffStat?(a?.(l.id),!0):t===`s`&&l?.type===`agent-session`?(o?.(l.id),!0):t===`d`&&l&&!u?(s?.(l.id),!0):!1},{isActive:c,ignoreRoute:!0});let _=e.filter(ho).length,v=Date.now(),y=Math.max(12,Math.min(48,t-28));if(!c){if(e.length===0)return null;let t=e[Math.min(d,e.length-1)];return J(Y,{flexDirection:`column`,children:[J(Y,{children:[q(X,{color:u.special,children:`▸ `}),q(D,{type:`secondary`,children:B.t(`bg.tasksTitle`)}),J(D,{type:`secondary`,children:[` `,e.length]}),_>0&&J(D,{type:`secondary`,children:[` · `,B.t(`bg.runningSuffix`,{n:_})]}),J(D,{type:`secondary`,dim:!0,children:[` `,A(`p`)]})]}),t&&J(Y,{flexDirection:`row`,children:[q(X,{color:u.inactive,children:`${R.pointer} `}),q(X,{color:u.inactive,children:ae(t.command,y).padEnd(y)}),J(D,{type:`secondary`,dim:!0,children:[` `,xo(t,v)]})]})]})}let x=e[Math.min(d,e.length-1)],S=(x?.type??`process`)===`agent-session`&&x?.agentStatus===`ready`&&!!x?.diffStat,C=!!x&&!ho(x),w=Math.min(d,e.length-1),E=[],ee,te=0;e.forEach((e,t)=>{let n=po(e);n!==ee&&(te>0&&E.push({type:`spacer`}),E.push({type:`header`,category:n}),te++,ee=n),E.push({type:`entry`,task:e,index:t})});let ne=pt(E,E.findIndex(e=>e.type===`entry`&&e.index===w),ze(E.length,l,3),p.current);return p.current=ne.scrollTop,J(Y,{flexDirection:`column`,marginTop:F.tight,children:[J(Y,{children:[q(X,{color:u.special,children:`▸ `}),q(X,{color:u.text,children:B.t(`bg.tasksTitle`)}),J(D,{type:`secondary`,children:[` `,_>0?B.t(`bg.runningSuffix`,{n:_}):`${e.length} total`,e.length>_?` · ${B.t(`bg.doneSuffix`,{n:e.length-_})}`:``]}),q(Y,{marginLeft:F.tight,children:q(O,{dim:!0,items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[`k`,B.t(`hint.kill`)],[`o`,B.t(`hint.output`)],...S?[[`a`,B.t(`hint.apply`)]]:[],...C?[[`d`,B.t(`hint.delete`)]]:[],[T.esc,B.t(`hint.close`)],[T.tab,B.t(`hint.tabFocus`)]]})})]}),q(Y,{marginLeft:F.section,flexDirection:`column`,children:e.length===0?q(D,{type:`secondary`,dim:!0,children:B.t(`bg.empty`)}):J(Mt,{children:[ne.hasMoreAbove&&q(X,{dimColor:!0,children:B.t(`scroll.above`,{n:1})}),ne.rows.map((e,t)=>{if(e.type===`spacer`)return q(X,{children:` `},`spacer-${t}`);if(e.type===`header`)return q(D,{type:`secondary`,dim:!0,children:B.t(`bg.categoryLabel`,{context:e.category})},`h-${t}`);let n=e.task,r=e.index===d;return J(Y,{flexDirection:`row`,children:[q(X,{color:r?u.selection:u.inactive,children:r?`${R.pointer} `:` `}),J(X,{color:jd(n,u),children:[Ad(n),` `]}),q(X,{color:r?u.selection:u.inactive,children:ae(n.command,y).padEnd(y)}),(n.type??`process`)===`agent-session`&&n.model&&J(D,{type:`secondary`,dim:!0,children:[` `,String(n.model)]}),J(D,{type:`secondary`,dim:!0,children:[` `,xo(n,v)]})]},n.id)}),ne.hasMoreBelow&&q(X,{dimColor:!0,children:B.t(`scroll.below`,{n:1})})]})})]})}function Nd({view:e,columns:t=80,rows:n,active:r=!0,onDismiss:i}){let a=h(),o=e.prompt!==void 0,s=e.messages!==void 0&&e.messages.length>0,l=!!e.diff?.trim(),u=(o?1:0)+(s?1:0)+(l?1:0)>=2,[d,f]=K(l?`diff`:s?`conversation`:`prompt`),[p,m]=K(0),[g,_]=K(!1),[v,b]=K(``),[x,S]=K(-1),C=n?c(n,12):18;U(()=>m(0),[e.id,d]);let w=Math.max(8,t-fe.contentInset),E=[],ee=[];if(d===`diff`)E=(e.diff??``).split(`
53
+ `);else if(d===`prompt`)E=Xa(e.prompt??``,w);else if(e.messages&&e.messages.length>0){let t=[];for(let n=0;n<e.messages.length;n++){let r=e.messages[n],i=$s(r,w);i.length!==0&&(t.length>0&&t.push(``),t.push(...i))}E=t,ee=e.streamText?Jc(e.streamText,w-fe.borderInset,3):[]}let te=d===`prompt`,ne=d===`diff`,k=e=>e.startsWith(`+`)&&!e.startsWith(`+++`)?a.diffAdd:e.startsWith(`-`)&&!e.startsWith(`---`)?a.diffRemove:e.startsWith(`@@`)||e.startsWith(`diff --git`)?a.special:a.secondary,re=e.status===`running`,ie=V.useMemo(()=>{if(!v)return{flat:[],byLine:new Map};let e=[],t=new Map;for(let n=0;n<E.length;n++){let r=ha(Ts(E[n]),v);if(r.length!==0){t.set(n,r);for(let t of r)e.push({line:n,range:t})}}return{flat:e,byLine:t}},[v,E]),A=jo(E.length,C,p),oe=E.slice(A.start,A.end),se=v?oe.map((e,t)=>{let n=A.start+t,r=ie.byLine.get(n);if(!r||r.length===0)return e;let i=x>=0?ie.flat[x]:void 0;return ma(e,r,i&&i.line===n?i.range:void 0)}):oe,M=e.responseText?.split(`
54
+ `)[0],[N,ce]=K(!1);ld(e=>m(t=>Math.max(0,t+e)),[]),j(`delegates-pane-2`,(t,n)=>{if(g){if(n.escape)return _(!1),b(``),S(-1),!0;if(n.backspace)return b(e=>e.slice(0,-1)),S(-1),!0;if((t===`n`||t===`N`)&&v.length>0){let e=t===`n`?1:-1;return S(t=>ie.flat.length>0?(t+e+ie.flat.length)%ie.flat.length:-1),!0}return t.length===1?(b(e=>e+t),S(-1),!0):!0}return t===`/`&&!n.ctrl&&!n.meta?(_(!0),b(``),S(-1),!0):n.escape?(i?.(),!0):t===`]`&&u?(f(e=>{let t=[...l?[`diff`]:[],...s?[`conversation`]:[],...o?[`prompt`]:[]];return t[(t.indexOf(e)+1)%t.length]??e}),!0):t===`d`&&e.responseText?(ce(e=>!e),!0):n.upArrow?(m(e=>e+1),!0):n.downArrow?(m(e=>Math.max(0,e-1)),!0):n.pageUp?(m(e=>e+C),!0):n.pageDown?(m(e=>Math.max(0,e-C)),!0):!1},{isActive:r,ignoreRoute:!0});let P=J(Y,{flexDirection:`column`,children:[J(Y,{flexDirection:`row`,children:[J(X,{color:kd(e.status,a),children:[Od[e.status],` `]}),q(X,{color:a.secondary,bold:!0,children:ae(e.command,Math.max(12,t-12))}),q(D,{type:`secondary`,children:re?` ${R.statusDot} ${B.t(`bg.live`)}`:` ${B.t(`status.done`)}`})]}),M&&J(Y,{flexDirection:`column`,children:[J(D,{type:`secondary`,dim:!0,children:[` `,M,` `,q(X,{color:a.suggestion,children:`[d] ${N?B.t(`hint.collapse`):B.t(`find.tabDiagnostics`)}`})]}),N&&e.responseText&&q(Y,{flexDirection:`column`,marginTop:F.tight,children:e.responseText.split(`
55
+ `).slice(1).map((e,t)=>q(X,{color:a.secondary,dimColor:!0,wrap:`truncate-end`,children:e===``?` `:e},t))})]}),q(X,{children:` `})]}),le=[...l?[{key:`diff`,label:B.t(`find.tabDiff`)}]:[],...s?[{key:`conversation`,label:B.t(`find.tabConversation`)}]:[],...o?[{key:`prompt`,label:B.t(`find.tabPrompt`)}]:[]];return J(y,{header:P,footer:q(O,{dim:!0,items:[...u?[[`]`,B.t(`hint.switch`)]]:[],...e.responseText?[[`d`,N?B.t(`hint.collapse`):B.t(`find.tabDiagnostics`)]]:[],...E.length>C?[[`${T.up}${T.down}`,B.t(`hint.scroll`)]]:[],[T.esc,B.t(`hint.back`)]]}),children:[u&&q(Y,{marginBottom:F.tight,children:q(Dd,{items:le.map(e=>({key:e.key,label:e.label})),activeKey:d,availableWidth:t-4,onSelect:e=>f(e)})}),J(Y,{flexDirection:`column`,children:[g&&q(Y,{height:1,children:q(X,{color:a.selection,children:B.t(`transcript.findBar`,{query:v,count:ie.flat.length})})}),q(X,{color:a.special,dimColor:!0,children:A.above>0?`↑ ${A.above}`:` `}),E.length===0?q(D,{type:`secondary`,dim:!0,children:B.t(`bg.noOutput`)}):se.map((e,t)=>ne?q(X,{color:k(e),wrap:`truncate-end`,children:e===``?` `:e},A.start+t):te?q(X,{color:a.secondary,wrap:`truncate-end`,children:e===``?` `:e},A.start+t):q(X,{wrap:`truncate-end`,children:e===``?` `:e},A.start+t)),ee.length>0&&q(Y,{flexDirection:`column`,children:ee.map((e,t)=>J(Y,{flexDirection:`row`,children:[q(X,{color:a.replyPrefix,children:t===0?`${R.bullet} `:` `}),q(X,{children:e})]},t))}),q(X,{color:a.special,dimColor:!0,children:A.below>0?`↓ ${A.below}`:` `})]})]})}function Pd(e){let t=e.agentStatus??`running`;return t===`running`||t===`ready`||t===`needs_input`}function Fd(e,t){if(e.stall===`stalled`)return{ch:R.statusDot,color:t.error};if(e.stall===`warn`)return{ch:R.statusDot,color:t.warning};switch(e.agentStatus??`running`){case`running`:return{ch:R.statusDot,color:t.accent};case`needs_input`:return{ch:R.needsInput,color:t.warning};case`ready`:return{ch:R.check,color:t.success};case`applied`:return{ch:R.check,color:t.success};case`failed`:return{ch:R.cross,color:t.error};case`canceled`:return{ch:R.cross,color:t.inactive};default:return{ch:R.statusDot,color:t.inactive}}}function Id(e){return ae(e,44)}function Ld({tasks:e,focused:t,now:n,onDismiss:r,onSwitch:i,onViewOutput:a,rows:o=24}){let s=h(),[c,l]=$i(`subagents`,e.length),u=G(0);if(j(`subagents-pane`,(t,n)=>{if(n.escape)return M()?.navigate(`/`,{reset:!0}),r?.(),!0;if(b(`list-nav-up`,t,n,`subagents`))return l(e=>Math.max(0,e-1)),!0;if(b(`list-nav-down`,t,n,`subagents`))return l(t=>Math.min(e.length-1,t+1)),!0;let o=e[Math.max(0,Math.min(c,e.length-1))];return n.return?(o&&i?.(o.id),!0):t===`s`?(o&&a?.(o.id),!0):!1},{isActive:t}),e.length===0)return null;let d=n??Date.now(),f=e.filter(Pd).length;if(!t)return J(Y,{children:[q(X,{color:s.special,children:`▸ `}),q(D,{type:`secondary`,children:B.t(`subagent.sTitle`)}),J(D,{type:`secondary`,children:[` `,e.length,f>0?` · ${B.t(`subagent.sRunning`,{n:f})}`:``]}),J(D,{type:`secondary`,dim:!0,children:[` `,A(`t`)]})]});let p=Math.min(c,e.length-1),m=pt(e,p,ze(e.length,o,3),u.current);return u.current=m.scrollTop,J(Y,{flexDirection:`column`,marginTop:F.tight,children:[J(Y,{children:[q(X,{color:s.special,children:`▸ `}),q(X,{color:s.text,children:B.t(`subagent.sTitle`)}),J(D,{type:`secondary`,children:[` `,e.length,f>0?` · ${B.t(`subagent.sRunning`,{n:f})}`:``]}),q(Y,{marginLeft:F.tight,children:q(O,{dim:!0,items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[T.enter,B.t(`hint.switch`)],[`s`,B.t(`hint.view`)],[T.esc,B.t(`hint.close`)],[T.tab,B.t(`hint.tabFocus`)]]})})]}),J(Y,{marginLeft:F.section,flexDirection:`column`,children:[m.hasMoreAbove&&q(X,{dimColor:!0,children:B.t(`scroll.above`,{n:1})}),m.rows.map((e,t)=>{let n=m.scrollTop+t===p,r=Fd(e,s),i=n?s.selection:void 0;return J(Y,{flexDirection:`row`,children:[q(X,{color:n?s.selection:s.inactive,children:n?`${R.pointer} `:` `}),J(X,{color:r.color,children:[r.ch,` `]}),q(X,{color:i??s.inactive,children:Id(e.command)}),e.model&&J(D,{type:`secondary`,children:[` `,e.model,e.modelDecidedBy?` (${e.modelDecidedBy})`:``]}),J(D,{type:`secondary`,children:[` `,xo(e,d)]})]},e.id)}),m.hasMoreBelow&&q(X,{dimColor:!0,children:B.t(`scroll.below`,{n:1})})]})]})}function Rd(e,t){return t===0?0:Math.max(0,Math.min(e,t-1))}function zd(e,t,n){let r=globalThis;r[`__ottoSchedule${e===`run`?`Run`:e===`toggle`?`Toggle`:`Remove`}Request`]=e===`toggle`?{taskId:t,...n}:t}function Bd({tasks:e,focused:t,onDismiss:n,rows:r=24}){let i=h(),[a,o]=$i(`schedule`,e.length),s=G(0);if(j(`schedule-pane`,(t,r)=>{if(r.escape)return M()?.navigate(`/`,{reset:!0}),n?.(),!0;if(b(`list-nav-up`,t,r,`schedule`))return o(e=>Math.max(0,e-1)),!0;if(b(`list-nav-down`,t,r,`schedule`))return o(t=>Math.min(e.length-1,t+1)),!0;let i=e[Math.max(0,Math.min(a,e.length-1))];return i?r.return||t===`r`?(zd(`run`,i.id),!0):t===` `||t===`t`?(zd(`toggle`,i.id,{enabled:!i.enabled}),!0):t===`d`?(zd(`remove`,i.id),!0):!1:!1},{isActive:t}),e.length===0&&!t)return null;if(!t)return J(Y,{children:[q(X,{color:i.special,children:`▸ `}),q(D,{type:`secondary`,children:B.t(`schedule.sLabel`)}),J(D,{type:`secondary`,children:[` `,e.length]}),J(D,{type:`secondary`,dim:!0,children:[` `,A(`s`)]})]});let c=Rd(a,e.length),l=Math.min(32,Math.max(0,...e.map(e=>it(e.name)))),u=pt(e,c,ze(e.length,r,3),s.current);return s.current=u.scrollTop,J(Y,{flexDirection:`column`,children:[J(Y,{children:[q(X,{color:i.special,children:`▸ `}),q(X,{color:i.text,children:B.t(`schedule.sLabel`)}),J(D,{type:`secondary`,children:[` `,e.length]}),q(Y,{marginLeft:F.tight,children:q(O,{dim:!0,items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[`↵/r`,B.t(`hint.execute`)],[`t`,B.t(`hint.toggle`)],[`d`,B.t(`hint.delete`)],[T.esc,B.t(`hint.close`)],[T.tab,B.t(`hint.tabFocus`)]]})})]}),J(Y,{marginLeft:F.section,flexDirection:`column`,children:[e.length===0&&q(D,{type:`secondary`,children:B.t(`schedule.sEmpty`)}),u.hasMoreAbove&&q(X,{dimColor:!0,children:B.t(`scroll.above`,{n:1})}),u.rows.map((e,t)=>{let n=u.scrollTop+t===c,r=e.lastFireFailed===!0,a=r?`!`:e.enabled?R.toggleOn:R.toggleOff,o=r?i.error:e.enabled?i.accent:i.inactive,s=n?i.selection:void 0,d=new Date(e.nextFireAt).toLocaleString(),f=e.recurring?e.cronExpression:B.t(`schedule.oneShot`),p=r&&e.lastFireError?` (failed: ${e.lastFireError})`:``;return J(Y,{flexDirection:`row`,children:[q(X,{color:n?i.selection:i.inactive,children:n?`${R.pointer} `:` `}),J(X,{color:o,children:[a,` `]}),q(X,{color:s??i.inactive,children:gt(e.name,l)}),J(D,{type:`secondary`,children:[` `,f,` `,B.t(`schedule.next`),d]}),p&&q(X,{color:i.error,children:p})]},e.id)}),u.hasMoreBelow&&q(X,{dimColor:!0,children:B.t(`scroll.below`,{n:1})})]})]})}function Vd({text:e,focused:t,columns:n=80,onDismiss:r,onOpenViewer:i}){let a=h();if(j(`clipboard-pane`,(e,t)=>t.escape?(M()?.navigate(`/`,{reset:!0}),r?.(),!0):t.return?(i?.(),!0):!1,{isActive:t}),e.length===0)return null;let o=Array.from(e).length;if(!t)return J(Y,{children:[q(X,{color:a.special,children:`▸ `}),q(D,{type:`secondary`,children:B.t(`clipboard.paneTitle`)}),J(D,{type:`secondary`,children:[` `,B.t(`clipboard.charsLabel`,{count:o})]})]});let s=Math.max(10,n-F.section-2),c=e.split(`
56
+ `),l=c.slice(0,5),u=c.length-l.length;return J(Y,{flexDirection:`column`,marginTop:F.tight,children:[J(Y,{children:[q(X,{color:a.special,children:`▸ `}),q(X,{color:a.text,children:B.t(`clipboard.paneTitle`)}),J(D,{type:`secondary`,children:[` `,B.t(`clipboard.charsLabel`,{count:o})]}),q(Y,{marginLeft:F.tight,children:q(O,{dim:!0,items:[[T.enter,B.t(`clipboard.openHint`)],[T.esc,B.t(`hint.close`)],[T.tab,B.t(`hint.tabFocus`)]]})})]}),J(Y,{marginLeft:F.section,flexDirection:`column`,children:[l.map((e,t)=>q(X,{color:a.inactive,wrap:`truncate-end`,children:ae(e===``?` `:e,s)},t)),u>0&&q(D,{type:`secondary`,dim:!0,children:` ${R.ellipsis} ${u} more`})]})]})}const Hd={pending:R.todoPending,in_progress:R.todoActive,done:R.check,skipped:R.todoPending,failed:R.cross};function Ud(e,t){switch(e){case`done`:return t.success;case`in_progress`:return t.accent;case`failed`:return t.error;case`skipped`:return t.warning;default:return t.inactive}}function Wd({tasks:e,title:t,collapsed:n=!1,selectedIndex:r,focused:i=!1,rows:a,onDismiss:o,onSelectIndex:s}){let c=h();j(`task-pane`,(t,n)=>n.escape?(o?.(),!0):b(`list-nav-up`,t,n,`taskFocus`)?(s?.(e=>Math.max(0,e-1)),!0):b(`list-nav-down`,t,n,`taskFocus`)?(s?.(t=>Math.min(e.length-1,t+1)),!0):!1,{isActive:i,ignoreRoute:!0});let l=G(0);if(e.length===0)return null;let u=e.filter(e=>e.status===`done`).length,d=e.filter(e=>e.status===`failed`).length,f=d>0?`${u}/${e.length}!`:`${u}/${e.length}`;return J(Y,{flexDirection:`column`,marginTop:F.tight,children:[J(Y,{children:[q(X,{color:c.special,children:`▸ `}),q(X,{color:c.text,children:t??B.t(`task.title`)}),J(X,{color:d>0?c.error:c.inactive,children:[` `,f]}),J(D,{type:`secondary`,children:[` `,la(e.filter(e=>e.status===`done`||e.status===`skipped`).length/e.length,8)]}),n&&J(D,{type:`secondary`,dim:!0,children:[` `,B.t(`task.collapsedHint`)]}),i&&!n&&q(Y,{marginLeft:F.tight,children:q(O,{dim:!0,items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[T.esc,B.t(`hint.close`)],[T.tab,B.t(`hint.tabFocus`)]]})})]}),!n&&q(Y,{marginLeft:F.section,flexDirection:`column`,children:(()=>{let t=Math.max(0,...e.map(e=>it(e.title??``))),n=ze(e.length,a??24,3),o=pt(e,Math.min(r??0,e.length-1),n,l.current);l.current=o.scrollTop;let s=o.rows.map((e,n)=>{let a=o.scrollTop+n,s=e.status===`done`||e.status===`skipped`,l=i&&a===(r??0),u=e.title??``,d=` `.repeat(Math.max(0,t-it(u))),f=B.t(`task.statusLabel`,{context:e.status??`pending`});return J(Y,{flexDirection:`row`,children:[q(X,{color:l?c.accent:Ud(e.status,c),children:l?`${R.pointer} `:`${Hd[e.status??`pending`]} `}),q(X,{color:l?c.accent:e.status===`skipped`?c.warning:s?c.inactive:c.text,strikethrough:s,italic:e.status===`skipped`,children:u}),q(X,{children:d}),J(X,{color:l?c.accent:Ud(e.status,c),dimColor:!0,children:[` `,f]})]},e.id??a)});return J(Mt,{children:[o.hasMoreAbove&&q(X,{dimColor:!0,children:B.t(`scroll.above`,{n:1})}),s,o.hasMoreBelow&&q(X,{dimColor:!0,children:B.t(`scroll.below`,{n:1})})]})})()})]})}const Gd={tasks:R.itemActive,delegates:R.service,edited:R.edited,subagents:R.attention,clipboard:R.clipboard},Kd={tasks:`/pane/tasks`,delegates:`/pane/delegates`,edited:`/pane/edited-files`,subagents:`/pane/subagents`,clipboard:`/pane/clipboard`};function qd({counts:e,labels:t,currentPath:n=``}){let r=[{id:`tasks`,count:e.tasks,label:t.tasks},{id:`delegates`,count:e.delegates,label:t.delegates},{id:`edited`,count:e.edited,label:t.edited},{id:`subagents`,count:e.subagents,label:t.subagents},{id:`clipboard`,count:e.clipboard,label:t.clipboard}].map(e=>{let t=Kd[e.id],r=t!==``&&(n===t||n.startsWith(`${t}/`));return{id:e.id,icon:Gd[e.id],label:e.label,count:e.count,active:r}}).filter(e=>e.count>0);if(e.clipboardFailed){let e=r.filter(e=>e.id!==`clipboard`);return e.push({id:`clipboard`,icon:Gd.clipboard,label:t.clipboardFailed,count:0,active:!1,hideCount:!0,tone:`warning`}),e}return r}function Jd(e){return e.length>0}const Yd=V.memo(function({counts:e,labels:t,currentPath:n=``,tabHint:r}){let i=qd({counts:e,labels:t,currentPath:n});return i.length===0?q(Y,{flexDirection:`row`,height:1}):q(Y,{flexDirection:`row`,height:1,children:J(Mt,{children:[i.map((e,t)=>J(D,{type:e.tone===`warning`?`warning`:e.active?`accent`:`secondary`,wrap:`truncate-end`,children:[t>0?` · `:``,e.hideCount?`${e.icon} ${e.label}`:`${e.icon} ${e.label} ${e.count}`]},e.id)),r&&Jd(i)&&q(D,{type:`secondary`,dim:!0,wrap:`truncate-end`,children:` · ${r}`})]})})});function Xd(e=process.env,t=process.platform){let n=e.TERM_PROGRAM;return n===`Apple_Terminal`?`Fn`:n===`iTerm.app`||e.LC_TERMINAL===`iTerm2`?`Option`:n===`vscode`||n===`ghostty`||n===`WarpTerminal`||n===`Hyper`?t===`darwin`?`Option`:`Shift`:n===`tmux`||e.TMUX?`Shift`:`Shift/Option/Fn`}function Zd(e=process.env,t=process.platform){let n=Xd(e,t);return n===`Shift/Option/Fn`?`Shift (Option in iTerm2, Fn in Terminal.app)`:n}const Qd=V.memo(function(e){let{fullScreenPaneActive:t,taskPaneRendered:n,tipVisible:r,tasksCollapsed:i,taskSelIndex:a,setTaskSelIndex:o,backgroundTasksOrdered:s,columns:c,openEditedFileFull:l,editedFileFullIndex:u,subagents:d}=e,{taskStore:f}=Vl(),p=Z(f.store,e=>e.tasks),m=Z(f.store,e=>e.tasksTitle),h=Z(f.store,e=>e.editedFiles),_=Z(f.store,e=>e.scheduleTasks),v=Z(f.store,e=>e.clipboardChars),y=Z(f.store,e=>e.clipboardFailed),b=Z(f.store,e=>e.clipboardText),x=Z(f.store,e=>e.subagentContext),S=Z(f.store,e=>e.backgroundTasks.length),{onBackgroundClose:C,onBackgroundKill:w,onBackgroundViewOutput:T,onBackgroundApply:E,onBackgroundSwitch:D,onBackgroundDelete:O,onToggleEditedFiles:ee,onToggleSubagents:te,onToggleSchedule:ne}=ql(),{currentPath:k}=g(),re=k===`/pane/tasks`&&p.length>0,ie=k===`/pane/delegates`&&S>0,A=k===`/pane/edited-files`,ae=k===`/pane/subagents`,j=k===`/pane/schedule`,oe=k===`/pane/clipboard`&&b.length>0;return t||x?null:J(Y,{flexDirection:`column`,marginTop:n||r?F.none:F.tight,children:[re&&q(Wd,{tasks:p,title:m,collapsed:i,focused:!0,selectedIndex:a,onDismiss:Yl,onSelectIndex:o}),ie&&S>0&&q(Md,{tasks:s,columns:c,onClose:C,onKill:w,onViewOutput:T,onApply:E,onSwitch:D,onDelete:O,active:!0}),A&&q(xu,{files:h,focused:!0,onDismiss:ee,onOpenFileFull:l,fullOpenIndex:u}),ae&&q(Ld,{tasks:d,focused:!0,onDismiss:te,onSwitch:D,onViewOutput:T}),j&&q(Bd,{tasks:_,focused:!0,onDismiss:ne}),oe&&q(Vd,{text:b,focused:!0,columns:c,onDismiss:Yl,onOpenViewer:()=>M()?.navigate(`/viewer/clipboard`,{state:{content:b}})}),q(Y,{height:1,flexShrink:0}),q(Yd,{currentPath:k,tabHint:B.t(`signalBar.tabHint`),counts:{tasks:p.length,delegates:S,edited:h.length,subagents:d.length,clipboard:v,clipboardFailed:y},labels:{tasks:m??B.t(`task.title`),delegates:B.t(`bg.tasksTitle`),edited:B.t(`panelTitle.editedFilesTitle`),subagents:B.t(`hint.subagents`),clipboard:B.t(`signalBar.clipboard`),clipboardFailed:B.t(`signalBar.clipboardFailed`,{modifier:Zd()})}})]})});function $d({items:e,focused:t,onDismiss:n,onLoad:r,onDelete:i,onDeleteMany:a,rows:o=24}){let s=h(),[c,l]=$i(`drafts`,e.length),u=G(0),[d,f]=K(new Set);if(j(`draft-pane`,(t,o)=>{if(o.escape)return d.size>0&&f(new Set),n?.(),!0;if(b(`list-nav-up`,t,o,`draft`))return l(e=>Math.max(0,e-1)),!0;if(b(`list-nav-down`,t,o,`draft`))return l(t=>Math.min(e.length-1,t+1)),!0;if(o.return)return r?.(c),!0;if(t===` `){let t=e[Math.max(0,Math.min(c,e.length-1))];return t&&f(e=>{let n=new Set(e);return n.has(t.id)?n.delete(t.id):n.add(t.id),n}),!0}return t===`d`?(d.size>0?(a?.([...d]),f(new Set)):i?.(c),!0):!1},{isActive:t}),e.length===0&&!t)return null;if(!t)return J(Y,{children:[q(X,{color:s.special,children:`▸ `}),q(D,{type:`secondary`,children:B.t(`draft.sLabel`)}),J(D,{type:`secondary`,children:[` `,e.length]}),J(D,{type:`secondary`,dim:!0,children:[` `,A(`o`)]})]});let p=Rd(c,e.length),m=pt(e,p,ze(e.length,o,7),u.current);return u.current=m.scrollTop,q(y,{header:J(Y,{children:[q(X,{color:s.secondary,bold:!0,children:B.t(`draft.sLabel`)}),J(D,{type:`secondary`,children:[` `,e.length]})]}),footer:q(O,{items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[T.enter,B.t(`hint.load`)],[`space`,B.t(`hint.check`)],[`d`,B.t(`hint.delete`)],[T.esc,B.t(`hint.close`)],[T.tab,B.t(`hint.tabFocus`)]]}),children:J(Y,{marginTop:F.tight,flexDirection:`column`,children:[e.length===0&&q(D,{type:`secondary`,children:B.t(`draft.sEmpty`)}),m.rows.map((e,t)=>{let n=m.scrollTop+t,r=n===p,i=d?.has(e.id)??!1,a=r?s.selection:s.text,o=ae(e.text,51),c=new Date(e.savedAt).toLocaleString();return J(Y,{flexDirection:`row`,children:[q(X,{color:r?s.selection:s.inactive,children:r?`${R.pointer} `:` `}),q(D,{type:`secondary`,children:`${n+1}. `}),q(X,{color:i?s.accent:s.inactive,children:i?`${R.bullet} `:`${R.todoPending} `}),q(X,{color:a,bold:!0,children:e.name}),J(X,{dimColor:!0,children:[` `,o]}),J(X,{dimColor:!0,children:[` `,c]})]},e.id)}),m.fillerCount>0&&Array.from({length:m.fillerCount},(e,t)=>q(X,{children:` `},`filler-${t}`))]})})}function ef({items:e,focused:t,rows:n=24,onDismiss:r,closeConfirmOpen:i=!1,editOpen:a=!1,onDelete:o,onMove:s,onEditOpen:c}){let l=h(),[u,d]=$i(`queue`,e.length),[f,p]=K(!1),m=G(0);if(!t&&f&&p(!1),j(`queue-pane`,(t,n)=>f?t===` `||n.escape?(p(!1),!0):n.upArrow||n.tab&&n.shift?(s?.(u,-1),d(e=>Math.max(0,e-1)),!0):n.downArrow||n.tab&&!n.shift?(s?.(u,1),d(t=>Math.min(e.length-1,t+1)),!0):!0:n.escape?(r?.(),!0):b(`list-nav-up`,t,n,`queue`)?(d(e=>Math.max(0,e-1)),!0):b(`list-nav-down`,t,n,`queue`)?(d(t=>Math.min(e.length-1,t+1)),!0):n.tab&&!n.ctrl&&!n.meta?(d(t=>n.shift?Math.max(0,t-1):Math.min(e.length-1,t+1)),!0):t===` `?(e.length>0&&p(!0),!0):n.return?(e.length>0&&c?.(u),!0):t===`d`?(o?.(u),!0):!1,{isActive:t&&!i&&!a}),!t)return null;let g=Rd(u,e.length),_=pt(e,g,ze(e.length,n,7),m.current);return m.current=_.scrollTop,q(y,{header:J(Y,{children:[q(X,{color:l.secondary,bold:!0,children:B.t(`queue.label`)}),J(D,{type:`secondary`,children:[` `,e.length]})]}),footer:q(O,{items:f?[[`${T.up}${T.down}`,B.t(`hint.move`)],[`space/Esc`,B.t(`hint.drop`)]]:[[`${T.up}${T.down}`,B.t(`hint.select`)],[T.enter,B.t(`hint.edit`)],[`space`,B.t(`hint.grab`)],[`d`,B.t(`hint.delete`)],[T.esc,B.t(`hint.close`)],[T.tab,B.t(`hint.select`)]]}),children:J(Y,{marginTop:F.tight,flexDirection:`column`,children:[e.length===0&&q(D,{type:`secondary`,children:B.t(`queue.empty`)}),_.rows.map((e,t)=>{let n=_.scrollTop+t,r=n===g,i=r&&f,a=i?l.accent:r?l.selection:l.text,o=i?`⇅ `:r?`${R.pointer} `:` `,s=e.mode===`bash_async`?`!! `:e.mode===`bash`?`! `:e.mode===`memory`?`# `:` `,c=e.text.length>60?ae(e.text,61):e.text;return J(Y,{flexDirection:`row`,children:[q(D,{type:`secondary`,children:`${n+1}. `}),q(X,{color:a,bold:r,children:o}),q(X,{color:a,bold:r,children:s}),q(X,{color:a,bold:r,children:c})]},n)}),Array.from({length:_.fillerCount},(e,t)=>q(X,{children:` `},`filler-${t}`))]})})}function tf(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];r.role===`user`&&typeof r.content==`string`&&r.content.trim().length>0&&t.push({text:r.content,index:n})}return t}function nf(e){return Math.max(1,u(e)-5-2)}function rf(e,t){let n=Math.max(20,t-12);return e.map((e,t)=>({value:String(e.index),label:`${t+1}. ${ae(e.text.replace(/\s+/g,` `),n)}`}))}function af({messageStore:e,focused:t,rows:n=24,columns:r=80,onDismiss:i}){let a=tf(Z(e.store,e=>e.messages));if(j(`prompt-log-pane`,(e,t)=>t.escape?(i?.(),!0):!1,{isActive:t,ignoreRoute:!0}),!t)return null;let o=u(n),s=nf(n),c=rf(a,r);return q(y,{maxHeight:o,header:J(Y,{children:[q(D,{type:`secondary`,bold:!0,children:B.t(`prompts.label`)}),J(D,{type:`secondary`,children:[` `,a.length]})]}),footer:q(O,{items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[T.esc,B.t(`hint.close`)]]}),children:a.length===0?q(D,{type:`secondary`,children:B.t(`prompts.empty`)}):q(ot,{id:`prompt-log-list`,tabIndex:0,autoFocus:!0,options:c,maxVisible:s,compact:!0,onSelect:()=>{}})})}function of(e={}){let{columns:t=120,onEmptyBackspace:n,onClearText:r,onCommit:i}=e,[a,o]=K(``),[s,c]=K(0),l=At((e,t)=>{o(e),c(t)},[]);return{text:a,offset:s,update:At((e,t)=>{o(e),c(t)},[]),handleEditing:At((e,o)=>{if(e.length>1&&!o.ctrl&&!o.meta&&!o.return&&!o.escape&&!o.backspace&&!o.delete&&!o.tab&&!o.upArrow&&!o.downArrow&&!o.leftArrow&&!o.rightArrow){let t=Ze(e);return t&&l(a.slice(0,s)+t+a.slice(s),s+t.length),!0}if(o.leftArrow){let e=Ue.fromText(a,t,s).left();return l(e.text,e.offset),!0}if(o.rightArrow){let e=Ue.fromText(a,t,s).right();return l(e.text,e.offset),!0}if((o.backspace||o.delete)&&a.length===0)return n?.(),!0;let c={name:o.backspace?`backspace`:o.delete?`delete`:o.tab?`tab`:o.escape?`escape`:o.return?`return`:e||`unknown`,ctrl:o.ctrl??!1,shift:!1,alt:o.meta??!1,meta:o.meta??!1},u=Ie(Ue.fromText(a,t,s),c);return u?u.action===`clear_text`?(l(``,0),r?.(),!0):u.action===`submit`||u.action===`submit_force`?(i?.(),!0):(l(u.cursor.text,u.cursor.offset),!0):!1},[a,s,t,n,r,l])}}const sf={send:`dialog`,bash:`bash`,bash_async:`bash_async`,memory:`memory`},cf=[`input`,`sendNow`,`confirm`,`cancel`];function lf({index:t,total:n,initialValue:r,mode:i,busy:o,columns:s=60,onSendNow:c,onConfirm:l,onCancel:u}){let[d,f]=K(`input`),{text:m,offset:h,update:g,handleEditing:_}=of({columns:s});V.useEffect(()=>{r&&g(r,r.length)},[]);let v=m.trim()===``,b=e=>{f(cf[(cf.indexOf(d)+e+cf.length)%cf.length])},x=()=>{if(d===`sendNow`){v||c(m);return}if(d===`confirm`){v||l(m);return}if(d===`cancel`){u();return}};j(`queue-edit-dialog`,(e,t)=>{if(t.return&&t.meta){v||c(m);return}if(t.escape){if(d===`input`&&m.length>0){g(``,0);return}u();return}if(t.tab||t.ctrl&&e===`n`){b(1);return}if(d!==`input`){if(t.leftArrow){b(-1);return}if(t.rightArrow){b(1);return}if(t.upArrow){f(`input`);return}if(t.downArrow){b(1);return}if(t.return){x();return}return}if(t.downArrow){b(1);return}if(t.upArrow){b(-1);return}if(t.return){v||f(`confirm`);return}return _(e,t)});let S=o?B.t(`queue.editSendNowHintBusy`):B.t(`queue.editSendNowHintIdle`);return J(y,{header:q(p,{children:B.t(`queue.editTitle`,{index:t,total:n})}),footer:q(O,{items:[[T.tab,B.t(`hint.quick`)],[`${T.up}${T.down}`,B.t(`hint.switch`)],[T.enter,B.t(`hint.confirm`)],[a(),B.t(`queue.editSendNowButton`)],[T.esc,B.t(`hint.cancel`)]]}),children:[q(Y,{marginTop:F.tight,flexDirection:`row`,children:q(e,{value:m,offset:h,columns:s,mode:sf[i],focused:d===`input`})}),J(Y,{marginTop:F.tight,flexDirection:`row`,gap:F.section,children:[q(I,{variant:`solid`,brackets:!0,color:`green`,label:B.t(`queue.editSendNowButton`),focused:d===`sendNow`,disabled:v}),q(I,{variant:`solid`,brackets:!0,color:`accent`,label:B.t(`queue.editConfirmButton`),focused:d===`confirm`,disabled:v}),q(I,{variant:`solid`,brackets:!0,color:`gray`,label:B.t(`common.genericCancelButton`),focused:d===`cancel`})]}),q(Y,{marginTop:F.tight,children:q(D,{type:`secondary`,dim:!0,children:S})})]})}function uf(e,t){let n=t?.length?[...e,...t]:[...e];return{search:(e,t,r=50)=>(e?ar(e,n).map(e=>e.entry):[...n].reverse()).slice(0,r).map(e=>({label:e,value:e,kind:`shortcut`}))}}function df({showHome:e,agentProcessing:t,hasTip:n}){return e||t||!n?0:3}function ff(e){let t=ql(),{currentPath:n,stack:r,navigate:i,goBack:a}=g(),o=r.some(e=>e.path===`/pane/queue`),{columns:s,rows:c,agentProcessing:l,handlePromptEscape:u,pluginInput:d,handleSigilTrigger:f,handleSigilClose:p,handleHistorySearch:m,handleChipReopen:h,handleChipViewPaste:_,handlePasteConfirmRequest:v,welcome:y,historyInsertRef:b,pasteBridgeRef:x,initialHistory:S,externalHistoryCommands:C,residencyGovernor:w,registryRef:T,shellBackendRef:E,sigilState:D,setSigilState:O,sigilApplyRef:ee,readFileContent:te,handleDraftLoad:ne,onQueueEscConfirm:k,queueEscSuppress:re,queueCloseConfirm:ie,setQueueCloseConfirm:A,interruptConfirm:ae,popQueuedConfirm:j,queueEditIndex:oe,setQueueEditIndex:se,scrollStore:M,messageStore:N}=e,{taskStore:ce}=Vl(),P=Z(ce.store,e=>e.forcedUpgrade),le=Z(ce.store,e=>e.commands),ue=Z(ce.store,e=>e.needsSetup),de=Z(ce.store,e=>e.recentMentions),pe=Z(ce.store,e=>e.drafts),me=Z(ce.store,e=>e.queued),he=Z(M.store,e=>e.offset>0),[ge,_e]=K(S??[]),ve=At(e=>{_e(e),t.onHistoryPush?.(e)},[t]),ye=W(()=>uf(ge,C),[ge,C]),be=()=>{se(null),n===`/pane/queue/edit`&&a()},xe=At((e,n,r)=>{t.onSubmit?.(e,n,r);let i=e.trimStart().startsWith(`/`);if(ue&&!i)return`rejected`},[t,ue]);return J(Mt,{children:[e.shadow&&q(Fu,{}),D&&d&&q(Y,{flexDirection:`column`,marginTop:F.tight,children:q(xc,{sigil:D.sigil,initialQuery:D.query,registry:D.mode===`history`?ye:d,active:n===`/pane/sigil`,rows:c,columns:Math.min(60,s-fe.borderInset),viewerColumns:s,readFileContent:te,recentEntries:D.sigil===`@`?de:void 0,title:D.mode===`history`?B.t(`history.label`):void 0,onSelect:e=>{if(O(null),D.mode===`history`){b.current?.fill(e.value);return}ee.current?.select(e),D.sigil===`@`&&t.onSigilSelect?.(e)},onClose:({deleteSigil:e})=>{O(null),ee.current?.cancel(e)}})}),q(Ai,{columns:s-fe.borderInset,rows:c,disabled:!!P||ie||ae||j,reviewing:he,idleTipVisible:!!e.idleTip,commands:le,placeholder:P?B.t(`prompt.upgradeRequired`):l?B.t(`prompt.working`):ue?B.t(`prompt.setup`):B.t(`prompt.default`),onSubmit:xe,onInterrupt:t.onInterrupt,onEscape:u,sigilEnabled:!!d,onSigilTrigger:f,onSigilClose:p,onChipReopen:h,onChipViewPaste:_,onToast:t.onToast,onDraftSave:t.onDraftSave,keybindingOverrides:e.keybindingOverrides,onPasteConfirm:v,cwd:y?.cwd,historyInsertRef:b,pasteBridgeRef:x,initialHistory:S,externalHistoryCommands:C,onHistoryPush:ve,onHistorySearch:m,historySearchOpen:D?.mode===`history`,residencyGovernor:w,registryRef:T,shellBackendRef:E}),q($d,{items:pe,focused:n===`/pane/draft`,onDismiss:t.onToggleDraftPane,onLoad:ne,onDelete:t.onDraftDelete,onDeleteMany:t.onDraftDeleteMany}),N&&n===`/pane/prompts`&&q(Y,{flexDirection:`column`,marginTop:F.tight,children:q(af,{messageStore:N,focused:!0,rows:c,columns:s,onDismiss:()=>t.onTogglePrompts?.()})}),o&&n===`/pane/queue`&&q(Y,{flexDirection:`column`,marginTop:F.tight,children:q(ef,{items:me,focused:!0,rows:c,onDismiss:()=>{ie&&A(!1),t.onToggleQueuePane?.()},onEscConfirm:k,escSuppress:re,closeConfirmOpen:ie,editOpen:oe!==null,onDelete:t.onQueueDelete,onMove:t.onQueueMove,onEditOpen:e=>{se(e),i(`/pane/queue/edit`)}})}),n===`/pane/queue/edit`&&oe!==null&&me[oe]&&q(lf,{index:oe+1,total:me.length,initialValue:me[oe].text,mode:me[oe].mode,busy:l,onSendNow:e=>{t.onQueueSendNow?.(oe,e),be()},onConfirm:e=>{t.onQueueEditText?.(oe,e),be()},onCancel:be}),n!==`/pane/queue`&&!n.startsWith(`/pane/queue/`)&&q(ji,{items:me})]})}function pf(e,t){let n=B.language===`zh`,r=n?`行`:e===1?`line`:`lines`,i=n?`字符`:t===1?`char`:`chars`;return B.t(`paste.previewSummary`,{context:`body`,lines:e,lineWord:r,chars:t,charWord:i})}function mf(e){let t=e.replace(/\n/g,`↵`);return t.length<=16?`[@${t}:]`:`[@${t.slice(0,5)}…${t.slice(-5)}:]`}function hf(e,t){let n=e.split(`
57
+ `);return n.length<=t?e:`${n.slice(0,t).join(`
58
+ `)}\n${pf(n.length,e.length)}`}function gf({content:e,previewLines:t=10,rows:n=24,columns:r=80,onConfirm:i,onCancel:a}){let o=h(),[s,c]=K(0),[l,u]=K(!1),d=G(0);d.current=s;let f=G(!1);U(()=>{let e=setTimeout(()=>{f.current=!0},0);return()=>{clearTimeout(e)}},[]);let m=hf(e,t),g=mf(e),_=W(()=>e.split(`
59
+ `),[e]);return j(`paste-confirm-dialog-buttons`,(e,t)=>{if(l)return!1;if(t.escape)return f.current&&a(),!0;if(t.leftArrow||t.rightArrow||t.tab){if(f.current){let e=E(t);e!==0&&c(t=>Le(t,e,3))}return!0}return t.return?(f.current&&c(e=>(e===0?i():e===1?u(!0):a(),e)),!0):!1}),l?q(rc,{lines:_,rows:n,columns:r,header:J(Y,{children:[q(X,{color:o.selection,children:B.t(`paste.viewTitle`)}),J(D,{type:`secondary`,children:[` `,pf(_.length,e.length)]})]}),onDismiss:()=>u(!1),initialScroll:`top`,contentKey:e}):J(y,{header:q(p,{children:B.t(`paste.confirmTitle`)}),footer:q(O,{items:[[`${T.left}${T.right}`,B.t(`hint.switch`)],[T.enter,`${B.t(`hint.confirm`)}/${B.t(`paste.view`)}`],[T.esc,B.t(`hint.cancel`)]]}),children:[q(Y,{marginTop:F.tight,flexDirection:`column`,children:q(D,{type:`secondary`,children:m})}),J(Y,{marginTop:F.tight,children:[q(X,{dimColor:!0,children:B.t(`paste.collapseLabel`)}),q(X,{color:o.selection,children:g})]}),J(Y,{marginTop:F.tight,flexDirection:`row`,gap:F.section,children:[q(I,{variant:`solid`,brackets:!0,color:`amber`,label:B.t(`paste.confirm`),focused:s===0}),q(I,{variant:`solid`,brackets:!0,color:`gray`,label:B.t(`paste.view`),focused:s===1}),q(I,{variant:`solid`,brackets:!0,color:`gray`,label:B.t(`paste.cancel`),focused:s===2})]})]})}function _f(e,t){let n=Math.floor((t-e)/1e3);return n<60?B.t(`time.justNow`):n<3600?B.t(`time.minAgo`,{min:Math.floor(n/60)}):n<86400?B.t(`time.hourAgo`,{hr:Math.floor(n/3600)}):B.t(`time.dayAgo`,{day:Math.floor(n/86400)})}function vf(e,t){return e===`error`?t.error:e===`warning`?t.warning:t.inactive}function yf({notifications:e,onClose:t,rows:n=24}){let r=h();j(`notification-center`,(e,n)=>n.escape?(t(),!0):!1);let[i,a]=K(()=>Date.now()),o=G(0);U(()=>{let e=setInterval(()=>a(Date.now()),3e4);return()=>clearInterval(e)},[]);let s=e.filter(e=>!e.read),c=e.filter(e=>e.read),l=[...s,...c];if(l.length===0)return null;let u=pt(l,-1,ee(l.length+6,n)-6,o.current);return o.current=u.scrollTop,q(y,{header:J(Y,{marginBottom:F.tight,children:[q(X,{color:r.secondary,bold:!0,children:B.t(`notif.title`)}),s.length>0&&J(X,{color:r.accent,children:[` `,s.length]})]}),footer:q(O,{items:[[`${T.up}${T.down}`,B.t(`hint.scroll`)],[T.enter,B.t(`hint.dismiss`)],[T.esc,B.t(`hint.close`)],[T.tab,B.t(`hint.tabFocus`)]]}),children:u.rows.map((e,t)=>J(Y,{flexDirection:`column`,children:[u.scrollTop+t===s.length&&c.length>0&&s.length>0&&q(Y,{marginY:F.tight,children:q(D,{type:`secondary`,dim:!0,children:B.t(`notif.readDivider`)})}),J(Y,{flexDirection:`row`,children:[q(X,{color:vf(e.level,r),children:e.level===`error`?R.cross:e.level===`warning`?R.warn:`i`}),q(D,{type:`secondary`,children:` `}),J(X,{color:e.read?r.inactive:r.secondary,dimColor:e.read,wrap:`truncate-end`,children:[`[`,e.source,`] `,e.title,` · `,e.message]}),J(D,{type:`secondary`,dim:!0,children:[` `,`(`,_f(e.timestamp,i),`)`]})]})]},e.id))})}function bf({focusOwner:e,pasteContent:t,onPasteConfirm:n,onPasteCancel:r,notifications:i,rows:a,columns:o}){let{onDismissNotification:s,onCloseNotifications:c}=ql();return J(Mt,{children:[t!=null&&q(v,{path:`/overlay/paste-confirm`,inStack:!0,element:q(gf,{content:t,rows:a,columns:o,onConfirm:n,onCancel:r})}),e===`notifications`&&q(yf,{notifications:i,onDismiss:e=>s?.(e),onClose:()=>c?.()})]})}function xf({component:t,columns:n=60,onAction:r,onDismiss:i}){let a=h(),o=t.fields??[],s=t.formTitle??`表单`,[c,l]=K(At(()=>{let e={},t={},n={};for(let r of o)if(r.type===`toggle`)t[r.id]=r.defaultValue===!0;else{let t=r.defaultValue==null?``:String(r.defaultValue);e[r.id]=t,n[r.id]=t.length}return{strings:e,toggles:t,offsets:n}},[o])),[u,d]=K({kind:`field`,index:0}),f=u.kind===`field`?u.index:-1,m=o.length,g=f>=0&&f<m?o[f]:void 0,_=(e,t,n)=>{l(r=>({strings:{...r.strings,[e]:t},toggles:r.toggles,offsets:{...r.offsets,[e]:n}}))},v=e=>{l(t=>({strings:t.strings,toggles:{...t.toggles,[e]:!(t.toggles[e]??!1)},offsets:t.offsets}))},b=()=>{u.kind===`field`&&u.index<m-1?d({kind:`field`,index:u.index+1}):d({kind:`submit`})},x=()=>{u.kind===`submit`?d({kind:`field`,index:Math.max(0,m-1)}):u.kind===`cancel`?d({kind:`submit`}):u.kind===`field`&&u.index>0&&d({kind:`field`,index:u.index-1})},S=()=>{let e={};for(let t of o)t.type===`toggle`?e[t.id]=c.toggles[t.id]??!1:e[t.id]=c.strings[t.id]??``;let n=t.action??`submit`;r(t.id,n,e)};j(`a2ui-form-dialog`,(e,t)=>{if(t.escape){if(u.kind===`field`){if(g?.type===`text`&&(c.strings[g.id]??``).length>0){_(g.id,``,0);return}x();return}i();return}if(t.tab||t.ctrl&&e===`n`){b();return}if(t.return&&t.meta){S();return}if(u.kind!==`field`){if(t.leftArrow){x();return}if(t.rightArrow){b();return}if(t.return&&u.kind===`submit`){S();return}if(t.return&&u.kind===`cancel`){i();return}return}if(g){if(t.upArrow){x();return}if(t.downArrow){b();return}if(t.return){f>=m-1?S():b();return}if(g.type===`text`){let r=g.id,i=c.strings[r]??``,a=c.offsets[r]??0;if(t.leftArrow){let e=Ue.fromText(i,n,a).left();_(r,e.text,e.offset);return}if(t.rightArrow){let e=Ue.fromText(i,n,a).right();_(r,e.text,e.offset);return}if(e.length>1&&!t.ctrl&&!t.meta&&!t.return&&!t.escape&&!t.backspace&&!t.delete&&!t.tab&&!t.upArrow&&!t.downArrow&&!t.leftArrow&&!t.rightArrow){let t=Ze(e);t&&_(r,i.slice(0,a)+t+i.slice(a),a+t.length);return}let o={name:t.backspace?`backspace`:t.delete?`delete`:t.tab?`tab`:e||`unknown`,ctrl:t.ctrl??!1,shift:t.shift??!1,alt:t.meta??!1,meta:t.meta??!1},s=Ie(Ue.fromText(i,n,a),o);if(!s)return;if(s.action===`clear_text`){_(r,``,0);return}_(r,s.cursor.text,s.cursor.offset);return}if(g.type===`select`){t.leftArrow?x():t.rightArrow&&b();return}if(g.type===`toggle`&&e===` `){v(g.id);return}}});let C=o.map(e=>e.label).join(` · `);return J(y,{header:q(p,{children:s}),footer:q(O,{items:[[T.tab,`next`],[T.enter,B.t(`hint.confirm`)],[T.esc,B.t(`hint.cancel`)]]}),children:[q(Y,{flexDirection:`column`,marginTop:F.tight,children:q(D,{type:`secondary`,dim:!0,children:C})}),q(Y,{flexDirection:`column`,marginTop:F.tight,children:o.map((t,r)=>{let i=u.kind===`field`&&u.index===r,o=t.required?` *`:``;return J(Y,{flexDirection:`column`,marginBottom:F.tight,children:[J(Y,{flexDirection:`row`,children:[q(X,{color:i?a.selection:a.inactive,children:i?`${R.pointer} `:` `}),J(X,{bold:i,color:i?a.selection:void 0,children:[t.label,o]})]}),t.type===`text`&&q(Y,{flexDirection:`row`,marginLeft:F.section,children:q(e,{value:c.strings[t.id]??``,offset:c.offsets[t.id]??0,columns:n-4,mode:`dialog`,focused:i,placeholder:t.placeholder})}),t.type===`select`&&q(Y,{flexDirection:`row`,gap:F.tight,marginLeft:F.section,children:q(X,{dimColor:!i,color:i?a.selection:a.inactive,children:(t.options??[]).map((e,n)=>J(V.Fragment,{children:[i?J(X,{color:c.strings[t.id]===e.id?a.selection:a.inactive,children:[c.strings[t.id]===e.id?`${R.toggleOn} `:`${R.toggleOff} `,e.label]}):q(D,{type:`secondary`,children:e.label}),n<(t.options??[]).length-1&&q(D,{type:`secondary`,children:` · `})]},e.id))})}),t.type===`toggle`&&q(Y,{flexDirection:`row`,marginLeft:F.section,children:J(X,{color:i?a.selection:a.inactive,children:[c.toggles[t.id]?R.check:R.cross,` `,c.toggles[t.id]?`enabled`:`disabled`]})}),![`text`,`select`,`toggle`].includes(t.type)&&q(Y,{flexDirection:`row`,marginLeft:F.section,children:q(D,{type:`secondary`,dim:!0,children:String(c.strings[t.id]??``)||`?`})})]},t.id)})}),J(Y,{flexDirection:`row`,gap:F.tight,marginTop:F.tight,children:[q(I,{variant:`solid`,brackets:!0,color:`accent`,label:B.t(`prompt.submit`),focused:u.kind===`submit`}),q(I,{variant:`solid`,brackets:!0,color:`gray`,label:B.t(`common.genericCancelButton`),focused:u.kind===`cancel`})]})]})}function Sf({columns:e}){let{state:t}=ce(),n=t;return n?q(xf,{component:n.component,columns:e,onAction:n.onAction,onDismiss:n.onDismiss}):null}function Cf({onOk:e}){let{state:t}=ce(),n=t;return n?q(Ol,{title:n.title,message:n.message,okLabel:n.okLabel,onOk:e}):null}function wf({onConfirm:e,onCancel:t,onExtra:n}){let{state:r}=ce(),i=r,a=G(t);return a.current=t,U(()=>()=>{a.current()},[]),i?q(Ve,{title:i.title,message:i.message,confirmLabel:i.confirmLabel,cancelLabel:i.cancelLabel,confirmColor:i.confirmColor,dangerous:i.dangerous,extraLabel:i.extraLabel,extraColor:i.extraColor,onConfirm:e,onCancel:t,onExtra:i.extraLabel?n:void 0}):null}function Tf(e,t){switch(e){case`warn`:return t.warning;case`error`:return t.error;default:return}}function Ef(e){let t=Date.now()-e,n=Math.floor(t/1e3);if(n<60)return`${n}s ago`;let r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}function Df({req:e,rows:t=24,columns:r=80}){let i=h(),[a,o]=K(0),s=(yt()?.currentPath??`/`)===`/dialog/extension/full-text`,c=e=>{let t=M();t&&(e&&t.currentPath===`/dialog/extension`?t.navigate(`/dialog/extension/full-text`):!e&&t.currentPath===`/dialog/extension/full-text`&&t.goBack())},[l,u]=K(0),[d,f]=K(Ca());U(()=>{c(!1),u(0)},[e.fullText]),U(()=>{if(d)return;let e=!0;return Sa().then(()=>{e&&f(Ca())}),()=>{e=!1}},[d]);let m=W(()=>e.fullText?e.fullText.kind===`plain`?[{id:`plain`,label:`Plain`,lines:e.fullText.content.split(`
60
+ `),wrapMode:`pre-wrap`}]:pc(`${e.fullText.title}.md`,e.fullText.content,r,d):[],[e.fullText,r,d]),g=m[Math.min(l,Math.max(0,m.length-1))],_=g?.lines??[],v=e.panelInfo&&e.onOpenPanel?[...e.actions,{label:B.t(`cmd.extPluginOpenPanelLabel`,{title:(()=>{let t=e.panelInfo.title;return t.includes(`.`)&&!t.includes(` `)?B.t(t):t})()}),value:`open-panel`,color:`accent`}]:e.actions,b=v.length;j(`extension-detail-dialog`,(t,n)=>{if(n.escape)return e.onClose(),!0;if(t===`r`&&e.onRefresh)return e.onRefresh(),!0;if(b===0)return!1;if(n.leftArrow)return o(e=>(e-1+b)%b),!0;if(n.rightArrow)return o(e=>(e+1)%b),!0;if(n.return){let t=v[a];return t?t.value===`open-panel`?(e.onOpenPanel?.(),!0):t.value===`view-full-text`?(e.fullText&&c(!0),!0):(e.onAction(t.value),!0):!1}return!1},{isActive:!s});let x=e.healthStats,S=x&&(x.hookTimeouts>0||x.toolTimeouts>0||x.lastError!==void 0),C=[[`← →`,B.t(`hint.select`)],[`Enter`,B.t(`hint.execute`)]];return e.onRefresh&&C.push([`r`,B.t(`cmd.extRefreshHint`)]),C.push([`Esc`,B.t(`hint.close`)]),s&&e.fullText?q(rc,{lines:_,rows:t,columns:r,wrapMode:g?.wrapMode??`pre-wrap`,header:J(Y,{children:[q(X,{color:i.selection,children:e.fullText.title}),m.length>1&&g?q(n,{leadingSpace:!0,children:g.label}):null]}),onDismiss:()=>c(!1),onKey:(e,t)=>e===`]`&&m.length>1?(u(e=>(e+1)%m.length),!0):!1,extraHints:m.length>1?[[`]`,B.t(`hint.tabSwitchOutput`)]]:void 0,initialScroll:`top`,contentKey:`${e.fullText.title}:${g?.id??``}`}):q(y,{header:q(p,{children:e.title}),footer:q(O,{items:C}),children:J(Y,{marginTop:F.tight,flexDirection:`column`,children:[e.meta||e.metaStatus?J(X,{children:[e.meta?q(X,{dimColor:!0,children:e.meta}):null,e.metaStatus?J(Mt,{children:[q(X,{dimColor:!0,children:e.meta?` · `:``}),q(X,{color:e.metaStatus.enabled?i.success:i.error,children:e.metaStatus.label})]}):null,e.metaSuffix?J(X,{dimColor:!0,children:[` · `,e.metaSuffix]}):null]}):null,b>0?q(Y,{marginTop:F.tight,children:v.map((e,t)=>q(Y,{marginRight:F.tight,children:q(I,{variant:`solid`,brackets:!0,label:e.label,focused:t===a,color:e.color??`accent`})},e.value))}):null,q(Y,{marginTop:F.tight,flexDirection:`column`,children:e.dataListEntries&&e.dataListEntries.length>0?q(Ye,{entries:e.dataListEntries}):e.info&&e.info.length>0?e.info.map((e,t)=>q(X,{wrap:`truncate-end`,children:e===``?` `:e},t)):q(X,{dimColor:!0,children:`(无详情视图)`})}),S&&q(Y,{marginTop:F.tight,children:q(X,{color:i.warning,children:x.lastError?.message?B.t(`cmd.extHealthSummary`,{context:`err`,hookTimeouts:x.hookTimeouts,toolTimeouts:x.toolTimeouts,lastError:x.lastError.message}):B.t(`cmd.extHealthSummary`,{hookTimeouts:x.hookTimeouts,toolTimeouts:x.toolTimeouts})})}),e.logEntries!==void 0&&J(Y,{marginTop:F.tight,flexDirection:`column`,children:[q(X,{dimColor:!0,bold:!0,children:B.t(`cmd.extLogSectionTitle`)}),e.logEntries.length===0?q(D,{type:`secondary`,dim:!0,children:B.t(`cmd.extNoLogs`)}):e.logEntries.map((e,t)=>q(X,{color:Tf(e.level,i),wrap:`truncate-end`,children:` ${Ef(e.ts)} ${e.msg}`},t))]})]})})}function Of({rows:e,columns:t}){let{state:n}=ce(),r=n;return r?q(Df,{req:r,rows:oe(e??24),columns:t}):null}function kf({rows:e}){let{state:t}=ce(),n=t;return n?q(xl,{req:n,rows:e}):null}function Af({req:e,rows:t,columns:r,active:i=!0,findActive:a,onFindModeChange:o}){let s=h(),[c,l]=K(0),[u,d]=K(Ca());U(()=>{if(u)return;let e=!0;return Sa().then(()=>{e&&d(Ca())}),()=>{e=!1}},[u]),U(()=>{l(0)},[e.path]);let f=W(()=>pc(e.path,e.content,r,u,e.preTruncated),[e.path,e.content,r,u,e.preTruncated]),p=f[Math.min(c,Math.max(0,f.length-1))];return q(rc,{lines:p?.lines??[],rows:t,columns:r,wrapMode:p?.wrapMode??`pre-wrap`,header:J(Y,{children:[q(X,{color:s.selection,children:e.path}),f.length>1&&p?q(n,{leadingSpace:!0,children:p.label}):null]}),onDismiss:e.onDismiss,onKey:(e,t)=>e===`]`&&f.length>1?(l(e=>(e+1)%f.length),!0):!1,extraHints:f.length>1?[[`]`,B.t(`hint.tabSwitchOutput`)]]:void 0,initialScroll:`top`,active:i,contentKey:`${e.path}:${p?.id??``}`,findActive:a,onFindModeChange:o})}function jf({rows:e,columns:t}){let{goBack:n,currentPath:r}=g(),a=i(`/viewer/file`),o=G(!1),s=G(a?.onDismiss);if(s.current=a?.onDismiss,U(()=>()=>{o.current||(o.current=!0,s.current?.())},[]),!a)return null;let c=r===`/viewer/file/find`,l=e=>{let t=M();t&&(e&&t.currentPath===`/viewer/file`?t.navigate(`/viewer/file/find`):!e&&t.currentPath===`/viewer/file/find`&&t.goBack())},u=()=>{o.current=!0,n(),a.onDismiss?.()};return q(Af,{req:{...a,onDismiss:u},rows:e,columns:t,active:!0,findActive:c,onFindModeChange:l})}function Mf({rows:e,columns:t}){let{goBack:n,currentPath:r}=g(),a=i(`/viewer/clipboard`)?.content??``,o=V.useMemo(()=>a.split(`
61
+ `),[a]),s=r===`/viewer/clipboard/find`;return q(rc,{lines:o,rows:e,columns:t,wrapMode:`pre-wrap`,header:J(Y,{flexDirection:`row`,justifyContent:`space-between`,children:[q(p,{children:B.t(`clipboard.viewerTitle`)}),q(X,{dimColor:!0,children:B.t(`clipboard.charsLabel`,{count:Array.from(a).length})})]}),onDismiss:n,initialScroll:`top`,active:!0,contentKey:`clipboard`,emptyMessage:B.t(`clipboard.empty`),findActive:s,onFindModeChange:e=>{let t=M();t&&(e&&t.currentPath===`/viewer/clipboard`?t.navigate(`/viewer/clipboard/find`):!e&&t.currentPath===`/viewer/clipboard/find`&&t.goBack())}})}function Nf({req:e,rows:t,columns:n,active:r=!0}){let i=h(),a=(yt()?.currentPath??`/`)===`/viewer/help/find`;return q(rc,{lines:e.lines,rows:t,columns:n,wrapMode:`truncate`,header:q(Y,{children:q(X,{color:i.selection,children:e.title})}),onDismiss:e.onDismiss,initialScroll:`top`,active:r,contentKey:e.title,findActive:a,onFindModeChange:e=>{let t=M();t&&(e&&t.currentPath===`/viewer/help`?t.navigate(`/viewer/help/find`):!e&&t.currentPath===`/viewer/help/find`&&t.goBack())}})}function Pf({rows:e,columns:t}){let{goBack:n}=g(),r=i(`/viewer/help`),a=G(!1),o=G(r?.onDismiss);if(o.current=r?.onDismiss,U(()=>()=>{a.current||(a.current=!0,o.current?.())},[]),!r)return null;let s=()=>{a.current=!0,n(),r.onDismiss?.()};return q(Nf,{req:{...r,onDismiss:s},rows:e,columns:t,active:!0})}function Ff({onDismiss:e}){let{state:t}=ce(),n=t;return n?q(ve,{title:n.title,lines:n.lines,onDismiss:e,action:n.action,lineTones:n.lineTones,dataListEntries:n.dataListEntries}):null}function If({title:t,description:n,placeholder:r,mask:i,defaultValue:a,onSubmit:o,onCancel:s,columns:c=60,actionButton:l,onActionButton:u}){let d=h(),{text:f,offset:m,update:g,handleEditing:_}=of({columns:c,onCommit:()=>o(f)});return U(()=>{a&&g(a,a.length)},[]),Re({tabIndex:0,id:`input-field`,onAction:()=>(o(f),!0),onEscape:()=>f.length===0?(s?.(),!0):(g(``,0),!0)}),j(`input-dialog`,(e,t)=>{if(t.ctrl&&e===`o`&&l&&u){u();return}if(t.escape&&f.length===0){s?.();return}return _(e,t)}),J(y,{header:t?q(p,{children:t}):void 0,footer:q(O,{items:l?[[`Ctrl+O`,l.label],[T.enter,B.t(`hint.confirm`)],[T.esc,B.t(`hint.cancel`)]]:[[T.enter,B.t(`hint.confirm`)],[T.esc,B.t(`hint.cancel`)]]}),children:[t&&q(Y,{marginTop:F.tight}),n&&n.length>0&&q(Y,{flexDirection:`column`,marginBottom:F.tight,children:n.map((e,t)=>q(X,{color:d.text,wrap:`wrap`,children:e},t))}),q(Y,{flexDirection:`row`,children:q(e,{value:f,offset:m,columns:c,mode:`dialog`,placeholder:r,mask:i,focused:!0,physicalCursor:!0})}),l&&J(Y,{marginTop:F.tight,flexDirection:`row`,children:[q(D,{type:`secondary`,children:` `}),q(I,{variant:`solid`,brackets:!0,color:`accent`,label:l.label,focused:!1})]})]})}function Lf({onSubmit:e,onCancel:t,onAction:n,columns:r}){let{state:i}=ce(),a=i,o=G(t);return o.current=t,U(()=>()=>{o.current()},[]),a?q(If,{title:a.title,description:a.description,placeholder:a.placeholder,mask:a.mask,defaultValue:a.defaultValue,columns:Math.min(60,r-fe.borderInset),onSubmit:e,onCancel:t,actionButton:a.actionButton,onActionButton:n}):null}const Rf=[{commandId:`inspector-continue`,description:`Inspector:继续执行`,keyLabel:`c`},{commandId:`inspector-step`,description:`Inspector:单步执行`,keyLabel:`s`},{commandId:`inspector-next`,description:`Inspector:下一节点`,keyLabel:`n`},{commandId:`inspector-out`,description:`Inspector:跳出当前`,keyLabel:`o`},{commandId:`inspector-exit`,description:`Inspector:退出调试`,keyLabel:`x`},{commandId:`background-kill`,description:`后台:终止任务`,keyLabel:`k`},{commandId:`background-view-output`,description:`后台:查看输出`,keyLabel:`o`},{commandId:`background-apply`,description:`后台:应用更改`,keyLabel:`a`},{commandId:`background-switch`,description:`后台:切换面板`,keyLabel:`s`},{commandId:`background-delete`,description:`后台:删除任务`,keyLabel:`d`}];function zf(e){let t=new Map;function n(n,r){for(let i of n){if(t.has(i.commandId))continue;let n=he(i.commandId,i.predicate,e);t.set(i.commandId,{commandId:i.commandId,description:i.description,group:r,defaultPredicate:i.predicate,effectivePredicate:n,isOverridden:!Bf(n,i.predicate),isUnassigned:de(n)})}}return n(re,`global`),n(tt,`navigation`),[...t.values()]}function Bf(e,t){return e.ctrl===t.ctrl&&e.shift===t.shift&&e.meta===t.meta&&e.input===t.input&&e.key===t.key&&e.upArrow===t.upArrow&&e.downArrow===t.downArrow}function Vf(e,t){if(!t.trim())return[...e];let n=t.toLowerCase();return e.filter(e=>e.commandId.toLowerCase().includes(n)||e.description.toLowerCase().includes(n))}function Hf(e=`project`){return{mode:`list`,searchQuery:``,selectedIndex:0,writeTarget:e}}function Uf(e,t,n,r){let i={state:e,effects:[]};switch(t.type){case`moveUp`:{if(e.mode!==`list`)return i;let t=Math.max(0,e.selectedIndex-1);return{state:{...e,selectedIndex:t},effects:[]}}case`moveDown`:{if(e.mode!==`list`)return i;let t=Math.max(0,n.length-1),r=Math.min(t,e.selectedIndex+1);return{state:{...e,selectedIndex:r},effects:[]}}case`setSearch`:return e.mode===`list`?{state:{...e,searchQuery:t.query,selectedIndex:0},effects:[]}:i;case`startRecording`:{if(e.mode!==`list`)return i;let t=n[e.selectedIndex];return!t||t.group===`reserved`?i:{state:{...e,mode:`recording`,recordingCommandId:t.commandId,pendingConflict:void 0},effects:[]}}case`cancelRecording`:return e.mode===`recording`?{state:{...e,mode:`list`,recordingCommandId:void 0,pendingConflict:void 0},effects:[]}:i;case`recordKey`:{if(e.mode!==`recording`||!e.recordingCommandId||t.escape)return i;let n=Wf(t);if(!n)return i;let a=S(e.recordingCommandId,n,`*`,r);return a?{state:{...e,pendingConflict:{conflictsWith:a.conflictsWith,newPredicate:n}},effects:[]}:{state:{...e,mode:`list`,recordingCommandId:void 0,pendingConflict:void 0},effects:[{type:`saveKeybinding`,commandId:e.recordingCommandId,predicate:n}]}}case`confirmConflict`:return e.mode!==`recording`||!e.pendingConflict||!e.recordingCommandId?i:{state:{...e,mode:`list`,recordingCommandId:void 0,pendingConflict:void 0},effects:[{type:`saveReplaceKeybinding`,actions:[{commandId:e.pendingConflict.conflictsWith,predicate:{}},{commandId:e.recordingCommandId,predicate:e.pendingConflict.newPredicate}]}]};case`cancelConflict`:return e.mode===`recording`?{state:{...e,pendingConflict:void 0},effects:[]}:i;case`close`:return e.mode===`recording`?{state:{...e,mode:`list`,recordingCommandId:void 0,pendingConflict:void 0},effects:[]}:{state:e,effects:[{type:`closePanel`}]};case`resetSingle`:{if(e.mode!==`list`)return i;let t=n[e.selectedIndex];return!t||!t.isOverridden?i:{state:e,effects:[{type:`resetKeybinding`,commandId:t.commandId}]}}case`resetAll`:return e.mode===`list`?{state:e,effects:[{type:`resetAllKeybindings`}]}:i;case`toggleWriteTarget`:return{state:{...e,writeTarget:e.writeTarget===`global`?`project`:`global`},effects:[]};default:return i}}function Wf(e){let t={};if(e.ctrl&&(t.ctrl=!0),e.shift&&(t.shift=!0),e.meta&&(t.meta=!0),e.upArrow)t.upArrow=!0;else if(e.downArrow)t.downArrow=!0;else if(e.return)t.key=`return`;else if(e.tab)t.key=`tab`;else if(e.escape)t.key=`escape`;else if(e.input&&e.input.length>0)t.input=e.input;else return null;return t}function Gf(e){if(de(e))return`(未分配)`;let t=[];return e.ctrl&&t.push(`Ctrl`),e.shift&&t.push(`Shift`),e.meta&&t.push(`Meta`),e.upArrow?t.push(`↑`):e.downArrow?t.push(`↓`):e.key===`return`?t.push(`↵`):e.key===`tab`?t.push(`Tab`):e.key===`escape`?t.push(`Esc`):e.input!==void 0&&t.push(e.input.toUpperCase()),t.join(`+`)||`(未分配)`}function Kf(e,t){if(!t.upArrow&&!t.downArrow)return[];let n=[];for(let t of tt)t.commandId===e&&(t.predicate.upArrow||t.predicate.downArrow||(t.predicate.input?n.push(t.predicate.input):t.predicate.key===`tab`&&n.push(Gf(t.predicate))));return n}function qf(e,t){if(e.isOverridden&&!e.isUnassigned)return Gf(e.effectivePredicate);let n=Kf(e.commandId,e.defaultPredicate);return n.length>0?[Gf(e.defaultPredicate),...n].join(` / `):Gf(e.defaultPredicate)}function Jf({overrides:e,onSave:t,onSaveReplace:n,onReset:r,onResetAll:i,onDismiss:a}){let o=h(),[s,c]=K(()=>Hf(`project`)),[l,u]=K(!1),d=W(()=>zf(e),[e]),f=W(()=>Vf(d,s.searchQuery),[d,s.searchQuery]),m=At(o=>{c(s=>{let c=Uf(s,o,f,e);for(let e of c.effects)switch(e.type){case`closePanel`:a();break;case`saveKeybinding`:t(e.commandId,e.predicate,s.writeTarget);break;case`saveReplaceKeybinding`:n(e.actions,s.writeTarget);break;case`resetKeybinding`:r(e.commandId);break;case`resetAllKeybindings`:i();break}return c.state})},[f,e,a,t,n,r,i]);return j(`keybinding-panel-dialog`,(e,t)=>{if(l){if(t.escape){u(!1);return}if(t.return){m({type:`resetAll`}),u(!1);return}return}if(s.mode===`recording`&&s.pendingConflict){if(t.escape){m({type:`cancelConflict`});return}if(t.return){m({type:`confirmConflict`});return}return}if(s.mode===`recording`){if(t.escape){m({type:`cancelRecording`});return}m({type:`recordKey`,input:e,ctrl:t.ctrl,shift:t.shift,meta:t.meta,upArrow:t.upArrow,downArrow:t.downArrow,return:t.return,escape:t.escape,tab:t.tab});return}if(s.mode===`list`){if(t.escape){s.searchQuery?m({type:`setSearch`,query:``}):m({type:`close`});return}if(t.ctrl&&e===`r`){u(!0);return}if(e===`r`&&!t.ctrl&&!t.meta){m({type:`resetSingle`});return}if(e&&e.length===1&&!t.ctrl&&!t.meta&&/^[a-zA-Z0-9]$/.test(e)){m({type:`setSearch`,query:s.searchQuery+e});return}if(t.delete||e===``&&t.backspace){s.searchQuery.length>0&&m({type:`setSearch`,query:s.searchQuery.slice(0,-1)});return}}}),l?q(y,{header:q(p,{children:`快捷键设置`}),children:J(Y,{marginTop:F.tight,flexDirection:`column`,children:[q(X,{color:o.warning,children:`确认清空全部快捷键覆盖设置,恢复为默认值?`}),J(Y,{marginTop:F.section,flexDirection:`row`,gap:F.section,children:[q(I,{variant:`solid`,brackets:!0,label:B.t(`common.genericCancelButton`),focused:!1,color:`gray`}),q(I,{variant:`solid`,brackets:!0,label:B.t(`confirm.reset`),focused:!0,color:`red`})]})]})}):s.mode===`recording`?q(Xf,{entries:f,selectedIndex:s.selectedIndex,recordingCommandId:s.recordingCommandId,pendingConflict:s.pendingConflict,searchQuery:s.searchQuery,writeTarget:s.writeTarget}):q(Yf,{entries:f,searchQuery:s.searchQuery,writeTarget:s.writeTarget,onEnterRecording:()=>m({type:`startRecording`}),onMoveUp:()=>m({type:`moveUp`}),onMoveDown:()=>m({type:`moveDown`}),onDismiss:a})}function Yf({entries:e,searchQuery:t,writeTarget:n,onEnterRecording:r,onDismiss:i}){let a=h(),o=[{group:`global`,label:`全局命令(${e.filter(e=>e.group===`global`).length})`,items:e.filter(e=>e.group===`global`)},{group:`navigation`,label:`列表导航(${e.filter(e=>e.group===`navigation`).length})`,items:e.filter(e=>e.group===`navigation`)},{group:`reserved`,label:`系统保留(${Rf.length})`,items:Rf.map(e=>({commandId:e.commandId,description:e.description,group:`reserved`,defaultPredicate:{},effectivePredicate:{},isOverridden:!1,isUnassigned:!1}))}],s=n===`global`?`全局配置`:`项目配置`;return q(z.Root,{title:`快捷键设置 写入:${s}`,subtitle:t?`搜索:"${t}"`:void 0,onCancel:i,onValueChange:()=>{r()},onKey:(e,t,n)=>!1,footer:J(Mt,{children:[q(O,{items:[[`${T.up}${T.down}`,`选择`],[T.enter,`修改键位`],[`r`,`重置当前`],[`Ctrl+R`,`全部重置`],[T.esc,`关闭`]]}),`
62
+ `,J(D,{type:`secondary`,dim:!0,children:[`搜索:直接输入字符筛选 · 写入目标:`,s,`(按 t 切换)`]})]}),children:q(z.Content,{children:o.map(e=>J(z.Group,{children:[q(z.Label,{children:e.label}),e.group===`reserved`?Rf.map(e=>q(z.Item,{value:e.commandId,disabled:!0,trailingLabel:e.keyLabel,trailingColor:a.inactive,children:e.description},e.commandId)):e.items.map(e=>{let t=qf(e,void 0),n=e.isOverridden&&!e.isUnassigned,r=e.isUnassigned;return q(z.Item,{value:e.commandId,trailingLabel:r?`(未分配)`:t,trailingColor:n?a.warning:void 0,labelColor:n?a.warning:void 0,children:e.description},e.commandId)})]},e.group))})})}function Xf({entries:e,selectedIndex:t,recordingCommandId:n,pendingConflict:r,searchQuery:i,writeTarget:a}){let o=h(),s=a===`global`?`全局配置`:`项目配置`,c=r?e.find(e=>e.commandId===r.conflictsWith):void 0;return q(y,{header:q(p,{children:`快捷键设置 写入:${s}`}),footer:q(O,{items:r?[[T.enter,`确认替换`],[T.esc,`取消`]]:[[T.esc,`取消录制`]]}),children:J(Y,{marginTop:F.tight,flexDirection:`column`,children:[i&&J(D,{type:`secondary`,dim:!0,children:[`搜索:"`,i,`"`]}),r&&J(Y,{marginBottom:F.tight,children:[J(X,{color:o.error,children:[`与『`,c?.description??r.conflictsWith,`』冲突——替换后该命令将无键位,需手动重新分配`]}),J(Y,{marginTop:F.tight,flexDirection:`row`,gap:F.section,children:[q(I,{variant:`solid`,brackets:!0,label:B.t(`confirm.replace`),focused:!0,color:`red`}),q(I,{variant:`solid`,brackets:!0,label:B.t(`common.genericCancelButton`),focused:!1,color:`gray`})]})]}),e.map((e,r)=>{let i=e.commandId===n,a=qf(e,void 0),s=e.isOverridden&&!e.isUnassigned,c=r===t,l=c?`${R.pointer} `:` `;return q(Y,{flexDirection:`column`,children:J(Y,{flexDirection:`row`,children:[J(X,{color:i?o.accent:c?o.selection:s?o.warning:void 0,bold:c,children:[l,e.description]}),q(D,{type:`secondary`,children:` `}),q(X,{color:i?o.accent:s?o.warning:o.inactive,children:i?`按下新键位…(Esc 取消)`:e.isUnassigned?`(未分配)`:a})]})},e.commandId)}),q(Y,{marginTop:F.section,children:J(D,{bold:!0,type:`secondary`,children:[`系统保留(`,Rf.length,`,不可修改)`]})}),Rf.map(e=>J(Y,{flexDirection:`row`,children:[J(D,{type:`secondary`,dim:!0,children:[` `,e.description]}),q(D,{type:`secondary`,children:` `}),q(D,{type:`secondary`,dim:!0,children:e.keyLabel})]},e.commandId))]})})}function Zf({onDismiss:e}){let{state:t}=ce(),n=t;return n?q(Jf,{overrides:n.overrides,onSave:n.onSave,onSaveReplace:n.onSaveReplace,onReset:n.onReset,onResetAll:n.onResetAll,onDismiss:e}):null}function Qf({onDismiss:e,rows:t,columns:n}){let{state:r}=ce(),i=r;return i?q(hl,{projectIndex:i.projectIndex,userIndex:i.userIndex,onViewEntry:i.onViewEntry,onForget:i.onForget,onDismiss:e,rows:t,columns:n}):null}const $f=new class{closeListeners=new Set;crashedListeners=new Set;hintListeners=new Set;requestClose(){for(let e of this.closeListeners)e()}onCloseRequest(e){return this.closeListeners.add(e),()=>{this.closeListeners.delete(e)}}reportCrashed(){for(let e of this.crashedListeners)e()}onCrashed(e){return this.crashedListeners.add(e),()=>{this.crashedListeners.delete(e)}}setHint(e){for(let t of this.hintListeners)t(e)}onHintChange(e){return this.hintListeners.add(e),()=>{this.hintListeners.delete(e)}}};function ep(){return!0}var tp=class extends V.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(){$f.reportCrashed()}render(){return this.state.error?J(X,{color:L.error,children:[`Panel crashed: `,this.state.error.message]}):this.props.children}};function np(){let[e,t]=V.useState(null),n=V.useRef(!0);return V.useEffect(()=>{n.current=!0;let e=e=>{n.current&&(t(e instanceof Error?e.message:String(e)),$f.reportCrashed())};return process.on(`unhandledRejection`,e),()=>{n.current=!1,process.removeListener(`unhandledRejection`,e)}},[]),{asyncError:e}}function rp({panelInfo:e}){let t=h(),[n,r]=V.useState(null),[i,a]=V.useState(null),{asyncError:o}=np();return V.useEffect(()=>(globalThis.__ottoCurrentPanelPluginId=e.pluginId,()=>{delete globalThis.__ottoCurrentPanelPluginId}),[e.pluginId]),V.useEffect(()=>{let t=!1;return import(e.modulePath).then(n=>{if(t)return;let i=e.exportName===`default`?n.default||n:n[e.exportName];if(!i||typeof i!=`function`){a(`Panel export "${e.exportName}" not found or not a component`),$f.reportCrashed();return}r(()=>i)}).catch(e=>{t||(a(e instanceof Error?e.message:String(e)),$f.reportCrashed())}),()=>{t=!0}},[e.modulePath,e.exportName]),i?J(X,{color:t.error,children:[`Panel error: `,i]}):o?J(X,{color:t.error,children:[`Panel crashed (possibly related async error): `,o]}):n?q(tp,{children:q(n,{})}):q(X,{dimColor:!0,children:`Loading…`})}function ip({req:e}){U(()=>$f.onCloseRequest(()=>e.onClose()),[]);let[t,n]=K(void 0);U(()=>(n(void 0),$f.onHintChange(e=>n(e))),[e.panelInfo.modulePath]);let[r,i]=K(!1);U(()=>(i(!1),$f.onCrashed(()=>i(!0))),[e.panelInfo.modulePath]),j(`plugin-panel-dialog`,(t,n)=>{n.escape&&e.onClose()},{isActive:r});let a=Array.isArray(t)?q(O,{items:t}):t??q(O,{items:[[`Esc`,B.t(`hint.close`)]]});return q(y,{header:q(p,{children:(()=>{let t=e.panelInfo.title;return t.includes(`.`)&&!t.includes(` `)?B.t(t):t})()}),footer:a,children:q(Y,{marginTop:F.tight,flexDirection:`column`,children:q(rp,{panelInfo:e.panelInfo})})})}function ap(){let{state:e}=ce(),t=e;return t?q(ip,{req:t}):null}const op=/^(bash|shell|run_command|execute|exec)/i;function sp(){let{state:e}=ce(),t=ql(),n=e;return n?op.test(n.tool)?q(Dl,{command:n.input,risk:n.risk??`medium`,description:n.description,alwaysAllowLabel:n.alwaysAllowLabel,onApprove:e=>t.onPermissionDecision?.(n.id,!0,e),onDeny:()=>t.onPermissionDecision?.(n.id,!1)}):q(Cl,{tool:n.tool,input:n.input,risk:n.risk??`medium`,onApprove:e=>t.onPermissionDecision?.(n.id,!0,e),onDeny:()=>t.onPermissionDecision?.(n.id,!1)}):null}function cp(){let{state:e}=ce(),{navigate:t}=g(),n=e;return n?q(rt,{title:n.title,phases:n.stages??n.phases,phaseIndex:n.phaseIndex??0,phaseStatuses:n.phaseStatuses??[],percent:n.percent??0,detail:n.detail??``,status:n.status??`running`,errorMessage:n.errorMessage,subProgress:n.subProgress,nextStep:n.nextStep,onDismiss:()=>{n.onDismiss?.(),t(`/`,{reset:!0})}}):null}function lp({onSubmit:e,onCancel:t}){let{state:n}=ce(),r=n;return r?q(kl,{title:r.title,message:r.message,placeholder:r.placeholder,initialValue:r.initialValue,submitLabel:r.submitLabel,cancelLabel:r.cancelLabel,onSubmit:e,onCancel:t}):null}function up({onSubmit:e,onCancel:t,columns:n}){let{state:r}=ce(),i=r,a=G(t);return a.current=t,U(()=>()=>{a.current()},[]),i?q(Ke,{title:i.title,questions:i.questions,columns:Math.min(60,n-fe.borderInset),onSubmit:e,onCancel:t}):null}function dp({title:t,subtitle:n,subtitleTone:r=`default`,options:i,maxVisible:a=10,searchable:o=!1,layout:s=`list`,onSelect:c,onCancel:l,subtitleActions:u,columns:d=60,rows:m=24,detailPlacement:g=`below`,initialFilter:_=``,onFilterChange:v,onHighlight:b,defaultSelectedValue:x}){let S=h(),C=s===`buttons`,w=s===`tabs`,E=!!u&&u.length>0&&!C&&!w,te=yt(),[k,re]=K(_),[A,ae]=K(_.length),oe=(e,t)=>{re(e),ae(t),v?.(e)},[se,M]=K(()=>E&&!i.some(e=>!e.disabled)?0:null),[N,ce]=K(o?`search`:`list`),P=W(()=>o?k===``?i:Yt(i,k):i,[o,k,i]),le=G(null);if(!le.current||le.current.options!==P){let e=Qe(P,{maxVisible:a});if(x){let t=P.findIndex(e=>e.value===x);t>=0&&e.selectByIndex(t)}le.current={options:P,state:e}}let ue=le.current.state,[,de]=K(0),fe=()=>{de(e=>e+1);let e=ue.getSelected();e&&b?.(e.value)};V.useEffect(()=>{let e=ue.getSelected();e&&b?.(e.value)},[]);let pe=()=>{ce(`list`),M(null),te?.focus(`select-list`)},me=()=>{ce(`search`),M(null),te?.focus(`select-search`)},he=e=>{ce(`list`),M(e)},{focused:_e}=Re({tabIndex:0,id:`select-search`,disabled:!o,onAction:()=>{if(k)pe();else{let e=ue.accept();e&&!e.disabled&&c(e.value)}return!0}}),{focused:ve}=Re({tabIndex:1,id:`select-list`,onAction:()=>{if(se!==null&&E)c(u[se].value);else{let e=ue.accept();e&&!e.disabled&&c(e.value)}return!0}}),ye=G(null),be=G(!0);V.useEffect(()=>{let e=_e?`search`:ve?`list`:null;e!==null&&e!==ye.current&&(be.current?be.current=!1:(ce(e),M(null))),ye.current=e},[_e,ve]);let Se=()=>{for(let e=P.length-1;e>=0;e--)if(!P[e]?.disabled){ue.selectByIndex(e);return}},Ce=()=>{for(let e=0;e<P.length;e++)if(!P[e]?.disabled){ue.selectByIndex(e);return}};j(`select-dialog`,(e,t)=>{if(o&&N===`search`&&e.length>1&&!t.ctrl&&!t.meta&&!t.return&&!t.escape&&!t.backspace&&!t.delete&&!t.tab&&!t.upArrow&&!t.downArrow&&!t.leftArrow&&!t.rightArrow){let t=Ze(e);t&&oe(k.slice(0,A)+t+k.slice(A),A+t.length);return}if(o&&se===null&&N===`search`){if(t.upArrow){E?he(u.length-1):(pe(),Se(),fe());return}if(t.downArrow){pe(),Ce(),fe();return}if(t.leftArrow){let e=Ue.fromText(k,d,A).left();oe(e.text,e.offset);return}if(t.rightArrow){let e=Ue.fromText(k,d,A).right();oe(e.text,e.offset);return}if(!t.return&&!t.tab){let n={name:t.return?`return`:t.escape?`escape`:t.backspace?`backspace`:t.delete?`delete`:t.tab?`tab`:e||`unknown`,ctrl:t.ctrl??!1,shift:!1,alt:t.meta??!1,meta:t.meta??!1},r=Ie(Ue.fromText(k,d,A),n);if(r){if(r.action===`clear_text`){oe(``,0);return}if(!(r.action===`submit`||r.action===`submit_force`)){oe(r.cursor.text,r.cursor.offset);return}}}}if((C||w)&&(t.leftArrow||t.rightArrow)){t.leftArrow?ue.moveUp():ue.moveDown(),fe();return}if(E&&se!==null&&(t.leftArrow||t.rightArrow)){let e=u.length-1;M(t.leftArrow?Math.max(0,se-1):Math.min(e,se+1));return}if(o&&se===null&&N===`search`&&(t.upArrow||t.downArrow))return;let n=Oe(e,t);if(n)switch(n.type){case`cancel`:l?.();return;case`up`:if(o&&N===`search`)return;if(se!==null){if(se>0){M(se-1);return}o&&me();return}{let e=ue.selectedIndex;if(ue.moveUp(),ue.selectedIndex===e){if(o){me();return}if(E){he(u.length-1);return}}}fe();return;case`down`:if(o&&N===`search`)return;if(se!==null){if(se<u.length-1){M(se+1);return}o?me():(pe(),Ce(),fe());return}{let e=ue.selectedIndex;if(ue.moveDown(),ue.selectedIndex===e&&o){me();return}}fe();return;case`index`:{se!==null&&M(null),ue.selectByIndex(n.index);let e=ue.getSelected();e&&!e.disabled&&c(e.value);return}case`accept`:{let e=ue.accept();e&&!e.disabled&&c(e.value);return}}});let we=G(0),L=W(()=>ge(P,g),[P,g]),Te=W(()=>g===`inline`?Math.max(0,...P.map(e=>it(e.label))):0,[g,P]),Ee=W(()=>g===`inline`?Math.max(0,...P.map(e=>it(e.trailingLabel??``))):0,[g,P]),De=C||w?1/0:o?ee(a+9,m)-9:ee(L.length+9,m)-9,ke=vt(L,ue.selectedIndex,De,we.current);we.current=ke.scrollTop;let Ae=P[ue.selectedIndex]??null;return J(y,{header:J(Mt,{children:[t&&q(p,{children:t}),t&&n&&q(Y,{marginTop:F.tight}),n&&E?J(Y,{flexDirection:`row`,alignSelf:`flex-start`,...ie,borderColor:S.accent,paddingX:F.tight,children:[J(X,{color:r===`warning`?S.warning:S.accent,children:[n,` `]}),u.map((e,t)=>J(V.Fragment,{children:[t>0&&J(D,{type:`secondary`,children:[` `,B.t(`common.wordOr`),` `]}),q(I,{variant:`ghost`,brackets:!0,color:r===`warning`?`amber`:`accent`,label:e.label,focused:se===t,tabIndex:-1})]},e.value))]}):n&&q(X,{color:r===`warning`?S.warning:S.inactive,children:n})]}),footer:q(O,{items:C||w?[[`${T.left}${T.right}`,B.t(`hint.select`)],[T.enter,B.t(`hint.confirm`)],[T.esc,B.t(`hint.cancel`)]]:[[`${T.up}${T.down}`,B.t(`hint.select`)],[T.enter,B.t(`hint.confirm`)],[T.esc,`${o?B.t(`select.clearHint`):``}${B.t(`hint.cancel`)}`],...o?[[`Tab`,B.t(`hint.switch`)]]:[]]}),children:[t&&!n&&q(Y,{marginTop:F.tight}),o&&J(Y,{flexDirection:`row`,marginBottom:F.tight,marginTop:n?F.tight:F.none,children:[q(D,{type:`secondary`,children:`/ `}),q(e,{value:k,offset:A,columns:d,mode:`dialog`,noPrefix:!0,placeholder:B.t(`select.filterPlaceholder`),focused:se===null&&N===`search`,tabIndex:-1})]}),o&&k!==``&&P.length===0&&q(Y,{marginBottom:F.tight,children:J(D,{type:`secondary`,dim:!0,children:[` `,B.t(`select.noMatches`)]})}),o&&k!==``&&P.length>0&&q(Y,{children:J(D,{type:`secondary`,dim:!0,children:[` `,B.t(`select.matchCount`,{count:P.length})]})}),C&&q(Y,{flexDirection:`row`,gap:F.section,marginTop:F.tight,children:P.map((e,t)=>q(I,{variant:`solid`,brackets:!0,color:e.color??(t===0?`accent`:`gray`),label:e.label,focused:e===Ae&&(o?N===`list`:!0),disabled:e.disabled},e.value))}),w&&J(Y,{flexDirection:`column`,marginTop:F.tight,children:[q(Dd,{items:P.map(e=>({key:e.value,label:e.label,disabled:e.disabled})),activeKey:Ae?.value??``,availableWidth:d-4}),Ae&&J(Y,{marginTop:F.tight,flexDirection:`column`,children:[q(X,{color:S.text,children:Ae.label}),Ae.detail&&q(Y,{marginTop:Math.floor(F.tight/2),children:q(D,{type:`secondary`,dim:!0,children:Ae.detail})})]})]}),!C&&!w&&q(Y,{height:1,children:q(ne,{hasMore:ke.hasMoreAbove})}),!C&&!w&&ke.rows.map((e,t)=>{if(e.kind===`spacer`)return q(X,{children:` `},`spacer-${t}`);if(e.kind===`divider`)return q(Y,{flexDirection:`column`,children:q(xe,{label:e.label,indent:` `})},`div-${t}`);let n=e.option;if(e.kind===`detail`)return J(Y,{flexDirection:`row`,children:[q(X,{children:` `}),J(D,{type:`secondary`,dim:!0,wrap:`truncate-end`,children:[` `,n.detail]})]},`detail-${e.optionIndex}`);let r=n===Ae,i=se===null&&(o?N===`list`:!0),a=r&&i,s=g===`inline`&&(n.detail||n.trailingLabel),c=s?`${gt(n.label,Te)} ${gt(n.trailingLabel??``,Ee)}${n.detail?` ${n.detail}`:``}`:n.label;return J(Y,{flexDirection:`row`,children:[q(X,{children:` `}),J(X,{color:n.disabled?S.inactive:a?S.selection:S.inactive,dimColor:n.disabled||r&&!i,bold:a&&!n.disabled,children:[r&&!n.disabled?`${R.pointer} `:` `,c,n.disabled?` (${B.t(`common.disabled`)})`:``]}),n.trailingLabel&&!s&&J(Mt,{children:[q(D,{type:`secondary`,children:` `}),q(X,{color:n.trailingColor??S.inactive,dimColor:!n.trailingColor,children:n.trailingLabel})]})]},`item-${e.optionIndex}`)}),!C&&!w&&Array.from({length:ke.fillerCount},(e,t)=>q(X,{children:` `},`filler-${t}`)),!C&&!w&&q(Y,{height:1,children:q(f,{hasMore:ke.hasMoreBelow})})]})}function fp({onSelect:e,onCancel:t,rows:n}){let{state:r}=ce(),i=r;return i?q(dp,{title:i.title,subtitle:i.subtitle,options:i.options??[],maxVisible:i.maxVisible,searchable:i.searchable,rows:n,layout:i.layout,subtitleActions:i.subtitleActions,detailPlacement:i.detailPlacement,initialFilter:i.initialFilter,onFilterChange:i.onFilterChange,onHighlight:i.onHighlight,defaultSelectedValue:i.defaultSelectedValue,onSelect:e,onCancel:t}):null}const pp=/^[A-Za-z0-9_-]+$/;function mp({shortcuts:e,onSave:t,onDelete:n,onDismiss:r}){let[i,a]=K(e),[o,s]=K({mode:`list`});return o.mode===`confirm-delete`?q(bp,{entry:o.entry,onConfirm:()=>{let e=o.entry.name;n(e),a(t=>t.filter(t=>t.name!==e)),s({mode:`list`})},onCancel:()=>s({mode:`list`})}):o.mode===`form`?q(yp,{editing:o.editing,existingNames:i.map(e=>e.name),onSave:(e,n)=>{let r=o.editing?.name;t(e,n,r),a(t=>[...(r?t.filter(e=>e.name!==r):t).filter(t=>t.name!==e),{name:e,text:n}]),s({mode:`list`})},onCancel:()=>s({mode:`list`})}):q(hp,{shortcuts:i,onNew:()=>s({mode:`form`}),onEdit:e=>s({mode:`form`,editing:e}),onDeleteRequest:e=>s({mode:`confirm-delete`,entry:e}),onDismiss:r})}function hp({shortcuts:e,onNew:t,onEdit:n,onDeleteRequest:r,onDismiss:i}){let a=new Map(e.map(e=>[e.name,e]));return e.length===0?J(y,{header:q(p,{children:B.t(`cmd.titleShortcuts`)}),footer:q(O,{items:[[`n`,B.t(`cmd.shortcutsPanelHintNew`)],[T.esc,B.t(`hint.close`)]]}),children:[q(Y,{marginTop:F.tight,children:q(X,{dimColor:!0,children:B.t(`cmd.shortcutsPanelEmptyHint`)})}),q(gp,{onNew:t,onDismiss:i})]}):q(z.Root,{title:`${B.t(`cmd.titleShortcuts`)} ${B.t(`cmd.shortcutsPanelListHint`)}(${e.length})`,onCancel:i,onKey:(e,n,i)=>{if(e===`n`)return t(),!0;if(e===`d`&&i){let e=a.get(i.value);return e&&r(e),!0}return!1},onValueChange:e=>{let t=a.get(e);t&&n(t)},footer:q(O,{items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[T.enter,B.t(`cmd.shortcutsPanelHintEdit`)],[`n`,B.t(`cmd.shortcutsPanelHintNew`)],[`d`,B.t(`cmd.shortcutsPanelHintDelete`)],[T.esc,B.t(`hint.close`)]]}),children:q(z.Content,{children:q(z.Group,{children:e.map(e=>q(z.Item,{value:e.name,detail:_p(e.text),marker:`number`,children:`@${e.name}`},e.name))})})})}function gp({onNew:e,onDismiss:t}){return j(`shortcuts-panel`,(n,r)=>{if(r.escape){t();return}n===`n`&&e()}),null}function _p(e,t=40){let n=e.trim().split(`
63
+ `)[0].replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const vp=[`name`,`text`,`save`,`cancel`];function yp({editing:t,existingNames:n,onSave:r,onCancel:i}){let a=h(),[o,s]=K(t?.name??``),[c,l]=K(o.length),[u,d]=K(t?.text??``),[f,m]=K(u.length),[g,_]=K(`name`),[v,b]=K(null),x=e=>{_(vp[(vp.indexOf(g)+e+vp.length)%vp.length])},S=()=>{let e=o.trim();return!e||!pp.test(e)?B.t(`cmd.shortcutsPanelNameInvalid`):n.some(n=>n===e&&n!==t?.name)?B.t(`cmd.shortcutsPanelNameDuplicate`):u.trim()?null:B.t(`cmd.shortcutsPanelTextEmpty`)},C=()=>{let e=S();if(e){b(e);return}r(o.trim(),u)};return j(`shortcuts-panel-2`,(e,t)=>{if(t.escape){i();return}if(t.tab){x(t.shift?-1:1);return}if(g===`save`||g===`cancel`){if(t.leftArrow||t.rightArrow){let e=E(t);e!==0&&x(e);return}if(t.return){g===`save`?C():i();return}return}let n=g===`name`,r=n?o:u,a=n?c:f,p=(e,t)=>{b(null),n?(s(e),l(t)):(d(e),m(t))};if(t.return&&n){_(`text`);return}if(t.leftArrow){let e=Ue.fromText(r,60,a).left();p(e.text,e.offset);return}if(t.rightArrow){let e=Ue.fromText(r,60,a).right();p(e.text,e.offset);return}if(e.length>1&&!t.ctrl&&!t.meta&&!t.return&&!t.escape&&!t.backspace&&!t.delete&&!t.tab&&!t.upArrow&&!t.downArrow&&!t.leftArrow&&!t.rightArrow){let t=Ze(e);t&&p(r.slice(0,a)+t+r.slice(a),a+t.length);return}let h={name:t.backspace?`backspace`:t.delete?`delete`:e||`unknown`,ctrl:t.ctrl??!1,shift:t.shift??!1,alt:t.meta??!1,meta:t.meta??!1},v=Ie(Ue.fromText(r,60,a),h);if(v){if(v.action===`clear_text`){p(``,0);return}if(v.action===`submit`||v.action===`submit_force`){n||C();return}p(v.cursor.text,v.cursor.offset)}}),J(y,{header:q(p,{children:t?B.t(`cmd.shortcutsPanelEditTitle`,{name:t.name}):B.t(`cmd.shortcutsPanelNewTitle`)}),footer:q(O,{items:[[T.tab,B.t(`hint.quick`)],[T.enter,B.t(`hint.confirm`)],[T.esc,B.t(`hint.cancel`)]]}),children:[J(Y,{marginTop:F.tight,flexDirection:`column`,children:[q(D,{type:`secondary`,children:B.t(`cmd.shortcutsPanelNameLabel`)}),J(Y,{flexDirection:`row`,children:[q(D,{type:`secondary`,children:`@`}),q(e,{value:o,offset:c,columns:60,mode:`dialog`,focused:g===`name`})]})]}),J(Y,{marginTop:F.tight,flexDirection:`column`,children:[q(D,{type:`secondary`,children:B.t(`cmd.shortcutsPanelTextLabel`)}),q(e,{value:u,offset:f,columns:60,mode:`dialog`,maxVisibleLines:6,focused:g===`text`})]}),v&&q(Y,{marginTop:F.tight,children:q(X,{color:a.error,children:v})}),J(Y,{marginTop:F.section,flexDirection:`row`,gap:F.section,children:[q(I,{variant:`solid`,brackets:!0,color:`accent`,label:B.t(`hint.confirm`),focused:g===`save`}),q(I,{variant:`solid`,brackets:!0,color:`gray`,label:B.t(`common.genericCancelButton`),focused:g===`cancel`})]})]})}function bp({entry:e,onConfirm:t,onCancel:n}){let r=h(),[i,a]=K(0);return j(`shortcuts-panel-3`,(e,r)=>{if(r.escape){n();return}if(r.leftArrow||r.rightArrow||r.tab){let e=E(r);e!==0&&a(t=>Le(t,e,2));return}r.return&&(i===1?t():n())}),q(y,{header:q(p,{children:B.t(`cmd.shortcutsPanelConfirmDeleteTitle`)}),children:J(Y,{marginTop:F.tight,flexDirection:`column`,children:[q(X,{color:r.warning,children:B.t(`cmd.shortcutsPanelConfirmDeleteMessage`,{name:e.name})}),J(Y,{marginTop:F.section,flexDirection:`row`,gap:F.section,children:[q(I,{variant:`solid`,brackets:!0,label:B.t(`common.genericCancelButton`),focused:i===0,color:`gray`}),q(I,{variant:`solid`,brackets:!0,label:B.t(`hint.delete`),focused:i===1,color:`red`})]})]})})}function xp({onDismiss:e}){let{state:t}=ce(),n=t;return n?q(mp,{shortcuts:n.bindings,onSave:n.onSave,onDelete:n.onDelete,onDismiss:e}):null}const Sp=[`en`,`zh`,`auto`];function Cp({step:e}){let t=[B.t(`onboarding.stepName`),B.t(`onboarding.stepLang`)];return J(Y,{flexDirection:`row`,marginBottom:F.tight,children:[t.map((t,n)=>J(V.Fragment,{children:[n>0&&q(D,{type:`secondary`,children:` · `}),n<e?q(D,{type:`success`,children:`${R.check} ${t}`}):n===e?q(D,{type:`accent`,bold:!0,children:`${R.statusDot} ${t}`}):q(D,{type:`secondary`,children:`${R.todoPending} ${t}`})]},n)),q(Y,{marginLeft:F.section,children:q(D,{type:`secondary`,children:B.t(`onboarding.stepCounter`,{current:e+1,total:2})})})]})}function wp({columns:t,onComplete:n,onLanguagePreview:r}){let[i,a]=K(0),[o,s]=K(``),[c,l]=K(0),[u,d]=K(2),[f,m]=K({}),h=At(e=>{let t={...f,...e};if(m(t),i>=1){n(t);return}a(i+1)},[i,f,n]),g=At(()=>{i>0&&a(i-1)},[i]);j(`onboarding-dialog`,(e,n)=>{if(n.escape)return h({}),!0;if(i>0&&n.leftArrow)return g(),!0;if(i!==0)return!1;if(n.return)return h(o.trim()?{nickname:o.trim()}:{}),!0;if(e.length>1&&!n.ctrl&&!n.meta&&!n.return&&!n.escape&&!n.backspace&&!n.delete&&!n.tab&&!n.upArrow&&!n.downArrow&&!n.leftArrow&&!n.rightArrow){let t=Ze(e);return t&&(s(o.slice(0,c)+t+o.slice(c)),l(c+t.length)),!0}let r={name:n.return?`return`:n.backspace?`backspace`:n.delete?`delete`:n.tab?`tab`:e||`unknown`,ctrl:n.ctrl??!1,shift:!1,alt:n.meta??!1,meta:n.meta??!1},a=Ie(Ue.fromText(o,t,c),r);return a?a.action===`submit`||a.action===`submit_force`?(h(o.trim()?{nickname:o.trim()}:{}),!0):(s(a.cursor.text),l(a.cursor.offset),!0):!1});let _=()=>i===0?J(Mt,{children:[q(p,{children:B.t(`onboarding.nameQuestion`)}),q(D,{type:`secondary`,children:B.t(`onboarding.nameDesc`)}),q(Y,{marginTop:F.tight,flexDirection:`row`,children:q(e,{value:o,offset:c,columns:t,mode:`dialog`,placeholder:B.t(`onboarding.namePlaceholder`),focused:!0,physicalCursor:!0})})]}):J(Mt,{children:[q(p,{children:B.t(`onboarding.langQuestion`)}),q(D,{type:`secondary`,children:B.t(`onboarding.langFootnote`)}),q(Y,{marginTop:F.tight,children:J(Ne.Root,{activeIndex:u,onActiveChange:d,onPick:e=>{let t=Sp[e];r?.(t),h({language:t})},children:[q(Ne.Item,{label:`English (en)`}),q(Ne.Item,{label:`中文 (zh)`}),q(Ne.Item,{label:B.t(`onboarding.langAuto`)})]})})]}),v=i===0?[[T.enter,B.t(`onboarding.hintNext`)],[T.esc,B.t(`onboarding.hintSkip`)]]:[[`${T.up}${T.down}`,B.t(`hint.select`)],[`1/2/3`,B.t(`onboarding.hintQuick`)],[T.enter,i>=1?B.t(`onboarding.hintDone`):B.t(`onboarding.hintNext`)],[T.left,B.t(`onboarding.hintBack`)],[T.esc,B.t(`onboarding.hintSkip`)]];return q(y,{header:q(Cp,{step:i}),footer:q(O,{items:v}),children:_()})}function Tp({onComplete:e,columns:t}){let{state:n}=ce(),r=n,i=G(e);return i.current=e,U(()=>()=>{i.current({})},[]),q(wp,{columns:Math.min(60,t-fe.borderInset),onComplete:e,onLanguagePreview:r?.onLanguagePreview})}function Ep(){let{state:e}=ce();return e?q(lt,{request:e}):null}function Dp(e){let{onAlertResolve:t,onConfirmResolve:n,onPromptResolve:r,onInputResolve:i,onInputAction:a,onQuestionsResolve:o,onOnboardingResolve:s,onSelectResolve:c,onInfoDismiss:l,onMemoryDismiss:u,onKeybindingPanelDismiss:d,onShortcutsDialogDismiss:f}=ql();return J(Mt,{children:[q(v,{path:`/dialog/alert`,element:q(Cf,{onOk:()=>t?.()})}),q(v,{path:`/dialog/confirm`,element:q(wf,{onConfirm:()=>n?.(!0),onCancel:()=>n?.(!1),onExtra:()=>n?.(!1,!0)})}),q(v,{path:`/dialog/prompt`,element:q(lp,{onSubmit:e=>r?.(e),onCancel:()=>r?.(null)})}),q(v,{path:`/dialog/input`,element:q(Lf,{onSubmit:e=>i?.(e),onCancel:()=>i?.(null),onAction:a,columns:e.columns})}),q(v,{path:`/dialog/questions`,element:q(up,{onSubmit:(e,t)=>o?.(e,t),onCancel:()=>o?.(null),columns:e.columns})}),q(v,{path:`/dialog/info`,element:q(Ff,{onDismiss:()=>l?.()})}),q(v,{path:`/dialog/memory`,element:q(Qf,{onDismiss:()=>u?.(),rows:e.rows,columns:e.columns})}),q(v,{path:`/dialog/select`,element:q(fp,{onSelect:e=>c?.(e),onCancel:()=>c?.(null),rows:e.rows})}),q(v,{path:`/dialog/wizard`,element:q(Ep,{})}),q(v,{path:`/dialog/onboarding`,element:q(Tp,{onComplete:e=>s?.(e),columns:e.columns})}),q(v,{path:`/dialog/a2ui-form`,element:q(Sf,{columns:e.columns})}),q(v,{path:`/dialog/progress`,element:q(cp,{})}),q(v,{path:`/dialog/keybindings`,element:q(Zf,{onDismiss:()=>d?.()})}),q(v,{path:`/dialog/shortcuts`,element:q(xp,{onDismiss:()=>f?.()})}),q(v,{path:`/viewer/file`,prefix:!0,element:q(jf,{rows:e.rows,columns:e.columns})}),q(v,{path:`/viewer/clipboard`,prefix:!0,element:q(Mf,{rows:e.rows,columns:e.columns})}),q(v,{path:`/viewer/help`,prefix:!0,element:q(Pf,{rows:e.rows,columns:e.columns})}),q(v,{path:`/dialog/extension`,prefix:!0,element:q(Of,{rows:e.rows,columns:e.columns})}),q(v,{path:`/dialog/extensions`,element:q(kf,{rows:e.rows})}),q(v,{path:`/dialog/plugin-panel`,element:q(ap,{})}),q(v,{path:`/dialog/permission`,element:q(sp,{})})]})}function Op({req:e,rows:t,columns:n,active:r=!0}){let i=h();return q(rc,{lines:W(()=>e.content.split(`
64
+ `),[e.content]),rows:t,columns:n,wrapMode:`pre-wrap`,header:q(Y,{children:q(X,{color:i.selection,children:e.label})}),onDismiss:e.onDismiss,initialScroll:`top`,active:r,contentKey:e.label})}function kp(e){let t=ql(),{stdout:n}=Bt(),{taskStore:r,notificationStore:i}=Vl(),a=Z(i.store,e=>e.notifications),o=Z(r.store,e=>e.queued),{stack:s}=g(),c=e=>s.some(t=>t.path===e);return J(Mt,{children:[q(bf,{focusOwner:e.routeDerivedOwner,pasteContent:c(`/overlay/paste-confirm`)?e.pasteContent:null,onPasteConfirm:e.handlePasteConfirm,onPasteCancel:e.handlePasteCancel,notifications:a,rows:e.rows,columns:e.columns}),q(Dp,{columns:e.columns,rows:e.rows}),e.chipContentViewerRequest&&c(`/overlay/chip-viewer`)&&q(v,{path:`/overlay/chip-viewer`,inStack:!0,element:q(Op,{req:e.chipContentViewerRequest,rows:n?.rows??e.rows,columns:e.columns,active:c(`/overlay/chip-viewer`)})}),e.queueCloseConfirm&&q(Ve,{title:B.t(`queue.exitTitle`),message:B.t(`queue.exitMessage`).replace(`%d`,String(o.length)),confirmLabel:B.t(`queue.exitConfirm`),checkLabel:B.t(`common.dontRemind`),checked:e.queueEscSuppress,onCheckChange:e.setQueueEscSuppress,onConfirm:()=>{e.setQueueCloseConfirm(!1),t.onToggleQueuePane?.()},onCancel:()=>e.setQueueCloseConfirm(!1)}),e.interruptConfirm&&q(Ve,{title:B.t(`agent.interruptTitle`),message:B.t(`agent.interruptMessage`),confirmLabel:B.t(`agent.interruptConfirm`),confirmColor:`red`,dangerous:!0,onConfirm:()=>{e.setInterruptConfirm(!1),t.onInterrupt?.()},onCancel:()=>e.setInterruptConfirm(!1)}),e.popQueuedConfirm&&q(Ve,{title:B.t(`queue.popTitle`),message:B.t(`queue.popMessage`),confirmLabel:B.t(`queue.popConfirm`),confirmColor:`red`,dangerous:!0,onConfirm:()=>{e.setPopQueuedConfirm(!1),t.onPopQueued?.()},onCancel:()=>e.setPopQueuedConfirm(!1)})]})}function Ap({exec:e,maxLines:t=8,totalLines:n,onCopyOutput:r,onAskAi:i,onAbort:a,onDismiss:o,onViewFullOutput:s,active:c=!0}){let l=h(),u=e.status===`running`,d=e.terminated||e.exitCode===null,f=!u&&(e.terminated===!0||e.exitCode!==0);j(`shell-pane`,(t,n)=>n.escape?(u&&a?.(),o?.(),!0):t===`v`&&!n.ctrl&&!n.meta&&!u?(s?.({command:e.command,output:e.output,isError:e.terminated===!0||e.exitCode!==0}),!0):t===`c`&&!n.ctrl&&!n.meta&&!u?(r?.(),!0):t===`a`&&!n.ctrl&&!n.meta&&f?(i?.(),o?.(),!0):!1,{isActive:c});let p=G(c);U(()=>{p.current&&!c&&(u&&a?.(),o?.()),p.current=c},[c,u,a,o]);let m=u?l.accent:d?l.error:e.exitCode===0?l.success:l.error,g=u?B.t(`shell.running`):e.terminated?B.t(`shell.terminated`):e.exitCode===null?B.t(`shell.errored`):B.t(`shell.exit`,{code:e.exitCode}),_=u?R.todoActive:d?R.cross:e.exitCode===0?R.check:R.cross,v=e.output.split(`
65
+ `),b=n??v.length,x=v.slice(-t),S=u&&x.length<t?[...x,...Array.from({length:t-x.length},()=>``)]:x,C=Math.max(0,v.length-t),w=u?B.t(`hint.toInterrupt`):B.t(`hint.close`),E=q(O,{items:[...!u&&b>t?[[`v`,B.t(`shell.viewAll`,{count:b})]]:[],...!u&&r?[[`c`,B.t(`shell.copyHint`)]]:[],...!u&&f&&i?[[`a`,B.t(`shell.hint`)]]:[],[T.esc,w]]});return J(y,{header:J(X,{children:[J(D,{type:`secondary`,children:[`>`,` `]}),q(X,{color:l.secondary,children:e.command}),q(X,{children:` `}),J(X,{color:m,children:[_,` `,g]})]}),footer:E,children:[(u||C>0)&&q(Y,{flexDirection:`row`,height:1,children:C>0?J(D,{type:`secondary`,dim:!0,children:[` `,B.t(`shell.moreLines`,{count:C})]}):q(X,{children:` `})}),S.map((e,t)=>q(Y,{flexDirection:`row`,children:q(X,{wrap:`truncate-end`,children:e===``?` `:e})},t))]})}function jp(e){if(e.operation===`edit`){if(e.oldContent!=null&&e.newContent!=null)return so(e.oldContent,e.newContent,2**53-1)}else if(e.operation===`delete`){if(e.oldContent!=null)return[{header:``,lines:e.oldContent.split(`
66
+ `).map((e,t)=>({type:`remove`,content:e,oldLine:t+1}))}]}else if(e.operation===`write`&&e.newContent!=null)return[{header:``,lines:e.newContent.split(`
67
+ `).map((e,t)=>({type:`add`,content:e,newLine:t+1}))}];return[]}function Mp({file:e,rows:t,columns:r=80,onDismiss:i,active:a=!0,resolveWholeFileDiff:o}){let s=h(),[c,l]=K(`diff`),[u,d]=K(0),[f,p]=K(Ca()),m=G(a);U(()=>{m.current&&!a&&i(),m.current=a},[a,i]);let[g,_]=K({status:`idle`});U(()=>{if(f)return;let e=!0;return Sa().then(()=>{e&&p(Ca())}),()=>{e=!1}},[f]),U(()=>{d(0)},[c,e.path]),U(()=>{_({status:`idle`})},[e.path]);let v=V.useRef(!1);U(()=>{v.current=!1},[e.path]),U(()=>{if(c!==`wholeFileDiff`||!o||v.current)return;v.current=!0;let t=!0;return _({status:`loading`}),o(e.path,e.operation).then(e=>{t&&_(e.error?{status:`error`,message:e.error}:{status:`ready`,oldContent:e.oldContent,newContent:e.newContent})}).catch(e=>{t&&_({status:`error`,message:e instanceof Error?e.message:String(e)})}),()=>{t=!1}},[c,e.path,e.operation,o]);let y=W(()=>{if(c!==`full`)return[];let t=e.operation===`delete`?e.oldContent:e.newContent;return t==null?[]:pc(e.path,t,r,f)},[e,f,c,r]),b=y[Math.min(u,Math.max(0,y.length-1))],x=W(()=>{if(c!==`wholeFileDiff`||g.status!==`ready`)return[];let{oldContent:e,newContent:t}=g;return e!=null&&t!=null?so(e,t,2**53-1,2**53-1):e==null&&t!=null?[{header:``,lines:t.split(`
68
+ `).map((e,t)=>({type:`add`,content:e,newLine:t+1}))}]:e!=null&&t==null?[{header:``,lines:e.split(`
69
+ `).map((e,t)=>({type:`remove`,content:e,oldLine:t+1}))}]:[]},[c,g]),S=W(()=>{if(c===`full`)return b?.lines??[];if(c===`wholeFileDiff`){let t=x.reduce((e,t)=>e+t.lines.length,0),n=qs(e.path);return Xs(x,f&&n!==``&&t<=2e3?{highlight:wa,lang:n}:{})}let t=jp(e),n=t.reduce((e,t)=>e+t.lines.length,0),r=qs(e.path);return Xs(t,f&&r!==``&&n<=2e3?{highlight:wa,lang:r}:{})},[e,f,c,b,x]),C=c===`full`?b?.wrapMode??`truncate`:`truncate`,w=(e.operation===`delete`?e.oldContent:e.newContent)!=null,E=o!=null,O=At(()=>{l(e=>e===`diff`?E?`wholeFileDiff`:w?`full`:`diff`:e===`wholeFileDiff`&&w?`full`:`diff`)},[E,w]),ee=E||w,te=B.t(`diff.fileOpLabel`,{context:e.operation}),ne=e.operation===`edit`?s.accent:e.operation===`write`?s.success:s.error,k=c===`wholeFileDiff`?g.status===`loading`?B.t(`diff.loading`):g.status===`error`?B.t(`diff.error`,{message:g.message}):void 0:e.oldContent==null&&e.newContent==null&&(e.addedLines>0||e.removedLines>0)?B.t(`common.contentUnavailable`):void 0,re=W(()=>c!==`wholeFileDiff`||g.status!==`ready`?null:co(x),[c,g.status,x]),ie=(yt()?.currentPath??`/`).endsWith(`/find`),A=e=>{let t=M();t&&(e&&!t.currentPath.endsWith(`/find`)?t.navigate(t.currentPath+`/find`):!e&&t.currentPath.endsWith(`/find`)&&t.goBack())};return q(rc,{lines:S,rows:t,header:J(Y,{children:[q(X,{color:ne,bold:!0,children:te}),J(X,{color:s.text,children:[` `,e.path]}),c===`wholeFileDiff`?q(n,{leadingSpace:!0,children:B.t(`diff.modeLabel`)}):c===`full`&&y.length>1&&b?q(n,{leadingSpace:!0,children:b.label}):null,J(D,{type:`secondary`,children:[` `,B.t(`diff.linesTotalLabel`,{count:S.length}),c===`wholeFileDiff`&&re?J(Mt,{children:[re.added>0&&` +${re.added}`,re.removed>0&&` -${re.removed}`,` `,`(`,B.t(`diff.modeLabel`),`)`]}):J(Mt,{children:[e.addedLines>0&&` +${e.addedLines}`,e.removedLines>0&&` -${e.removedLines}`]})]})]}),onDismiss:i,onKey:(e,t)=>e===`f`&&ee?(O(),!0):e===`]`&&c===`full`&&y.length>1?(d(e=>(e+1)%y.length),!0):!1,initialScroll:`bottom`,emptyMessage:k,active:a,contentKey:`${e.path}:${c}:${b?.id??``}:${g.status}`,columns:r,wrapMode:c===`full`?C:`truncate`,extraHints:[...ee?[[`f`,B.t(`hint.switch`)]]:[],...c===`full`&&y.length>1?[[`]`,B.t(`hint.tabSwitchOutput`)]]:[],[T.tab,B.t(`hint.tabFocus`)]],findActive:ie,onFindModeChange:A})}function Np({tasks:e,rows:t,onDismiss:n}){let r=h(),i=W(()=>e.filter(e=>(e.type??`process`)===`process`&&e.status===`running`&&e.detectedService),[e]),[a,o]=K(0),s=Math.max(3,t-6),c=Math.max(0,i.length-s),l=Math.min(a,c),u=i.slice(l,l+s),d=i.length===0;return Re({tabIndex:0,id:`services-dialog`,onEscape:()=>(n(),!0)}),ld(e=>o(t=>Math.min(c,Math.max(0,t-e))),[c]),j(`services-dialog`,(e,t)=>t.escape?(n(),!0):t.upArrow?(o(e=>Math.max(0,e-1)),!0):t.downArrow?(o(e=>Math.min(c,e+1)),!0):t.pageUp?(o(e=>Math.max(0,e-s)),!0):t.pageDown?(o(e=>Math.min(c,e+s)),!0):e===`g`&&!t.ctrl&&!t.meta?(o(0),!0):e===`G`&&!t.ctrl&&!t.meta?(o(c),!0):!1),q(y,{header:q(p,{children:B.t(`service.sTitle`)}),footer:q(O,{items:[[`${T.up}${T.down}/g/G`,B.t(`hint.scroll`)],[T.esc,B.t(`hint.close`)]]}),children:d?q(Y,{marginTop:F.tight,children:q(D,{type:`secondary`,dim:!0,children:B.t(`service.sEmpty`)})}):J(Y,{flexDirection:`column`,children:[q(Y,{height:1,children:l>0?q(ne,{hasMore:!0,count:l}):q(X,{children:` `})}),u.map((e,t)=>{let n=e.detectedService,i=n.url?n.url.replace(/^https?:\/\//,``).replace(/^wss?:\/\//,``).replace(/\/$/,``):`:${n.port}`,a=n.protocol===`ws`?`ws`:n.protocol===`tcp`?`tcp`:`http`;return J(Y,{flexDirection:`column`,children:[J(Y,{flexDirection:`row`,children:[q(X,{color:r.accent,children:`↕ `}),q(X,{color:r.selection,children:i})]}),q(Y,{marginLeft:F.section,children:J(D,{type:`secondary`,dim:!0,children:[e.command,` · `,a,n.port?` · :${n.port}`:``]})})]},l+t)}),q(Y,{height:1,children:l+s<i.length?q(f,{hasMore:!0,count:i.length-l-s}):q(X,{children:` `})})]})})}function Pp({command:e,output:t,rows:n,columns:r,onDismiss:i,active:a=!0,isError:o=!1,onCopyOutput:s,onAskAi:c,scrollStore:l}){let u=G(a);U(()=>{u.current&&!a&&i(),u.current=a},[a,i]);let d=W(()=>t.split(`
70
+ `),[t]),f=(e,t)=>e===`c`&&!t.ctrl&&!t.meta&&s?(s(),!0):e===`a`&&!t.ctrl&&!t.meta&&o&&c?(c(),!0):!1,m=[...s?[[`c`,B.t(`shell.copyHint`)]]:[],...o&&c?[[`a`,B.t(`shell.hint`)]]:[]],h=(yt()?.currentPath??`/`)===`/viewer/shell-output/find`;return q(rc,{lines:d,rows:n,columns:r,wrapMode:`truncate`,scrollStore:l,header:J(Y,{flexDirection:`row`,justifyContent:`space-between`,children:[J(p,{children:[`>`,` `,e]}),q(X,{dimColor:!0,children:B.t(`diff.linesTotalLabel`,{count:d.length})})]}),onDismiss:i,onKey:f,extraHints:m.length>0?m:void 0,initialScroll:`top`,active:a,contentKey:e,findActive:h,onFindModeChange:e=>{let t=M();t&&(e&&t.currentPath===`/viewer/shell-output`?t.navigate(`/viewer/shell-output/find`):!e&&t.currentPath===`/viewer/shell-output/find`&&t.goBack())}})}function Fp(e){let t=ql(),{stdout:n}=Bt(),{currentPath:r,stack:i,dismiss:a}=g(),o=e=>i.some(t=>t.path===e),{taskStore:s}=Vl(),c=Z(s.store,e=>e.backgroundOutput),l=Z(s.store,e=>e.editedFiles),u=Z(s.store,e=>e.backgroundTasks),{columns:d,rows:f,fullScreenPaneActive:p,shellFullOutput:m,shellExecution:h,setShellFullOutput:_,editedFileFullIndex:y,closeEditedFileFull:b,resolveWholeFileDiff:x}=e;return J(Mt,{children:[!p&&!m&&h&&q(Ap,{exec:h,totalLines:h.output.split(`
71
+ `).length,columns:d,onCopyOutput:t.onShellCopyOutput,onAskAi:t.onShellAskAi,onAbort:t.onShellAbort,onDismiss:t.onShellDismiss,onViewFullOutput:_,active:r===`/pane/shell`}),c&&q(Nd,{view:c,columns:d,rows:n?.rows,active:r===`/pane/delegates/output`,onDismiss:t.onBackgroundOutputClose}),y!==null&&y<l.length&&q(Mp,{file:l[y],rows:n?.rows??f,columns:d,onDismiss:b,active:r.startsWith(`/pane/edited-files/`),resolveWholeFileDiff:x}),o(`/overlay/services`)&&q(v,{path:`/overlay/services`,inStack:!0,element:q(Np,{tasks:u,columns:d,rows:n?.rows??f,onDismiss:()=>{a(`/overlay/services`)}})}),m&&q(Pp,{command:m.command,output:m.output,rows:n?.rows??f,columns:d,onDismiss:()=>_(null),active:r===`/viewer/shell-output`,scrollStore:e.scrollStore,isError:m.isError,onCopyOutput:t.onShellCopyOutput,onAskAi:t.onShellAskAi?()=>{t.onShellAskAi?.(),_(null),t.onShellDismiss?.()}:void 0})]})}function Ip(e,t){switch(e){case`healthy`:return t.accent;case`warning`:return t.warning;case`critical`:return t.error}}function Lp(e){return`${(e/1024/1024).toFixed(1)}MB`}function Rp({memory:e,history:t}){let n=h();return e?J(Y,{flexDirection:`column`,children:[J(Y,{children:[q(X,{color:Ip(e.level,n),bold:!0,children:e.level}),J(D,{type:`secondary`,children:[` `,e.usedPct.toFixed(1),`%`]}),t.length>=2&&J(D,{type:`secondary`,children:[` `,ca(t,20)]})]}),J(D,{type:`secondary`,children:[Lp(e.heapUsed),` / `,Lp(e.heapSizeLimit),` heap`]})]}):q(D,{type:`secondary`,children:`collecting…`})}function zp({notify:e}){let t=h();if(!e)return q(D,{type:`secondary`,dim:!0,children:`渲染数据将在 M2 接入`});let n=e.coalescedCalls===0,r=n?`idle`:e.alert;return J(Y,{flexDirection:`column`,children:[J(Y,{children:[q(X,{color:n?t.inactive:e.alert===`warning`?t.warning:t.accent,bold:!0,children:r}),J(D,{type:`secondary`,children:[` `,e.coalesceRatio.toFixed(1),`x merge`]})]}),J(D,{type:`secondary`,children:[`coalesced `,e.coalescedCalls,`→`,e.coalescedFires,` · direct `,e.immediateCalls,` · flush `,e.flushFires]})]})}function Bp(e){let t=typeof e==`string`?e:JSON.stringify(e);return t===void 0?`undefined`:ae(t,121)}function Vp({metrics:e,maxRows:t=1/0}){let n=h();if(e.length===0)return null;let r=e.slice(0,t),i=e.length-r.length;return J(Y,{flexDirection:`column`,children:[q(Y,{marginTop:F.loose,marginBottom:F.tight,children:q(D,{type:`secondary`,bold:!0,children:`Plugins`})}),r.map(e=>J(Y,{flexDirection:`row`,children:[q(X,{color:n.suggestion,children:e.label}),q(D,{type:`secondary`,children:` `}),e.error?J(X,{color:n.error,children:[`error: `,e.error]}):q(D,{type:`secondary`,children:Bp(e.value)})]},e.id)),i>0&&J(D,{type:`secondary`,dim:!0,children:[` `,i,` more`]})]})}function Hp({perfStore:e,onDismiss:t,onRefresh:n,rows:r=24}){let i=h(),a=Z(e.store,e=>e),o=yt();return j(`perf-panel`,(e,r)=>{if(r.escape){t();return}e===`r`&&n()},{isActive:o?o.currentPath===`/pane/perf`:!0}),q(y,{header:q(X,{color:i.secondary,bold:!0,children:`Performance`}),footer:q(O,{items:[[T.esc,B.t(`hint.close`)],[`r`,B.t(`hint.refresh`)],[T.tab,B.t(`hint.tabFocus`)]]}),children:J(Y,{marginTop:F.tight,flexDirection:`column`,children:[q(Y,{marginBottom:F.tight,children:q(D,{type:`secondary`,bold:!0,children:`Memory`})}),q(Rp,{memory:a.memory,history:a.memoryHistory}),q(Y,{marginTop:F.loose,marginBottom:F.tight,children:q(D,{type:`secondary`,bold:!0,children:`Rendering`})}),q(zp,{notify:a.notify}),q(Vp,{metrics:a.pluginMetrics,maxRows:ee(9+a.pluginMetrics.length+7,r)-9-7})]})})}function Up(e,t,n,r){let i=Math.max(0,n-r);return e.upArrow?Math.max(0,t-1):e.downArrow?Math.min(i,t+1):e.pageUp?Math.max(0,t-r):e.pageDown?Math.min(i,t+r):null}function Wp({children:e,visibleRows:t,offset:n,showHint:r=!0,onScroll:i}){let a=W(()=>V.Children.toArray(e),[e]),o=aa();U(()=>{if(!(!o||!i))return o.registerWheel(e=>{i(na(n,e,a.length,t))})},[o,i,a.length,t]);let s=a.length>t,c=s&&r?Math.max(1,t-1):t,l=ea(a.length,c,n);return J(Y,{flexDirection:`column`,children:[a.slice(l.start,l.end),s&&r&&q(D,{type:`secondary`,children:l.below>0?` ↓ ${l.below} more${l.above>0?` · ↑ ${l.above}`:``}`:` ↑ ${l.above} above`})]})}function Gp(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}m`}function Kp(e,t){return e>=80?t.accent:e>=40?t.warning:t.error}function qp({ratio:e,width:t}){let n=h(),r=Math.max(0,Math.min(100,Math.round(e*100))),i=Math.min(24,Math.max(8,t-20)),a=Kp(r,n);return J(Y,{children:[J(X,{color:a,bold:!0,children:[String(r).padStart(3),`%`,` `]}),q(Pe,{percent:r,width:i,chars:`block`,color:a,labelPosition:`none`})]})}function Jp({label:e}){return J(D,{type:`secondary`,dim:!0,children:[e,`: n/a(供应商未报告缓存数据)`]})}function Yp({row:e,width:t}){let n=h(),r=e.cacheReadTokens+e.cacheWriteTokens+e.inputTokens,i=e.hitRatio===null?`n/a`:`${Math.round(e.hitRatio*100)}%`,a=e.hitRatio===null?n.inactive:Kp(Math.round(e.hitRatio*100),n),o=`${e.modelName} read ${Gp(e.cacheReadTokens)} · write ${Gp(e.cacheWriteTokens)} · total ${Gp(r)}`;return J(Y,{justifyContent:`space-between`,children:[q(X,{color:n.suggestion,children:ae(o,t-8)}),q(X,{color:a,bold:e.hitRatio!==null,children:i})]})}function Xp({view:e,width:t,colors:n}){if(!e)return[q(D,{type:`secondary`,children:`collecting…`},`collecting`)];if(!(e.totalCacheReadTokens+e.totalCacheWriteTokens+e.totalInputTokens>0))return[q(D,{type:`secondary`,children:`本会话暂无缓存用量数据`},`nodata`)];let r=[];if(r.push(q(D,{type:`secondary`,bold:!0,children:`Session hit rate`},`h-session`)),r.push(e.sessionHitRatio===null?q(Jp,{label:B.t(`cache.sessionLabel`)},`v-session`):q(qp,{ratio:e.sessionHitRatio,width:t},`v-session`)),r.push(q(Y,{},`gap-1`)),r.push(q(D,{type:`secondary`,bold:!0,children:`Last turn`},`h-last`)),r.push(e.lastTurnHitRatio===null?q(Jp,{label:B.t(`cache.lastTurnLabel`)},`v-last`):q(qp,{ratio:e.lastTurnHitRatio,width:t},`v-last`)),r.push(q(Y,{},`gap-2`)),r.push(q(D,{type:`secondary`,children:`cache read ${Gp(e.totalCacheReadTokens)} · cache write ${Gp(e.totalCacheWriteTokens)} · input ${Gp(e.totalInputTokens)}`},`totals`)),e.totalCostUSD!==void 0&&e.totalCostUSD>0&&r.push(q(X,{color:n.suggestion,children:`~$${e.totalCostUSD.toFixed(4)}`},`cost`)),e.perModel.length>1){r.push(q(Y,{},`gap-3`)),r.push(q(D,{type:`secondary`,bold:!0,children:`By model`},`h-model`));for(let n of e.perModel)r.push(q(Yp,{row:n,width:t},n.modelId))}return r}function Zp({cacheStore:e,onDismiss:t,rows:n=24}){let r=h(),i=Z(e.store,e=>e),[a,o]=K(0),s=Xp({view:i.view,width:60,colors:r}),c=Math.max(1,u(n)-7),l=yt();return j(`cache-panel`,(e,n)=>{if(n.escape){t();return}let r=Up(n,a,s.length,c);r!==null&&o(r)},{isActive:l?l.currentPath===`/pane/cache`:!0}),q(y,{header:q(X,{color:r.secondary,bold:!0,children:`Cache`}),footer:q(O,{items:[[T.esc,B.t(`hint.close`)],[T.tab,B.t(`hint.tabFocus`)]]}),children:q(Y,{marginTop:F.tight,flexDirection:`column`,children:q(Wp,{visibleRows:c,offset:a,onScroll:o,children:s})})})}function Qp(e,t,n,r=[],i){let[a,o]=K(0),[s,c]=K(!1),l=e.length+r.length,u=l>0?Math.min(a,l-1):0,d=u>=e.length,f=e=>{if(e.kind===`input`){c(!0),t({kind:`input`,title:e.title??e.label,placeholder:e.placeholder,mask:e.mask}).then(t=>{t!=null&&t.trim()&&n(e.id,t.trim())}).finally(()=>c(!1));return}if(e.kind===`switch`){n(e.id,!e.value);return}if(e.kind===`select`){c(!0),t({kind:`select`,title:e.title??e.label,options:e.options,onSelect:t=>{c(!1),n(e.id,t)},onCancel:()=>c(!1)});return}};return{selectedIndex:u,editing:s,handleKey:(t,n)=>{if(s||l===0)return!1;if(b(`list-nav-up`,t,n))return o(e=>(e-1+l)%l),!0;if(b(`list-nav-down`,t,n))return o(e=>(e+1)%l),!0;if(n.return){if(d){let t=r[u-e.length];return t&&i?.(t.id),!0}let t=e[u];return t&&f(t),!0}return!1},isTrailingSelected:d}}function $p({field:e,selected:t,emptyLabel:n=`未设置`}){let r=h(),i=t?`${R.pointer} `:` `,a=t?r.selection:void 0;if(e.kind===`switch`){let n=e.value?R.statusDot:R.toggleOff,o=e.value?e.onLabel??`已启用`:e.offLabel??`已停用`,s=e.value?r.accent:r.inactive;return J(X,{children:[J(X,{color:a,bold:t,children:[i,e.label]}),q(X,{color:r.inactive,children:` `}),J(X,{color:s,children:[n,` `,o]})]})}let o=e.value?e.value:n;return J(X,{children:[J(X,{color:a,bold:t,children:[i,e.label]}),q(X,{color:r.inactive,children:` `}),q(X,{color:r.inactive,dimColor:!e.value,children:o})]})}function em(e){try{let t=new URL(e);return t.password?e.replace(`:${t.password}@`,`:••••@`):e}catch{return e}}function tm({view:e,onDismiss:t,onOpenModal:n,onSubmitUrl:r,onToggleEnabled:i,onClear:a,onTest:o,rows:s=24}){let c=h(),l=e.url?e.enabled===!1?`disabled`:`enabled`:`unconfigured`,d=e.url?[{kind:`input`,id:`url`,label:B.t(`proxy.fieldUrl`),value:em(e.url),title:B.t(`proxy.dialogEditUrl`),placeholder:B.t(`proxy.urlPlaceholder`)},{kind:`switch`,id:`enabled`,label:B.t(`proxy.fieldEnabled`),value:l===`enabled`,onLabel:B.t(`proxy.stateEnabled`),offLabel:B.t(`proxy.stateDisabled`)}]:[{kind:`input`,id:`url`,label:B.t(`proxy.fieldUrl`),value:``,title:B.t(`proxy.dialogSetUrl`),placeholder:B.t(`proxy.urlPlaceholder`)}],f=(e,t)=>{e===`url`&&typeof t==`string`&&r(t),e===`enabled`&&typeof t==`boolean`&&i()},p=l!==`unconfigured`,m=l===`unconfigured`?e.detectedEnvProxy:void 0,g=[...m?[{id:`adopt-env`,label:B.t(`proxy.actionAdoptEnv`,{value:em(m.value),source:m.source})}]:[],...p&&o?[{id:`test`,label:B.t(`proxy.actionTest`)}]:[],...p?[{id:`clear`,label:B.t(`proxy.actionClear`)}]:[]],[_,v]=K(!1),b=()=>{v(!0),n({kind:`confirm`,title:B.t(`proxy.clearTitle`),message:B.t(`proxy.clearMessage`,{url:e.url??``}),confirmLabel:B.t(`proxy.clearConfirm`),confirmColor:`red`,dangerous:!0,onConfirm:()=>{v(!1),a()},onCancel:()=>v(!1)})},{selectedIndex:x,editing:S,handleKey:C,isTrailingSelected:w}=Qp(d,n,f,g,e=>{e===`clear`&&b(),e===`test`&&o?.(),e===`adopt-env`&&m&&r(m.value)}),E=S||_,ee=Math.max(1,u(s)-7),te=1+(w?d.length:x),ne=Math.max(0,te-ee+2),k=e.url&&e.enabled!==!1?e.url:void 0,re=e.effectiveUrl!==k,ie=e.probe,A=null;ie&&ie.status!==`idle`?A=ie.status===`probing`?q(D,{type:`secondary`,children:B.t(`proxy.probeProbing`)},`note`):ie.status===`ok`?J(X,{color:c.success,children:[R.check,` `,B.t(`proxy.probeOk`,{latency:ie.latencyMs,target:ie.target})]},`note`):J(X,{color:ie.blamesProxy?c.error:c.warning,children:[R.cross,` `,B.t(ie.blamesProxy?`proxy.probeFailedProxy`:`proxy.probeFailedTarget`,{reason:ie.reason})]},`note`):l!==`unconfigured`&&re&&(A=J(X,{color:c.warning,children:[R.warn,` `,e.effectiveUrl?B.t(`proxy.effectiveMismatch`,{effective:em(e.effectiveUrl)}):B.t(`proxy.effectiveNotApplied`)]},`note`));let ae=aa();return U(()=>{if(ae)return ae.registerWheel(e=>{if(E)return;let t=Math.abs(e)*3,n={upArrow:e>0,downArrow:e<0};for(let e=0;e<t;e++)C(``,n)})},[ae,E,C]),j(`proxy-pane`,(e,n)=>{if(n.escape){t();return}C(e,n)},{isActive:!E}),q(y,{header:q(X,{color:c.secondary,bold:!0,children:B.t(`proxy.title`)}),footer:E?void 0:q(O,{items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[T.enter,B.t(`hint.execute`)],[T.esc,B.t(`hint.close`)]]}),children:q(Y,{marginTop:F.tight,flexDirection:`column`,children:J(Wp,{visibleRows:ee,offset:ne,children:[q(xe,{label:B.t(`proxy.groupConfig`),indent:``},`h-config`),d.map((e,t)=>q($p,{field:e,selected:!E&&t===x,emptyLabel:B.t(`proxy.urlEmpty`)},e.id)),g.map((e,t)=>{let n=w&&!E&&x-d.length===t,r=e.id===`clear`?c.error:void 0;return J(X,{color:n?c.selection:r,bold:n,children:[n?`${R.pointer} `:` `,e.label]},e.id)}),A,q(X,{children:` `},`gap`),q(xe,{label:B.t(`proxy.groupAbout`),indent:``},`h-about`),q(D,{type:`secondary`,children:B.t(`proxy.aboutScope`)},`d1`),q(D,{type:`secondary`,children:B.t(`proxy.aboutLoopback`)},`d2`),q(D,{type:`secondary`,children:B.t(`proxy.aboutStorage`,{path:e.configPath})},`d3`),q(D,{type:`secondary`,dim:!0,children:B.t(`proxy.aboutCommand`)},`d4`)]})})})}function nm(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}:${String(t.getSeconds()).padStart(2,`0`)}`}function rm(e){switch(e.kind){case`compact`:{let t=e.before&&e.before>0?Math.round((e.after??0)/e.before*100):0;return B.t(`compact.logCompactRow`,{before:e.before??0,after:e.after??0,pct:t})}case`prune`:return e.prunedCount===void 0?B.t(`compact.logPruneRow`,{tokensSaved:e.tokensSaved??0}):B.t(`compact.logPruneRow`,{context:`pruned`,count:e.prunedCount,tokensSaved:e.tokensSaved??0});case`history_capped`:return B.t(`compact.logHistoryCappedRow`,{count:e.removedCount??0})}}const im={compact:`compact`,prune:`prune`,history_capped:`history`};function am({entry:e}){return e.kind===`compact`?J(Y,{flexDirection:`column`,children:[q(D,{type:`secondary`,children:rm(e)}),q(Y,{marginTop:F.tight,children:e.summary?q(X,{children:e.summary}):q(D,{type:`secondary`,dim:!0,children:B.t(`compact.logNoSummary`)})})]}):q(D,{type:`secondary`,children:rm(e)})}function om({entries:e,onClose:t,rows:n=24}){let r=h(),[i,a]=$i(`compactionLog`,e.length),o=yt(),s=o?.currentPath??`/`,c=o?s.startsWith(`/pane/compaction-log`):!0,l=s.match(/^\/pane\/compaction-log\/(\d+)$/),u=l?Number(l[1]):null,d=e=>{let t=M();t&&(e==null?t.currentPath.startsWith(`/pane/compaction-log/`)&&t.goBack():t.navigate(`/pane/compaction-log/${e}`))},f=e.length===0?0:Math.min(i,e.length-1),p=u==null?void 0:e.find(e=>e.id===u),m=G(0),g=pt(e,f,ee(e.length+7,n)-7,m.current);return m.current=g.scrollTop,j(`compaction-log-dialog`,At((n,r)=>{if(r.escape){p?d(null):t();return}if(!p){if(b(`list-nav-up`,n,r)){a(t=>e.length===0?0:(t-1+e.length)%e.length);return}if(b(`list-nav-down`,n,r)){a(t=>e.length===0?0:(t+1)%e.length);return}if(r.return){let t=e[f];t&&d(t.id)}}},[p,e,f,t]),{isActive:c}),p?q(y,{header:q(X,{color:r.secondary,bold:!0,children:B.t(`compact.logDetailTitle`,{kind:im[p.kind],time:nm(p.timestamp)})}),footer:q(O,{items:[[T.esc,B.t(`hint.cancel`)]]}),children:q(Y,{marginTop:F.tight,flexDirection:`column`,children:q(am,{entry:p})})}):q(y,{header:q(X,{color:r.secondary,bold:!0,children:B.t(`compact.logTitle`)}),footer:q(O,{items:[[`${T.up}${T.down}`,B.t(`hint.select`)],[T.enter,B.t(`compact.logViewSummary`)],[T.esc,B.t(`hint.cancel`)],[T.tab,B.t(`hint.tabFocus`)]]}),children:J(Y,{marginTop:F.tight,flexDirection:`column`,children:[e.length===0?q(D,{type:`secondary`,dim:!0,children:B.t(`compact.logEmpty`)}):g.rows.map((e,t)=>{let n=g.scrollTop+t===f;return q(Y,{flexDirection:`row`,children:J(X,{color:n?r.selection:r.inactive,bold:n,children:[n?`${R.pointer} `:` `,nm(e.timestamp),` `,im[e.kind].padEnd(8),` `,rm(e)]})},e.id)}),g.fillerCount>0&&Array.from({length:g.fillerCount},(e,t)=>q(X,{children:` `},`filler-${t}`))]})})}function sm({checked:e,onChange:t,label:n,tabIndex:r=0,disabled:i=!1}){let a=h(),{focused:o}=Re({tabIndex:r,disabled:i});l(o,(n,r)=>n===` `?(t(!e),!0):!1);let s=e?R.check:R.todoPending;return J(X,{color:o?a.selection:e?a.success:a.inactive,children:[o?`${R.pointer} `:` `,s,` `,n]})}function cm({options:e,selected:t,onSelect:n,onPick:r,escapeIndex:i,tabIndex:a=0}){return H(Ne.Root,{onPick:r,activeIndex:t,onActiveChange:n,escapeIndex:i,tabIndex:a,id:`choices-${e.map(e=>e.key).join(`-`)}`},...e.map(e=>H(Ne.Item,{key:e.key,label:e.label,color:e.color,shortcut:e.shortcut})))}const lm=[`good`,`neutral`,`bad`];function um(e){switch(e){case`good`:return B.t(`pulse.ratingGood`);case`neutral`:return B.t(`pulse.ratingNeutral`);case`bad`:return B.t(`pulse.ratingBad`)}}function dm({item:t,columns:n=60,onChange:r}){if(Re({tabIndex:0,id:`pulse-survey-overlay`,onEscape:()=>{if(t.phase===`rating`)return!1;let e=t.rating??`good`,n=t.commentText.length>0?t.commentText:void 0;return t.onSubmit(e,n),t.onClose(),!0}}),j(`pulse-survey-overlay`,(e,i)=>{if(t.phase===`rating`)return i.escape?(t.onClose(),!0):!1;let a=t.rating??`good`,o=()=>{let e=t.commentText.length>0?t.commentText:void 0;t.onSubmit(a,e),t.onClose()};if(i.return||i.escape)return o(),!0;if(i.leftArrow){let e=Ue.fromText(t.commentText,n,t.commentOffset).left();return r?.({commentText:e.text,commentOffset:e.offset}),!0}if(i.rightArrow){let e=Ue.fromText(t.commentText,n,t.commentOffset).right();return r?.({commentText:e.text,commentOffset:e.offset}),!0}if(e.length>1&&!i.ctrl&&!i.meta&&!i.backspace&&!i.delete&&!i.tab&&!i.upArrow&&!i.downArrow){let n=Ze(e);return n&&r?.({commentText:t.commentText.slice(0,t.commentOffset)+n+t.commentText.slice(t.commentOffset),commentOffset:t.commentOffset+n.length}),!0}let s={name:i.backspace?`backspace`:i.delete?`delete`:i.tab?`tab`:e||`unknown`,ctrl:i.ctrl??!1,shift:!1,alt:i.meta??!1,meta:i.meta??!1},c=Ie(Ue.fromText(t.commentText,n,t.commentOffset),s);return c?c.action===`submit`||c.action===`submit_force`?(o(),!0):(r?.({commentText:c.cursor.text,commentOffset:c.cursor.offset}),!0):!1}),t.phase===`rating`){let e=lm.map(e=>({key:e,label:um(e)}));return q(y,{header:q(p,{children:B.t(`pulse.title`)}),footer:q(X,{children:B.t(`pulse.hintRating`)}),children:q(Y,{marginTop:F.tight,children:q(cm,{options:e,selected:t.selectedIndex,onSelect:e=>r?.({selectedIndex:e}),onPick:n=>{if(n>=e.length){t.onClose();return}r?.({phase:`comment`,rating:lm[n]??`good`})},escapeIndex:e.length})})})}return q(y,{header:q(p,{children:t.rating?B.t(`pulse.commentTitle`,{ratingLabel:um(t.rating)}):B.t(`pulse.title`)}),footer:q(X,{children:B.t(`pulse.hintComment`)}),children:q(Y,{marginTop:F.tight,flexDirection:`row`,children:q(e,{value:t.commentText,offset:t.commentOffset,columns:n,mode:`dialog`,placeholder:B.t(`pulse.commentPlaceholder`),focused:!0,physicalCursor:!0})})})}function fm({enabledCount:e}){let t=h();return e===0?null:q(X,{color:t.accent,children:` * ${e} scheduled`})}function pm({title:e,indent:t=F.section,titleIndent:n,children:r}){return J(Y,{flexDirection:`column`,children:[e!=null&&q(xe,{label:e,indent:n}),q(Y,{marginLeft:t,flexDirection:`column`,children:r})]})}const mm=Math.max(...Mu.map(e=>Math.max(it(e.en),it(e.zh))));function hm({tip:e}){let{resolvedTheme:t}=C();if(!e)return null;let n=B.t(`welcome.tipLabel`),r=it(n)+1+mm+F.tight*2,i=it(e),a=i<mm?e+` `.repeat(mm-i):e,o=(t===`light`?Ru:Lu)[Wu(0)],s=Gu(r,0,t);return J(Y,{flexDirection:`column`,alignSelf:`flex-start`,children:[J(Y,{flexDirection:`row`,children:[q(X,{color:o,children:`╭`}),s.map((e,t)=>q(X,{color:e,children:`─`},t)),q(X,{color:o,children:`╮`})]}),J(Y,{flexDirection:`row`,children:[q(X,{color:o,children:`│`}),J(Y,{flexDirection:`row`,paddingX:F.tight,children:[J(D,{type:`accent`,children:[n,` `]}),q(D,{type:`secondary`,children:a})]}),q(X,{color:o,children:`│`})]}),J(Y,{flexDirection:`row`,children:[q(X,{color:o,children:`╰`}),s.map((e,t)=>q(X,{color:e,children:`─`},t)),q(X,{color:o,children:`╯`})]})]})}const gm={pointer:R.pointer,check:R.check,cross:R.cross,bullet:R.bullet,todoPending:R.todoPending,todoActive:R.todoActive,todoDone:R.todoDone,toggleOn:R.toggleOn,toggleOff:R.toggleOff,statusDot:R.statusDot,warn:R.warn,ellipsis:R.ellipsis};function _m(e,t){if(e)return t[e]}function vm({name:e,color:t,bold:n,dim:r,trailingSpace:i}){return J(X,{color:_m(t,h()),bold:n,dimColor:r,children:[gm[e],i?` `:``]})}function ym(e){let t=new Date,n=e=>String(e).padStart(2,`0`),r=`${n(t.getHours())}:${n(t.getMinutes())}`;return e?`${r}:${n(t.getSeconds())}`:r}function bm({color:e,dimColor:t=!0,showSeconds:n=!1}){let r=h(),[i,a]=K(()=>ym(n));return U(()=>{let e=setInterval(()=>{a(ym(n))},n?1e3:3e4);return()=>clearInterval(e)},[n]),q(X,{color:e??r.inactive,dimColor:t,children:i})}function xm({level:e,usedPct:t}){let n=h();return e===`healthy`?q(Y,{}):q(Y,{flexDirection:`row`,children:J(X,{color:e===`critical`?n.error:n.warning,children:[` `,`<mem`,e===`critical`?`!!`:`!`,t===void 0?``:` ${Math.round(t)}%`,`> `]})})}function Sm({count:e,hasUrgent:t}){let n=h();return e===0?q(Y,{}):q(Y,{flexDirection:`row`,children:J(X,{color:t?n.warning:n.accent,children:[` [`,e,`!]`]})})}const Cm=3500;function wm({toast:e,onDismiss:t}){return Re({tabIndex:0,id:`toast`,onEscape:()=>(t?.(),!0),onAction:()=>(t?.(),!0)}),j(`toast`,(e,n)=>n.ctrl?!1:(t?.(),!0)),q(y,{header:q(p,{children:e.title}),footer:q(O,{items:[[T.esc,B.t(`hint.close`)]]}),children:q(Y,{marginTop:F.tight,children:q(X,{children:e.content})})})}function Tm(e,t=10,n){let r=Math.max(1,Math.floor(t)),i=mt({percent:e,width:r}),a=i.pct,o=i.filledCount,s=a>=90?L.error:a>=80?L.warning:L.suggestion,c=n?.prune!==void 0&&Number.isFinite(n.prune)?Math.max(0,Math.min(r-1,Math.round(n.prune/100*r))):null,l=n?.compact!==void 0&&Number.isFinite(n.compact)?Math.max(0,Math.min(r-1,Math.round(n.compact/100*r))):null,u=i.cells.map(e=>e.filled?`▰`:`▱`),d=u.join(``),f=u.map((e,t)=>({char:e,isPrune:c===t,isCompact:l===t}));return{pct:a,filled:o,total:r,color:s,bar:d,label:`${d} ${a}%`,segments:f}}function Em({tasks:e=[]}){let t=h(),n=e.filter(e=>e.status===`running`).length,[r,i]=K(()=>Date.now());U(()=>{if(n===0)return;i(Date.now());let e=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(e)},[n]);let a=_o(e,r);return a?q(X,{color:t.accent,children:` · ${a}`}):null}function Dm({tasks:e=[]}){let t=h(),n=vo(e);return n?q(X,{color:t.accent,children:` · ${n}`}):null}function Om({columns:e,footerVisible:t,perfIndicatorLevel:n,perfIndicatorUsedPct:r,modelName:i,budget:a,badgeEntries:o,fullScreenPaneActive:s,backgroundTasks:c,scheduleEnabledCount:l,agentProcessing:u,queuedItems:d,notifications:f,language:p,welcome:m,messages:g,hasHistory:_,paused:v=!1,pausePending:y=null,shadow:b=!1}){let x=h();return J(Y,{flexDirection:`row`,justifyContent:`space-between`,width:e,children:[J(Y,{flexDirection:`row`,children:[b&&q(X,{bold:!0,color:x.warning,children:`🕶 ${B.t(`welcome.shadowBadge`)} `}),t.perfIndicator&&q(xm,{level:n,usedPct:r}),t.modelName&&i&&q(X,{color:x.suggestion,children:i}),t.occupancyBar&&a&&a.contextWindow>0&&(()=>{let e={prune:a.pruneLine>0?a.pruneLine/a.contextWindow*100:void 0,compact:a.compactLine>0?a.compactLine/a.contextWindow*100:void 0},t=Tm(a.contextPercent,10,e),n={},r=t.segments.findIndex(e=>e.isPrune),i=t.segments.findIndex(e=>e.isCompact);return r>=0&&(n.prune={pos:r,color:x.warning}),i>=0&&(n.compact={pos:i,color:x.error}),J(X,{children:[` `,q(Pe,{percent:t.pct,width:t.total,chars:`dot`,color:t.color,markers:n,labelPosition:`suffix`,labelPrefix:a.live?`~`:``})]})})(),o.map(e=>J(X,{color:e.color===`warning`?x.warning:x.inactive,children:[e.separator===`dot`?` · `:` `,e.text]},e.id)),t.backgroundTaskIndicator&&!s&&q(Em,{tasks:c}),t.scheduleIndicator&&!s&&q(fm,{enabledCount:l}),t.serviceIndicator&&q(Dm,{tasks:c})]}),J(Y,{flexDirection:`row`,children:[t.hintText&&q(X,{color:v||y?x.warning:x.inactive,children:y?`${B.t(`pause.toolCount`,{n:y.toolCount,s:y.elapsedSec})} /continue ${B.t(`pause.btnCancel`)}`:v?`${B.t(`cmd.titlePaused`)} · ${B.t(`hint.pausedContinue`)}`:u?e>=76?`${T.enter} ${B.t(`hint.steer`)} · ${bt()} ${B.t(`hint.queue`)} · ${T.esc} ${d.length>0?B.t(`hint.delOne`):B.t(`hint.toInterrupt`)}`:`${T.esc}${d.length>0?` ${B.t(`hint.delOne`)}`:`/${A(`c`)} ${B.t(`hint.toInterrupt`)}`}`:e>=76?`${T.right} ${B.t(`hint.autosuggestAccept`)} · Tab ${B.t(`hint.autosuggestMenu`)} · ${A(`r`)} ${B.t(`hint.history`)} · /help`:`/help`}),t.notificationBell&&f.some(e=>!e.read)&&q(D,{type:`secondary`,children:` · `}),t.notificationBell&&q(Sm,{count:f.filter(e=>!e.read).length,hasUrgent:f.some(e=>e.level===`error`&&!e.read)}),(()=>{let e=t.language&&!!p,n=t.liveClock&&!s&&(!m||g.length>0||_);return!e&&!n?null:J(D,{type:`secondary`,children:[` `,e&&(p===`zh`?`中`:`EN`),e&&n&&` `,n&&q(bm,{color:x.inactive,dimColor:!1})]})})()]})]})}const km=()=>{},Am=[{id:`Button`,category:`components`,title:`Button`,variants:[{name:`solid/accent`,render:()=>H(I,{variant:`solid`,color:`accent`,label:`Approve`,focused:!0})},{name:`solid/amber`,render:()=>H(I,{variant:`solid`,color:`amber`,label:`Upgrade`,focused:!0})},{name:`solid/red`,render:()=>H(I,{variant:`solid`,color:`red`,label:`Delete`,focused:!0})},{name:`solid/green`,render:()=>H(I,{variant:`solid`,color:`green`,label:`Confirm`,focused:!0})},{name:`outline/accent`,render:()=>H(I,{variant:`outline`,color:`accent`,label:`Select`,focused:!0})},{name:`outline/gray`,render:()=>H(I,{variant:`outline`,color:`gray`,label:`Cancel`,focused:!1})},{name:`ghost/accent`,render:()=>H(I,{variant:`ghost`,color:`accent`,label:`Escape`,focused:!0})},{name:`ghost/gray`,render:()=>H(I,{variant:`ghost`,color:`gray`,label:`Dismiss`,focused:!1})},{name:`disabled`,render:()=>H(I,{variant:`solid`,color:`accent`,label:`Unavailable`,disabled:!0})}]},{id:`Segmented`,category:`components`,title:`Segmented`,variants:[{name:`three-tabs`,render:()=>H(Dd,{items:[{key:`events`,label:`Events`},{key:`tools`,label:`Tools`},{key:`budget`,label:`Budget`}],activeKey:`tools`})},{name:`with-disabled`,render:()=>H(Dd,{items:[{key:`events`,label:`Events`},{key:`stats`,label:`Stats`,disabled:!0}],activeKey:`events`,color:`amber`})}]},{id:`SegmentItem`,category:`components`,title:`SegmentItem`,variants:[{name:`active`,render:()=>H(Ed,{label:`Events`,active:!0})},{name:`inactive`,render:()=>H(Ed,{label:`Tools`,active:!1})}]},{id:`GroupDivider`,category:`components`,title:`GroupDivider`,variants:[{name:`default`,render:()=>H(xe,{label:`File`})}]},{id:`ScrollIndicatorAbove`,category:`components`,title:`ScrollIndicatorAbove`,variants:[{name:`with-count`,render:()=>H(ne,{hasMore:!0,count:12})},{name:`no-count`,render:()=>H(ne,{hasMore:!0})}]},{id:`ScrollIndicatorBelow`,category:`components`,title:`ScrollIndicatorBelow`,variants:[{name:`with-count`,render:()=>H(f,{hasMore:!0,count:7})},{name:`no-count`,render:()=>H(f,{hasMore:!0})}]},{id:`Group`,category:`components`,title:`Group`,variants:[{name:`with-title`,render:()=>H(pm,{title:`Settings`,children:H(X,{},`Auto-indented content`)})},{name:`no-title`,render:()=>H(pm,{children:H(X,{},`Indent only, no title divider`)})},{name:`custom-indent=4`,render:()=>H(pm,{title:`Wide indent`,indent:4,children:H(X,{},`Indented by 4 columns`)})}]},{id:`Choices`,category:`components`,title:`Choices`,variants:[{name:`vertical-numbered`,render:()=>H(cm,{options:[{key:`approve`,label:`Approve`,color:`green`,shortcut:`y`},{key:`deny`,label:`Deny`,color:`red`,shortcut:`n`},{key:`always`,label:`Always`,color:`accent`,shortcut:`a`}],selected:0,onSelect:km,onPick:km,escapeIndex:1})}]},{id:`Menu`,category:`components`,title:`Menu (RFC-268 竖排编号原语)`,variants:[{name:`composite-api`,render:()=>H(Ne.Root,{onPick:km},H(Ne.Item,{label:`Trust — full access`,color:`green`}),H(Ne.Item,{label:`Read-only this session`,color:`accent`}),H(Ne.Item,{label:`No, exit`,color:`gray`}))}]},{id:`Typography`,category:`components`,title:`Typography (RFC-269 文字层级)`,variants:[{name:`type-scale`,render:()=>H(Y,{flexDirection:`column`},H(D,{type:`primary`},`primary — 正文(终端默认前景)`),H(D,{type:`secondary`},`secondary — 次级/说明文字`),H(D,{type:`danger`},`danger — 错误态`),H(D,{type:`success`},`success — 成功态`),H(D,{type:`warning`},`warning — 警示态`),H(D,{type:`accent`},`accent — 品牌强调(守恒 ≤5%)`))}]},{id:`Tag`,category:`components`,title:`Tag (RFC-269 内联标签)`,variants:[{name:`view-label`,render:()=>H(n,{leadingSpace:!0},`Rendered`)},{name:`counter`,render:()=>H(n,null,`2/5`)}]},{id:`Kbd`,category:`components`,title:`Kbd (RFC-269 键位标签)`,variants:[{name:`single-key`,render:()=>H(k,null,`↵`)},{name:`chord`,render:()=>H(k,null,`⇧+↵`)}]},{id:`ProgressBar`,category:`components`,title:`ProgressBar (RFC-279)`,variants:[{name:`simple/ascii`,render:()=>H(Pe,{percent:45,width:30,chars:`ascii`,color:L.accent})},{name:`simple/block`,render:()=>H(Pe,{percent:68,width:24,chars:`block`,color:L.warning})},{name:`simple/dot`,render:()=>H(Pe,{percent:30,width:10,chars:`dot`,color:L.suggestion})},{name:`segments`,render:()=>H(Pe,{percent:0,width:30,chars:`block`,labelPosition:`prefix`,segments:[{key:`overhead`,width:4,color:L.accent},{key:`messages`,width:18,color:L.success},{key:`free`,width:8,color:L.inactive,dimColor:!0}]})},{name:`markers`,render:()=>H(Pe,{percent:90,width:10,chars:`dot`,color:L.suggestion,markers:{prune:{pos:7,color:L.warning},compact:{pos:9,color:L.error}}})}]},{id:`ScrollableBody`,category:`components`,title:`ScrollableBody (RFC-271 滚动容器)`,variants:[{name:`overflow-with-hint`,render:()=>H(Wp,{visibleRows:5,offset:0},...Array.from({length:8},(e,t)=>H(X,{key:t},`row ${t+1}`)))},{name:`fits-no-scroll`,render:()=>H(Wp,{visibleRows:5,offset:0},...Array.from({length:3},(e,t)=>H(X,{key:t},`row ${t+1}`)))}]},{id:`IdleTipCard`,category:`components`,title:`IdleTipCard (空闲技巧卡片)`,variants:[{name:`with-tip`,render:()=>H(hm,{tip:`Ctrl+R 搜索历史命令`})}]},{id:`Icon`,category:`components`,title:`Icon (RFC-273 具名图标)`,variants:[{name:`named-icons`,render:()=>H(Y,{flexDirection:`column`},H(vm,{name:`pointer`,color:`selection`,trailingSpace:!0}),H(vm,{name:`check`,color:`success`}),H(vm,{name:`cross`,color:`error`}),H(vm,{name:`statusDot`,color:`accent`}))}]},{id:`DialogFrame`,category:`components`,title:`DialogFrame`,variants:[{name:`default`,render:()=>H(y,{header:H(p,{children:`Confirm action`}),children:H(I,{variant:`ghost`,color:`gray`,label:`Body content goes here`}),footer:`Enter confirm · Esc cancel`})}]},{id:`DialogTitle`,category:`components`,title:`DialogTitle`,variants:[{name:`default`,render:()=>H(p,{children:`Settings`})},{name:`warning-color`,render:()=>H(p,{color:L.warning,children:`Forced upgrade`})}]},{id:`HintBar`,category:`components`,title:`HintBar`,variants:[{name:`multi-hint`,render:()=>H(O,{items:[[`← →`,`select`],[`Enter`,`confirm`],[`y/n/a`,`shortcut`],[`Esc`,`cancel`]]})}]},{id:`LiveClock`,category:`components`,title:`LiveClock`,variants:[{name:`default`,render:()=>H(bm,{})}]},{id:`Spinner`,category:`components`,title:`Spinner`,variants:[{name:`responding`,render:()=>H(gd,{verb:`Thinking`,mode:`responding`,responseLength:128,tokens:6800,progressPercent:42})},{name:`requesting`,render:()=>H(gd,{verb:`Reticulating`,mode:`requesting`})},{name:`stalled`,render:()=>H(gd,{verb:`Waiting`,responseLength:64,hasActiveTools:!1,toolTurnCount:8,maxToolTurns:10})}]},{id:`StreamingSpinner`,category:`components`,title:`StreamingSpinner`,variants:[{name:`streaming`,render:()=>{let e=rl();return e.store.setState({processing:!0,streamingText:`Generating a response for the user request…`,spinnerMode:`responding`,outputTokensThisTurn:512,maxOutputTokens:4096,toolTurnCount:3,maxToolTurns:12,activeTool:null}),H(_d,{streamStore:e,pendingPermission:null})}}]},{id:`BreathingTool`,category:`components`,title:`BreathingTool`,variants:[{name:`default`,render:()=>H(tl,{name:`grep`})}]},{id:`ThinkingLine`,category:`components`,title:`ThinkingLine`,variants:[{name:`default`,render:()=>H($c,{tokens:6800,toolTurnCount:2,maxToolTurns:12,promptOutputTokens:1200,promptOutputTokenBudget:8e3})}]},{id:`PerfIndicator`,category:`components`,title:`PerfIndicator`,variants:[{name:`warning`,render:()=>H(xm,{level:`warning`,usedPct:72.4})},{name:`critical`,render:()=>H(xm,{level:`critical`,usedPct:91.2})},{name:`warning (no usedPct)`,render:()=>H(xm,{level:`warning`})}]},{id:`NotificationBell`,category:`components`,title:`NotificationBell`,variants:[{name:`normal`,render:()=>H(Sm,{count:3,hasUrgent:!1})},{name:`urgent`,render:()=>H(Sm,{count:1,hasUrgent:!0})}]},{id:`Toast`,category:`components`,title:`Toast`,variants:[{name:`default`,render:()=>H(wm,{toast:{id:1,title:`Theme changed`,content:`Switched to dark theme`}})}]},{id:`Home`,category:`components`,title:`Home`,variants:[{name:`default`,render:()=>H(cd,{version:`0.1.0`,buildId:1234,cwd:`/home/user/project`})}]},{id:`SignalBar`,category:`components`,title:`SignalBar`,variants:[{name:`all counts (delegates active)`,render:()=>H(Yd,{counts:{tasks:4,delegates:3,edited:7,subagents:2,clipboard:0},labels:{tasks:`Tasks`,delegates:`Delegates`,edited:`Edited`,subagents:`Subagents`,clipboard:`Clipboard`,clipboardFailed:`Copy blocked — hold Shift and drag`},currentPath:`/pane/delegates`,tabHint:`Tab to switch`})},{name:`partial (only non-zero signals shown)`,render:()=>H(Yd,{counts:{tasks:0,delegates:0,edited:2,subagents:0,clipboard:0},labels:{tasks:`Tasks`,delegates:`Delegates`,edited:`Edited`,subagents:`Subagents`,clipboard:`Clipboard`,clipboardFailed:`Copy blocked — hold Shift and drag`},tabHint:`Tab to switch`})},{name:`clipboard copied (success)`,render:()=>H(Yd,{counts:{tasks:0,delegates:0,edited:0,subagents:0,clipboard:128},labels:{tasks:`Tasks`,delegates:`Delegates`,edited:`Edited`,subagents:`Subagents`,clipboard:`Copied`,clipboardFailed:`Copy blocked — hold Shift and drag`}})},{name:`clipboard failed (warning, no count)`,render:()=>H(Yd,{counts:{tasks:0,delegates:0,edited:0,subagents:0,clipboard:0,clipboardFailed:!0},labels:{tasks:`Tasks`,delegates:`Delegates`,edited:`Edited`,subagents:`Subagents`,clipboard:`Copied`,clipboardFailed:`Copy blocked — hold Shift and drag for native copy`}})},{name:`empty (blank 1-row placeholder)`,render:()=>H(Yd,{counts:{tasks:0,delegates:0,edited:0,subagents:0,clipboard:0},labels:{tasks:`Tasks`,delegates:`Delegates`,edited:`Edited`,subagents:`Subagents`,clipboard:`Clipboard`,clipboardFailed:`Copy blocked — hold Shift and drag`}})}]},{id:`StatusBar`,category:`components`,title:`StatusBar`,variants:[{name:`wide (full visibility)`,render:()=>H(Om,{columns:120,footerVisible:tu(120),perfIndicatorLevel:`healthy`,perfIndicatorUsedPct:void 0,modelName:`claude-sonnet-4-5`,budget:{modelName:`claude-sonnet-4-5`,contextWindow:2e5,contextPercent:42,overheadTokens:2e3,messageTokens:82e3,pruneLine:16e4,compactLine:18e4},badgeEntries:[{id:`host:permission-mode`,text:`Auto`,separator:`dot`,tier:`narrow`,isHost:!0},{id:`host:cost`,text:`$0.12`,separator:`space`,tier:`medium`,isHost:!0},{id:`demo:status`,text:`demo-plugin ready`,separator:`space`,tier:`low`,isHost:!1}],fullScreenPaneActive:!1,backgroundTasks:[],scheduleEnabledCount:0,agentProcessing:!1,queuedItems:[],notifications:[],language:`en`,welcome:void 0,messages:[],hasHistory:!0})},{name:`narrow (agent processing)`,render:()=>H(Om,{columns:60,footerVisible:tu(60),perfIndicatorLevel:`warning`,perfIndicatorUsedPct:78.5,modelName:`deepseek-v4`,budget:null,badgeEntries:[{id:`host:permission-mode`,text:`Autopilot`,color:`warning`,separator:`dot`,tier:`narrow`,isHost:!0}],fullScreenPaneActive:!1,backgroundTasks:[],scheduleEnabledCount:2,agentProcessing:!0,queuedItems:[],notifications:[],language:`zh`,welcome:void 0,messages:[],hasHistory:!0})}]},{id:`Checkbox`,category:`components`,title:`Checkbox`,variants:[{name:`checked`,render:()=>H(sm,{checked:!0,label:`Enable telemetry`,onChange:()=>{}})},{name:`unchecked`,render:()=>H(sm,{checked:!1,label:`Enable telemetry`,onChange:()=>{}})}]},{id:`List`,category:`components`,title:`List`,variants:[{name:`three-options`,render:()=>H(ot,{options:[{value:`a`,label:`model-a`,detail:`fast`},{value:`b`,label:`model-b`,detail:`balanced`},{value:`c`,label:`model-c`,detail:`deep`,disabled:!0}],onSelect:()=>{}})}]},{id:`ListItem`,category:`components`,title:`ListItem`,variants:[{name:`label-detail`,render:()=>H(Se,{label:`model-a`,detail:`fast · 200k ctx`})},{name:`disabled`,render:()=>H(Se,{label:`model-x`,detail:`unavailable`,disabled:!0})}]},{id:`Wordmark`,category:`components`,title:`Wordmark`,variants:[{name:`default`,render:()=>H(id)}]},{id:`ScheduleIndicator`,category:`components`,title:`ScheduleIndicator`,variants:[{name:`two-scheduled`,render:()=>H(fm,{enabledCount:2})}]},{id:`PulseSurveyOverlay`,category:`components`,title:`PulseSurveyOverlay`,variants:[{name:`rating`,render:()=>H(dm,{item:{phase:`rating`,rating:null,selectedIndex:0,commentText:``,commentOffset:0,onSubmit:()=>{},onClose:()=>{}},columns:60})}]}],jm=()=>{},Mm=Date.UTC(2026,6,10,12,0,0),Nm=[{id:`t1`,title:`Read type contract`,status:`done`,turn:1},{id:`t2`,title:`Implement pane examples`,status:`in_progress`,turn:3},{id:`t3`,title:`Wire registry aggregation`,status:`pending`},{id:`t4`,title:`Skip redundant EditedFilesPane`,status:`skipped`,turn:2},{id:`t5`,title:`Run typecheck gate`,status:`failed`,turn:4}],Pm=[{id:`d1`,command:`refactor error handling in run-modes.ts`,type:`agent-session`,origin:`user`,status:`running`,agentStatus:`ready`,startedAt:Mm-92e3,diffStat:`+42/-18`,turnIndex:4,toolUseCount:11,tokenCount:8400,model:`claude-sonnet-4`,modelDecidedBy:`category`},{id:`d2`,command:`npm run build`,type:`process`,status:`running`,startedAt:Mm-45e3,port:5173},{id:`d3`,command:`grep -rn TODO packages/`,type:`process`,status:`exited`,startedAt:Mm-3e5,exitCode:0},{id:`d4`,command:`audit security surface`,type:`agent-session`,origin:`main`,status:`running`,agentStatus:`needs_input`,startedAt:Mm-15e3,turnIndex:2,toolUseCount:3,model:`deepseek-v4`}],Fm={id:`d1`,command:`refactor error handling in run-modes.ts`,status:`running`,prompt:`Refactor the error handling in run-modes.ts to use the shared classifier.`,responseText:`turn 4 ${R.check} 3 tools 2.1s\n activity editing run-modes.ts\n tokens 8.4k out · 11 tools`,text:`applying edit to run-modes.ts …
72
+ + import { classify } from "./classify"
73
+ `},Im=[{id:`s1`,command:`@explore survey the compiler pipeline`,type:`agent-session`,origin:`main`,status:`running`,agentStatus:`running`,startedAt:Mm-12e4,stall:`none`,turnIndex:6,toolUseCount:14,filesEdited:2,tokenCount:12300,model:`claude-sonnet-4`,modelDecidedBy:`slot`,lastActivity:`using grep`},{id:`s2`,command:`@librarian cross-check RFC references`,type:`agent-session`,origin:`main`,status:`running`,agentStatus:`running`,startedAt:Mm-8e4,stall:`warn`,idleMs:6e3,blockedOn:`model_io`,turnIndex:3,toolUseCount:5,tokenCount:4100,model:`deepseek-v4`,lastActivity:`awaiting model`},{id:`s3`,command:`@reviewer critique integration wiring`,type:`agent-session`,origin:`main`,status:`running`,agentStatus:`running`,startedAt:Mm-2e5,stall:`stalled`,idleMs:34e3,blockedOn:`approval`,abortable:!1,turnIndex:8,toolUseCount:9,tokenCount:7800,model:`claude-sonnet-4`,lastActivity:`awaiting approval`},{id:`s4`,command:`@explore locate dead code`,type:`agent-session`,origin:`main`,status:`exited`,agentStatus:`applied`,startedAt:Mm-4e5,turnIndex:5,toolUseCount:7}],Lm=[{id:`sc1`,name:`Daily standup digest`,cronExpression:`0 9 * * 1-5`,enabled:!0,recurring:!0,nextFireAt:Mm+36e5,lastFiredAt:Mm-828e5},{id:`sc2`,name:`One-shot release reminder`,cronExpression:``,enabled:!1,recurring:!1,nextFireAt:Mm+72e5}],Rm=[{text:`implement the pane gallery entries`,mode:`send`},{text:`pnpm --filter @x-otto/tui typecheck`,mode:`bash`},{text:`run the build in the background`,mode:`bash_async`},{text:`remember: gallery entries live under examples/`,mode:`memory`}],zm=[{id:`df1`,name:`rfc-outline`,text:`Draft the RFC outline covering the pluginization endgame audit and adoption assessment.`,savedAt:Mm-36e5},{id:`df2`,name:`commit-message`,text:`feat(tui): add pane gallery example registry`,savedAt:Mm-6e5}],Bm=[{id:1,source:`job`,level:`info`,title:`Delegate ready`,message:`refactor job produced a diff (+42/-18)`,timestamp:Mm-3e4,read:!1,action:`/delegates`},{id:2,source:`version`,level:`warning`,title:`Update available`,message:`a newer build (1300) is available`,timestamp:Mm-6e5,read:!1},{id:3,source:`system`,level:`error`,title:`MCP server crashed`,message:`filesystem server exited unexpectedly`,timestamp:Mm-36e5,read:!0}],Vm=[{id:`TaskPane`,category:`components`,title:`TaskPane`,variants:[{name:`default`,render:()=>H(Wd,{tasks:Nm,title:`Feature implementation`})},{name:`focused`,render:()=>H(Wd,{tasks:Nm,title:`Feature implementation`,focused:!0})}]},{id:`DelegatesPane`,category:`components`,title:`DelegatesPane`,variants:[{name:`focused`,render:()=>H(Md,{tasks:Pm,columns:80,active:!0,onClose:jm})},{name:`summary`,render:()=>H(Md,{tasks:Pm,columns:80,active:!1,onClose:jm})}]},{id:`DelegateOutputPane`,category:`components`,title:`DelegateOutputPane`,variants:[{name:`running`,render:()=>H(Nd,{view:Fm,columns:80,rows:24,active:!0})}]},{id:`SubagentsPane`,category:`components`,title:`SubagentsPane`,variants:[{name:`focused`,render:()=>H(Ld,{tasks:Im,focused:!0,now:Mm})},{name:`summary`,render:()=>H(Ld,{tasks:Im,focused:!1,now:Mm})}]},{id:`SchedulePane`,category:`components`,title:`SchedulePane`,variants:[{name:`focused`,render:()=>H(Bd,{tasks:Lm,focused:!0})}]},{id:`QueuePane`,category:`components`,title:`QueuePane`,variants:[{name:`focused`,render:()=>H(ef,{items:Rm,focused:!0})},{name:`grabbed`,render:()=>H(ef,{items:Rm,focused:!0})}]},{id:`DraftPane`,category:`components`,title:`DraftPane`,variants:[{name:`focused`,render:()=>H($d,{items:zm,focused:!0})}]},{id:`NotificationsPane`,category:`components`,title:`NotificationsPane`,variants:[{name:`default`,render:()=>H(yf,{notifications:Bm,onDismiss:jm,onClose:jm})}]}];function Hm({taskTitle:e,turn:t,messages:n,rows:r,columns:i,onDismiss:a}){let o=h();j(`task-detail-pane`,(e,t)=>t.escape?(a(),!0):!1);let s=n.reduce((e,t)=>e+$s(t,i).length,0),c=Math.max(3,ee(s+4,r)-4),l=[],u=c;for(let e of n){let t=$s(e,i);if(u-t.length<0&&l.length>0||(l.push({m:e,lines:t}),u-=t.length,u<=0))break}return q(y,{header:J(Y,{flexDirection:`row`,children:[J(X,{color:o.replyPrefix,children:[R.bullet,` `]}),J(X,{color:o.secondary,bold:!0,children:[B.t(`task.detailTitle`),`:`,` `]}),q(X,{color:o.accent,children:e}),J(D,{type:`secondary`,dim:!0,children:[` `,B.t(`task.turnInfo`,{turn:t,shown:l.length,total:n.length})]})]}),footer:q(O,{items:[[T.esc,B.t(`hint.back`)],[T.tab,B.t(`hint.tabFocus`)]]}),children:J(Y,{marginTop:F.tight,paddingLeft:F.section,flexDirection:`column`,children:[l.map(({lines:e},t)=>q(Y,{flexDirection:`column`,children:e.map((e,t)=>q(Y,{flexDirection:`row`,children:q(X,{children:e})},t))},t)),l.length<n.length&&q(Y,{children:q(D,{type:`secondary`,dim:!0,children:B.t(`task.truncated`,{n:n.length-l.length})})})]})})}function Um(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(e<1e4?1:0)}k`:`${(e/1e6).toFixed(1)}m`}function Wm(e,t){switch(e){case`overhead`:return t.accent;case`messages`:return t.success;case`free`:return t.inactive}}function Gm(e,t){let n=[{kind:`overhead`,tokens:e.overheadTokens,label:B.t(`insp.budgetOverhead`)},{kind:`messages`,tokens:e.messageTokens,label:B.t(`insp.budgetMessages`)},{kind:`free`,tokens:e.free,label:B.t(`insp.budgetFree`)}].filter(e=>e.tokens>0);if(n.length===0)return[];let r=n.reduce((e,t)=>e+t.tokens,0),i=[],a=0;for(let e=0;e<n.length;e++){let o=n[e],s=e===n.length-1?t-a:Math.max(1,Math.round(o.tokens/r*t));i.push({kind:o.kind,width:s,tokens:o.tokens,label:o.label}),a+=s}return i}function Km({budget:e,width:t}){let n=h(),r=Math.min(40,Math.max(20,t-16)),i=Gm(e,r),a=Math.max(0,Math.min(100,Math.round(e.contextPercent))),o=a>=90?n.error:a>=80?n.warning:n.accent,s=t<80,c=t<60,l=e.pruneLine>0?Math.round(e.pruneLine/e.contextWindow*r):-1,u=e.compactLine>0?Math.round(e.compactLine/e.contextWindow*r):-1;return J(Y,{flexDirection:`column`,children:[e.modelName?J(Y,{children:[q(X,{color:n.suggestion,children:e.modelName}),q(D,{type:`secondary`,children:` · `}),q(D,{type:`secondary`,children:B.t(`context.tokensLabel`,{formatted:Um(e.contextWindow)})})]}):q(D,{type:`secondary`,children:B.t(`context.tokensLabel`,{formatted:Um(e.contextWindow)})}),(l>=0||u>=0)&&q(Y,{children:(()=>{let e=[];l>=0&&e.push({pos:5+l,color:n.warning}),u>=0&&e.push({pos:5+u,color:n.error}),e.sort((e,t)=>e.pos-t.pos);let t=0;return e.map((e,n)=>{let r=Math.max(0,e.pos-t);return t=e.pos+1,J(X,{color:e.color,children:[` `.repeat(r),`▼`]},n)})})()}),J(Y,{children:[J(X,{color:o,bold:!0,children:[String(a).padStart(3),`%`,` `]}),q(Pe,{percent:a,width:r,chars:`block`,segments:i.map(e=>({key:e.kind,width:e.width,color:Wm(e.kind,n),dimColor:e.kind===`free`})),labelPosition:`none`}),J(D,{type:`secondary`,children:[` `,Um(e.totalUsed),`/`,Um(e.contextWindow)]})]}),!c&&q(Y,{children:i.map((t,r)=>J(V.Fragment,{children:[J(X,{color:Wm(t.kind,n),dimColor:t.kind===`free`,children:[`█`,` `]}),q(D,{type:`secondary`,children:(()=>{let n=s?t.label.slice(0,3):t.label,r=t.kind===`messages`&&e.messageCount>0?`(${e.messageCount})`:``;return`${n} ${Um(t.tokens)}${r}`})()}),r<i.length-1&&q(D,{type:`secondary`,children:` `})]},r))})]})}function qm({budget:e,columns:t,onDismiss:n,onViewDetails:r}){let i=h();return j(`context-pane`,(e,t)=>{t.escape?n():t.return&&r()}),J(Y,{flexDirection:`column`,...ie,borderColor:i.panelBorder,backgroundColor:i.overlayBg,paddingX:F.tight,children:[q(X,{color:i.secondary,bold:!0,children:B.t(`context.title`)}),q(Y,{marginTop:F.tight,flexDirection:`column`,children:e?q(Km,{budget:e,width:t-fe.contentInset}):q(X,{dimColor:!0,children:B.t(`context.noData`)})}),q(Y,{marginTop:F.tight,children:J(X,{dimColor:!0,children:[B.t(`context.viewDetails`),` · `,B.t(`common.escClose`)]})})]})}function Jm(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function Ym({owned:e,total:t,width:n}){let r=h(),i=t>0?Math.min(1,e/t):0,a=Math.max(3,n-12);return q(Pe,{percent:Math.round(i*100),width:a,chars:`dot`,color:i>=.85?r.warning:i>=.7?r.accent:r.secondary})}function Xm({s:e}){let t=e.lane===`volatile`?B.t(`context.laneVolatile`):B.t(`context.laneCache`);return J(D,{type:e.lane===`volatile`?`secondary`:`primary`,children:[` `,t,` `,e.label,` (`,Jm(e.estimatedTokens),`t)`]})}function Zm({t:e,inProgress:t}){let r=e.role===`user`?R.pointer:R.bullet,i=[];e.pruned&&i.push(B.t(`context.tagPruned`)),e.compacted&&i.push(B.t(`context.tagCompacted`)),e.truncated&&i.push(B.t(`context.tagTruncated`));let a=e.pruned||e.compacted?`secondary`:`primary`;return J(Y,{flexDirection:`row`,children:[t?q(vm,{name:`pointer`,color:`accent`,trailingSpace:!0}):q(D,{type:`secondary`,children:` `}),J(D,{type:a,bold:t,children:[r,` `,B.t(`context.turnRow`,{index:e.turnIndex,messages:e.messageCount,tokens:Jm(e.estimatedTokens)})]}),i.map(e=>q(n,{leadingSpace:!0,children:e},e))]})}function Qm({ctxStore:e,columns:t,onBack:n}){let r=Z(e.store,e=>e.conversationTurns),i=Z(e.store,e=>e.systemSections),a=Z(e.store,e=>e.modelName),o=Z(e.store,e=>e.contextWindow),s=Z(e.store,e=>e.contextPercent),c=Z(e.store,e=>e.totalUsed),l=Z(e.store,e=>e.free),u=i.filter(e=>e.lane===`stable`).length,d=i.length-u,f=i.reduce((e,t)=>e+t.estimatedTokens,0),p=Math.max(0,c-f),m=Math.max(0,r.length-5),h=W(()=>r.slice(m),[r,m]),g=W(()=>r.slice(0,m).reduce((e,t)=>e+t.estimatedTokens,0),[r,m]);j(`context-panel`,At((e,t)=>{t.escape&&n()},[n]));let _=Math.max(40,t-fe.contentInset);return J(Y,{flexDirection:`column`,children:[J(Y,{flexDirection:`row`,justifyContent:`space-between`,children:[q(D,{type:`secondary`,bold:!0,children:B.t(`context.title`)}),a&&q(D,{type:`secondary`,children:a})]}),q(Y,{marginY:F.tight,children:q(Ym,{owned:c,total:o,width:_})}),i.length>0&&J(Mt,{children:[J(D,{type:`secondary`,children:[B.t(`context.systemHeading`),` (`,B.t(`context.systemMeta`,{tokens:Jm(f),stable:u,volatile:d}),`)`]}),i.map(e=>q(Xm,{s:e},e.label)),q(Y,{marginY:F.tight,children:q(D,{type:`secondary`,children:R.hr.repeat(_-4)})})]}),J(D,{type:`secondary`,children:[B.t(`context.conversationHeading`),` (`,B.t(`context.conversationMeta`,{tokens:Jm(p),turns:r.length}),`)`]}),q(Y,{height:1,children:m>0&&J(D,{type:`secondary`,children:[` `,R.bullet,` `,B.t(`context.earlierTurns`,{count:m,tokens:Jm(g)})]})}),h.map(e=>q(Zm,{t:e,inProgress:!1},e.turnIndex)),q(Y,{marginTop:F.tight,children:q(D,{type:`secondary`,children:B.t(`context.totalLine`,{used:Jm(c),window:Jm(o),percent:Math.round(s),free:Jm(l)})})})]})}function $m({message:e,onUpgrade:t,onCancel:n}){let r=h(),[i,a]=K(0),o=V.useRef(0);return o.current=i,Re({tabIndex:0,id:`forced-upgrade`,onEscape:()=>!0}),j(`forced-upgrade-buttons`,(e,r)=>{if(r.escape)return!0;let i=E(r);return i===0?r.return?(a(e=>(e===0?t?.():n?.(),e)),!0):!1:(a(e=>Le(e,i,2)),!0)}),J(y,{header:q(p,{color:r.warning,children:B.t(`model.forcedUpgradeTitle`)}),footer:q(O,{items:[[`${T.left}${T.right}`,B.t(`hint.switch`)],[T.enter,B.t(`hint.confirm`)]]}),children:[q(Y,{marginTop:F.tight,children:q(X,{children:e})}),J(Y,{marginTop:F.tight,flexDirection:`row`,gap:F.section,children:[q(I,{variant:`solid`,brackets:!0,color:`amber`,label:B.t(`common.upgradeButton`),focused:i===0}),q(I,{variant:`solid`,brackets:!0,color:`gray`,label:B.t(`common.cancelButton`),focused:i===1})]})]})}const eh=()=>{},th=Date.UTC(2026,6,10,12,0,0),nh=`export function greet(name: string) {
74
+ return \`Hi \${name}\`
75
+ }
76
+ `,rh=`export function greet(name: string): string {
77
+ return \`Hello, \${name}!\`
78
+ }
79
+ `,ih=[{path:`packages/tui/src/components/gallery/examples/components-panes-viewers.ts`,operation:`write`,newContent:rh,addedLines:3,removedLines:0,timestamp:th-5e3},{path:`packages/tui/src/components/Button.tsx`,operation:`edit`,oldContent:nh,newContent:rh,addedLines:2,removedLines:2,timestamp:th-2e4},{path:`packages/tui/src/legacy/old-helper.ts`,operation:`delete`,oldContent:nh,addedLines:0,removedLines:3,timestamp:th-4e4}],ah=[{role:`assistant`,content:[{type:`text`,text:`Reading the type contract before editing the registry.`}]},{role:`tool`,name:`read`,args:`gallery/types.ts`,result:`export interface GalleryEntry { ... }`},{role:`assistant`,content:[{type:`text`,text:`The contract is clear — constructing static mock props now.`}]}],oh={modelName:`claude-sonnet-4 (200K)`,contextWindow:2e5,contextPercent:38,overheadTokens:14e3,messageTokens:62e3,messageCount:42,totalUsed:76e3,free:124e3,pruneLine:14e4,compactLine:17e4,lastInput:3200,lastOutput:640,totalInput:58e3,totalOutput:18e3,cost:.42},sh={command:`pnpm --filter @x-otto/tui build`,output:`> @x-otto/tui build
80
+ > tsc -p tsconfig.json
81
+ Compiling…
82
+ src/components/gallery/examples`,status:`running`,exitCode:null},ch={command:`git status --short`,output:` M packages/tui/src/components/gallery/examples/components-panes.ts
83
+ ?? /tmp/scratch.ts`,status:`done`,exitCode:0},lh=Array.from({length:40},(e,t)=>`line ${t+1}: build step output`).join(`
84
+ `);function uh(){let e=wu();return e.setMemory({level:`warning`,heapUsed:512*1024*1024,heapSizeLimit:700*1024*1024,usedPct:73.1}),e.setNotify({coalescedCalls:1200,coalescedFires:340,immediateCalls:88,flushFires:12,coalesceRatio:3.5,alert:`healthy`}),e}function dh(){let e=Tu();return e.setView({lastTurnHitRatio:.82,sessionHitRatio:.71,totalCacheReadTokens:128e3,totalCacheWriteTokens:24e3,totalInputTokens:56e3,totalCostUSD:.18,perModel:[{modelId:`claude-sonnet-4`,modelName:`claude-sonnet-4`,cacheReadTokens:96e3,cacheWriteTokens:18e3,inputTokens:4e4,hitRatio:.75},{modelId:`deepseek-v4`,modelName:`deepseek-v4`,cacheReadTokens:32e3,cacheWriteTokens:6e3,inputTokens:16e3,hitRatio:null}]}),e}const fh=[{id:3,timestamp:Date.UTC(2026,6,13,14,32,7),kind:`compact`,before:1566,after:395,summary:`User asked to refactor the auth module. Assistant read auth-store.ts, extracted the token refresh logic into a separate helper, and added regression tests. All tests pass.`},{id:2,timestamp:Date.UTC(2026,6,13,14,10,2),kind:`prune`,tokensSaved:4200,prunedCount:12},{id:1,timestamp:Date.UTC(2026,6,13,13,58,41),kind:`history_capped`,removedCount:137}];function ph(){let e=Rl();return e.setBudget({modelName:`claude-sonnet-4 (200K)`,contextWindow:2e5,contextPercent:38,totalUsed:76e3,free:124e3,overheadTokens:14e3}),e.addTurn({turnIndex:1,role:`user`,messageCount:1,estimatedTokens:320,compacted:!1,truncated:!1,pruned:!1}),e.addTurn({turnIndex:2,role:`assistant`,messageCount:4,estimatedTokens:5200,compacted:!1,truncated:!1,pruned:!1}),e.addTurn({turnIndex:3,role:`assistant`,messageCount:6,estimatedTokens:8800,compacted:!0,truncated:!1,pruned:!1}),e.addTurn({turnIndex:4,role:`user`,messageCount:1,estimatedTokens:210,compacted:!1,truncated:!1,pruned:!1}),e.addTurn({turnIndex:5,role:`assistant`,messageCount:3,estimatedTokens:3400,compacted:!1,truncated:!0,pruned:!1}),e}const mh={title:`Broken plugin panel`,modulePath:`/nonexistent/plugin/panel-module.js`,exportName:`default`},hh=[{id:`EditedFilesPane`,category:`components`,title:`EditedFilesPane`,variants:[{name:`focused`,render:()=>H(xu,{files:ih,focused:!0,onDismiss:eh})}]},{id:`EditedFileFullPane`,category:`components`,title:`EditedFileFullPane`,variants:[{name:`diff`,render:()=>H(Mp,{file:ih[1],rows:24,onDismiss:eh,active:!0})}]},{id:`FileContentViewer`,category:`components`,title:`FileContentViewer`,variants:[{name:`default`,render:()=>H(rc,{lines:rh.split(`
85
+ `),rows:24,header:H(X,{bold:!0},`greet.ts`),onDismiss:eh,active:!0})}]},{id:`TaskDetailPane`,category:`components`,title:`TaskDetailPane`,variants:[{name:`default`,render:()=>H(Hm,{taskTitle:`Implement pane examples`,turn:3,messages:ah,rows:24,columns:80,onDismiss:eh})}]},{id:`SubagentContextView`,category:`components`,title:`SubagentContextView`,variants:[{name:`streaming`,render:()=>H(ud,{title:`@explore survey the compiler pipeline`,status:`running`,messages:ah,streamText:`Scanning packages/tui for pane components…`,rows:24,columns:80})}]},{id:`ShellPane`,category:`components`,title:`ShellPane`,variants:[{name:`running`,render:()=>H(Ap,{exec:sh,maxLines:8,columns:80})},{name:`done`,render:()=>H(Ap,{exec:ch,maxLines:8,columns:80,totalLines:2})}]},{id:`ShellFullOutputDialog`,category:`components`,title:`ShellFullOutputDialog`,variants:[{name:`default`,render:()=>H(Pp,{command:`pnpm --filter @x-otto/tui build`,output:lh,rows:24,columns:80,onDismiss:()=>{}})}]},{id:`ContextPane`,category:`components`,title:`ContextPane`,variants:[{name:`default`,render:()=>H(qm,{budget:oh,columns:80,onDismiss:eh,onViewDetails:eh})}]},{id:`ContextDetailPane`,category:`components`,title:`ContextDetailPane`,variants:[{name:`default`,render:()=>H(Qm,{ctxStore:ph(),columns:80,onBack:eh})}]},{id:`PerfPane`,category:`components`,title:`PerfPane`,variants:[{name:`default`,render:()=>H(Hp,{perfStore:uh(),onDismiss:eh,onRefresh:eh})}]},{id:`CachePane`,category:`components`,title:`CachePane`,variants:[{name:`default`,render:()=>H(Zp,{cacheStore:dh(),onDismiss:eh})}]},{id:`CompactionLogPane`,category:`components`,title:`CompactionLogPane`,variants:[{name:`default`,render:()=>H(om,{entries:fh,onClose:eh})}]},{id:`BackgroundTaskIndicator`,category:`components`,title:`BackgroundTaskIndicator`,variants:[{name:`default`,render:()=>H(Em,{tasks:Pm})}]},{id:`ServiceIndicator`,category:`components`,title:`ServiceIndicator`,variants:[{name:`default`,render:()=>H(Dm,{tasks:Pm.map(e=>e.id===`d2`?{...e,detectedService:{url:`http://localhost:5173/`,port:5173,protocol:`http`}}:e)})}]},{id:`ForcedUpgradeOverlay`,category:`components`,title:`ForcedUpgradeOverlay`,variants:[{name:`default`,render:()=>H($m,{message:`Your CLI is below the minimum supported version. Upgrade to continue.`,onUpgrade:eh,onCancel:eh})}]},{id:`TrustPromptDialog`,category:`components`,title:`TrustPromptDialog`,variants:[{name:`default`,render:()=>H(bn,{root:`/home/user/untrusted-project`,onChoice:eh})}]},{id:`PluginPane`,category:`components`,title:`PluginPane`,variants:[{name:`error`,render:()=>H(rp,{panelInfo:mh})}]}];function gh({item:e}){let t=h(),{phase:n,requestedAt:r,toolCount:i,totalToolCount:a,onCancel:o,onResume:s,onDismiss:c}=e,[l,u]=K(Math.floor((Date.now()-r)/1e3));return U(()=>{if(n!==`requested`)return;let e=setInterval(()=>{u(Math.floor((Date.now()-r)/1e3))},1e3);return()=>clearInterval(e)},[n,r]),Re({tabIndex:0,id:`pause-dialog`,onEscape:()=>(c?.(),!0),onAction:()=>(n===`requested`?o?.():s?.(),!0)}),j(`pause-dialog`,(e,t)=>t.escape?(c?.(),!0):t.return?(n===`requested`?o?.():s?.(),!0):!1),J(y,{header:q(p,{color:n===`active`?t.accent:void 0,children:n===`requested`?B.t(`pause.titleRequested`):B.t(`pause.titleActive`)}),paddingY:F.tight,children:[q(X,{children:n===`requested`?B.t(`pause.bodyRequested`):B.t(`pause.bodyActive`)}),q(Y,{marginTop:F.tight,children:q(X,{children:n===`requested`?B.t(`pause.toolCount`,{n:i,s:l}):a==null?``:B.t(`pause.toolTotal`,{n:a})})}),q(Y,{marginTop:F.tight,children:q(I,{variant:`solid`,brackets:!0,color:`accent`,focused:!0,label:n===`requested`?B.t(`pause.btnCancel`):B.t(`pause.btnResume`)})}),q(Y,{marginTop:F.tight,children:q(X,{dimColor:!0,children:n===`requested`?B.t(`pause.footerDismiss`):B.t(`pause.footerActive`)})})]})}const _h=()=>{},vh=(()=>Promise.resolve(null)),yh=[{id:`DataList`,category:`components`,title:`DataList`,variants:[{name:`groups+rows+text`,render:()=>H(Ye,{entries:[{kind:`group`,title:`连接`},{kind:`row`,label:`地址`,value:`http://127.0.0.1:7890`},{kind:`row`,label:`状态`,value:`已启用`,tone:`success`},{kind:`blank`},{kind:`group`,title:`其他`},{kind:`row`,label:`配置文件`,value:`~/.otto/config.json`,tone:`muted`},{kind:`text`,value:`提示:修改后需重启生效`,tone:`muted`}]})}]},{id:`EditableFieldRow`,category:`components`,title:`EditableFieldRow`,variants:[{name:`input/selected`,render:()=>H($p,{field:{kind:`input`,id:`url`,label:`代理地址`,value:`http://127.0.0.1:7890`},selected:!0})},{name:`input/empty`,render:()=>H($p,{field:{kind:`input`,id:`token`,label:`API Key`,value:``,mask:!0},selected:!1})},{name:`switch/on`,render:()=>H($p,{field:{kind:`switch`,id:`enabled`,label:`启用`,value:!0},selected:!1})}]},{id:`ParentWorkspaceDialog`,category:`dialogs`,title:`ParentWorkspaceDialog`,variants:[{name:`default`,render:()=>H(Cn,{parentRoot:`/Users/dev/projects/monorepo`,currentRoot:`/Users/dev/projects/monorepo/packages/app`,onChoice:_h})}]},{id:`PauseDialog`,category:`components`,title:`PauseDialog`,variants:[{name:`requested`,render:()=>H(gh,{item:{phase:`requested`,requestedAt:Date.now()-3e3,toolCount:2,totalToolCount:5}})},{name:`active`,render:()=>H(gh,{item:{phase:`active`,requestedAt:Date.now()-8e3,toolCount:0}})}]},{id:`ProxyPane`,category:`components`,title:`ProxyPane`,variants:[{name:`enabled`,render:()=>H(tm,{view:{url:`http://127.0.0.1:7890`,enabled:!0,configPath:`~/.otto/config.json`},onDismiss:_h,onOpenModal:vh,onSubmitUrl:_h,onToggleEnabled:_h,onClear:_h})},{name:`unconfigured`,render:()=>H(tm,{view:{configPath:`~/.otto/config.json`},onDismiss:_h,onOpenModal:vh,onSubmitUrl:_h,onToggleEnabled:_h,onClear:_h})}]},{id:`KeybindingsDialog`,category:`dialogs`,title:`KeybindingsDialog`,variants:[{name:`default`,render:()=>H(Jf,{overrides:void 0,onSave:_h,onSaveReplace:_h,onReset:_h,onResetAll:_h,onDismiss:_h})}]}],$=()=>{},bh=[{id:`svc-1`,command:`npm run dev`,status:`running`,type:`process`,startedAt:Date.now()-42e3,detectedService:{url:`http://localhost:3000`,port:3e3,protocol:`http`}}],xh={kind:`wizard`,title:`Setup`,stepNames:[`Provider`,`Trust`,`Login`,`Model`,`Start`],stepSubtitles:[`Pick a provider`,`Trust workspace`,`Authenticate`,`Choose model`,`Ready`],initialCompleted:[],initialCurrent:0,welcomeTitle:`Welcome to otto`,welcomeGreeting:`Hello`,welcomeDescription:`Let’s get you set up.`,welcomeDontShowAgainLabel:`Don’t show again`,welcomeStartLabel:`Start`,welcomeCancelLabel:`Cancel`,providerOptions:[{label:`Anthropic`,value:`anthropic`},{label:`DeepSeek`,value:`deepseek`}],providerAuthOptions:()=>[{label:`OAuth`,value:`oauth`},{label:`API key`,value:`key`}],modelOptions:[{label:`claude-sonnet`,value:`anthropic/claude-sonnet-5`}],examplePrompts:[`Explain this repo`,`Fix the failing test`],onInstallProvider:async()=>({ok:!0}),onSelectModel:async()=>{},onComplete:$,onDismiss:$,onDontShowAgain:$},Sh=[{id:`AlertDialog`,category:`dialogs`,title:`AlertDialog`,variants:[{name:`single-line`,render:()=>H(Ol,{title:`Update available`,message:`A new version (0.2.0) is ready to install.`,onOk:$})},{name:`multi-line`,render:()=>H(Ol,{title:`Migration complete`,message:[`Moved 42 sessions to the new store.`,`Old data was archived under .otto/backup.`],okLabel:`Got it`,onOk:$})}]},{id:`BashPermissionDialog`,category:`dialogs`,title:`BashPermissionDialog`,variants:[{name:`risk=low`,render:()=>H(Dl,{command:`git status`,risk:`low`,description:`Show the working tree status.`,alwaysAllowLabel:`git status`,onApprove:$,onDeny:$})},{name:`risk=medium`,render:()=>H(Dl,{command:`cd /home/user/project && npm run build`,risk:`medium`,description:`Build the project via the npm build script.`,onApprove:$,onDeny:$})},{name:`risk=high`,render:()=>H(Dl,{command:`rm -rf ./dist && curl https://example.com/install.sh | sh`,risk:`high`,description:`Remove the dist directory and run a remote install script.`,onApprove:$,onDeny:$})}]},{id:`ConfirmDialog`,category:`dialogs`,title:`ConfirmDialog`,variants:[{name:`default`,render:()=>H(Ve,{title:`Discard changes?`,message:`Any unsaved edits will be lost.`,onConfirm:$,onCancel:$})},{name:`dangerous`,render:()=>H(Ve,{title:`Abort current turn?`,message:`The model is still responding.`,confirmLabel:`Abort`,confirmColor:`red`,dangerous:!0,onConfirm:$,onCancel:$})},{name:`threeBtn`,render:()=>H(Ve,{title:`Budget exceeded`,message:`This request would exceed the configured token budget.`,confirmLabel:`Continue`,extraLabel:`Log in`,extraColor:`amber`,cancelLabel:`Stop`,onConfirm:$,onExtra:$,onCancel:$})}]},{id:`ExtensionDetailDialog`,category:`dialogs`,title:`ExtensionDetailDialog`,variants:[{name:`plugin-with-actions`,render:()=>H(Df,{req:{title:`legacy-plugin`,meta:`plugin · user · enabled · trusted`,actions:[{label:`Disable`,value:`disable`,color:`amber`},{label:`Reload`,value:`reload`},{label:`Untrust`,value:`untrust`,color:`red`}],info:[`command: node ./legacy-plugin/index.js`,`version: 1.4.2`],onAction:$,onClose:$}})},{name:`mcp-info-only`,render:()=>H(Df,{req:{title:`filesystem`,meta:`mcp · user · connected`,actions:[{label:`Reconnect`,value:`reconnect`}],info:[`url: stdio://filesystem`,`tools: read_file, write_file, list_dir`],onAction:$,onClose:$}})}]},{id:`ExtensionsListDialog`,category:`dialogs`,title:`ExtensionsListDialog`,variants:[{name:`grouped-with-details`,render:()=>H(xl,{req:{entries:[{category:`mcp`,id:`filesystem`,name:`filesystem`,enabled:!0,description:`stdio://filesystem`},{category:`skill`,id:`rfc-to-todos`,name:`rfc-to-todos`,enabled:!0,description:`Turn a fuzzy request into an RFC + TODO tracker + milestone doc.`},{category:`plugin`,id:`legacy-plugin`,name:`legacy-plugin`,enabled:!1,description:`command: node ./legacy-plugin/index.js`,applies:`next-turn`}],menuContributions:[{id:`open-config`,title:`Open plugin config →`}],onSelect:$,onCancel:$}})},{name:`empty`,render:()=>H(xl,{req:{entries:[],onSelect:$,onCancel:$}})}]},{id:`FileViewerDialog`,category:`dialogs`,title:`FileViewerDialog`,variants:[{name:`markdown-rendered`,render:()=>H(Af,{req:{path:`README.md`,content:[`# 安装指南`,``,`## 前置要求`,``,`### Node 版本`,`正文:需要 Node 18 以上,查看 [文档](https://example.com/docs)。`,``,`- 检查版本`," - 运行 `node -v`",` - 应显示 v18+`,`- [x] 安装依赖`,``,`> 注意:不要使用 sudo。`,``,"```bash",`pnpm build`,`pnpm test`,"```",``,`| Name | Status |`,`|---|---|`,`| Queue | Ready |`].join(`
86
+ `),onDismiss:$},rows:24,columns:80})},{name:`code-file`,render:()=>H(Af,{req:{path:`index.ts`,content:`export function add(a: number, b: number): number {
87
+ return a + b
88
+ }`,onDismiss:$},rows:24,columns:80})}]},{id:`HelpViewerDialog`,category:`dialogs`,title:`HelpViewerDialog`,variants:[{name:`command-list`,render:()=>{let e=e=>`\x1b[38;2;162;142;249m${e}\x1b[39m`,t=e=>`\x1b[38;2;148;152;184m${e}\x1b[39m`,n=e=>`\x1b[38;2;255;201;102m${e}\x1b[39m`,r=e=>`\x1b[1m\x1b[38;2;162;142;249m${e}\x1b[39m\x1b[22m`;return H(Nf,{req:{title:`Help`,lines:[r(`Session`),` ${e(`/clear`)} ${t(`Clear screen and reset interface state`)}`,` ${e(`/compact`)} ${t(`Compact context now`)}`,``,r(`Model & auth`),` ${e(`/model`)} ${t(`Switch model`)}`,` ${e(`/auth`)} ${t(`Log in to a provider`)}`,``,r(`Prefixes`),` ${n(`!<cmd>`)} ${t(`Run as shell command`)}`,` ${n(`@<file>`)} ${t(`Read file into context`)}`],onDismiss:$},rows:24,columns:80})}}]},{id:`PluginDialog`,category:`dialogs`,title:`PluginDialog`,variants:[{name:`panel-loading`,render:()=>H(ip,{req:{panelInfo:{title:`Miniprogram Use`,modulePath:`/nonexistent/config.mjs`,exportName:`default`},onClose:$}})}]},{id:`InfoDialog`,category:`dialogs`,title:`InfoDialog`,variants:[{name:`no-action`,render:()=>H(ve,{title:`Permissions`,lines:[`Bash: ask each time`,`Edit: auto-approve within project`,`WebFetch: ask each time`],onDismiss:$})},{name:`with-action`,render:()=>H(ve,{title:`Authentication expired`,lines:[`Your session token is no longer valid.`,`Log in again to continue.`],lineTones:{0:`warning`},action:{kind:`login`,run:$},onDismiss:$})},{name:`key-value/about`,render:()=>H(ve,{title:`About otto`,lines:pl([{label:`Version`,value:`0.0.1 (build 2709)`},{label:`Branch`,value:`dev`},{label:`Commit`,value:`525e96a8`},null,{label:`Runtime`,value:`Node.js v22.22.1 · darwin arm64`},{label:`CPU`,value:`12 cores`},{label:`Memory`,value:`48 GB total / 88 MB free`}]),onDismiss:$})},{name:`key-value/about-zh`,render:()=>H(ve,{title:`关于 otto`,lines:pl([{label:`版本`,value:`0.0.1 (build 2709)`},{label:`分支`,value:`dev`},{label:`提交`,value:`525e96a8`},null,{label:`运行时`,value:`Node.js v22.22.1 · darwin arm64`},{label:`当前模型`,value:`anthropic/claude-sonnet-5`}]),onDismiss:$})}]},{id:`InputDialog`,category:`dialogs`,title:`InputDialog`,variants:[{name:`plain`,render:()=>H(If,{title:`Rename session`,placeholder:`New session name`,onSubmit:$,onCancel:$})},{name:`masked-with-action`,render:()=>H(If,{title:`Enter API key`,description:[`Paste your provider API key below.`,`It is stored locally and never logged.`],placeholder:`sk-...`,mask:!0,actionButton:{label:`Open browser`},onActionButton:$,onSubmit:$,onCancel:$})}]},{id:`MemoryDialog`,category:`dialogs`,title:`MemoryDialog`,variants:[{name:`default`,render:()=>H(hl,{projectIndex:[`- [build-commands](memory/build-commands.md) — how to build and test this repo`,`- [api-endpoints](memory/api-endpoints.md) — non-sensitive service endpoints`].join(`
89
+ `),userIndex:`- [editor-prefs](memory/editor-prefs.md) — preferred editor and formatting`,onViewEntry:async()=>`sample entry content`,onForget:async()=>{},onDismiss:$})},{name:`empty`,render:()=>H(hl,{projectIndex:``,userIndex:``,onViewEntry:async()=>null,onForget:async()=>{},onDismiss:$})}]},{id:`PasteConfirmDialog`,category:`dialogs`,title:`PasteConfirmDialog`,variants:[{name:`default`,render:()=>H(gf,{content:Array.from({length:24},(e,t)=>`line ${t+1}: pasted content goes here`).join(`
90
+ `),onConfirm:$,onCancel:$})}]},{id:`PermissionDialog`,category:`dialogs`,title:`PermissionDialog`,variants:[{name:`risk=low`,render:()=>H(Cl,{tool:`read`,input:`{ "path": "src/index.ts" }`,risk:`low`,onApprove:$,onDeny:$})},{name:`risk=medium`,render:()=>H(Cl,{tool:`edit`,input:`{ "path": "src/app.ts", "oldContent": "...", "newContent": "..." }`,risk:`medium`,onApprove:$,onDeny:$})},{name:`risk=high`,render:()=>H(Cl,{tool:`web_fetch`,input:`{ "url": "https://external.example.com/data" }`,risk:`high`,onApprove:$,onDeny:$})}]},{id:`PromptDialog`,category:`dialogs`,title:`PromptDialog`,variants:[{name:`default`,render:()=>H(kl,{title:`Name this branch`,message:`Enter a short, descriptive branch name.`,placeholder:`feature/...`,onSubmit:$,onCancel:$})},{name:`with-initial-value`,render:()=>H(kl,{title:`Edit commit message`,message:[`Update the message below.`,`Use conventional commit format.`],initialValue:`feat: add gallery dialogs`,submitLabel:`Save`,onSubmit:$,onCancel:$})}]},{id:`QuestionsDialog`,category:`dialogs`,title:`QuestionsDialog`,variants:[{name:`single-question`,render:()=>H(Ke,{title:`Pick a deployment target`,questions:[{header:`Target`,question:`Which environment should we deploy to?`,multiSelect:!1,options:[{label:`Staging`,description:`Safe, non-production sandbox`},{label:`Production`,description:`Live user traffic`}]}],onSubmit:$,onCancel:$})},{name:`multi-question`,render:()=>H(Ke,{title:`Configure the run`,questions:[{header:`Scope`,question:`Which packages should the task cover?`,multiSelect:!0,options:[{label:`tui`},{label:`agent`},{label:`coding`}]},{header:`Mode`,question:`How should it run?`,multiSelect:!1,options:[{label:`Fast`},{label:`Thorough`}],freeformInput:!0,freeformPlaceholder:`Any extra notes…`}],onSubmit:$,onCancel:$})}]},{id:`SelectDialog`,category:`dialogs`,title:`SelectDialog`,variants:[{name:`list`,render:()=>H(dp,{title:`Select a model`,subtitle:`Choose the model for this session`,options:[{label:`claude-sonnet`,value:`sonnet`,detail:`balanced · 200k context`},{label:`claude-opus`,value:`opus`,detail:`strongest reasoning`},{label:`claude-haiku`,value:`haiku`,detail:`fast · cheap`}],onSelect:$,onCancel:$})},{name:`searchable`,render:()=>H(dp,{title:`Resume a session`,searchable:!0,options:[{label:`Refactor gallery registry`,value:`s1`,detail:`2 hours ago`},{label:`Fix dialog typecheck`,value:`s2`,detail:`yesterday`},{label:`RFC-147 planning`,value:`s3`,detail:`3 days ago`}],onSelect:$,onCancel:$})}]},{id:`SelectRoot`,category:`dialogs`,title:`Select.Root`,variants:[{name:`grouped`,render:()=>H(z.Root,{title:`Fruits & Vegetables`,children:H(z.Content,{children:[H(z.Group,{key:`fruits`,children:[H(z.Label,{key:`label`,children:`Fruits`}),H(z.Item,{key:`orange`,value:`orange`,children:`Orange`}),H(z.Item,{key:`apple`,value:`apple`,children:`Apple`}),H(z.Item,{key:`grape`,value:`grape`,disabled:!0,children:`Grape`})]}),H(z.Separator,{key:`sep`}),H(z.Group,{key:`vegetables`,children:[H(z.Label,{key:`label`,children:`Vegetables`}),H(z.Item,{key:`carrot`,value:`carrot`,children:`Carrot`}),H(z.Item,{key:`potato`,value:`potato`,detail:`starchy`,children:`Potato`})]})]})})}]},{id:`SelectItem`,category:`dialogs`,title:`Select.Item`,variants:[{name:`default`,render:()=>H(z.Root,{children:[H(z.Item,{key:`a`,value:`a`,children:`Item A`}),H(z.Item,{key:`b`,value:`b`,detail:`with detail text`,children:`Item B`}),H(z.Item,{key:`c`,value:`c`,disabled:!0,children:`Item C (disabled)`})]})}]},{id:`SelectGroup`,category:`dialogs`,title:`Select.Group`,variants:[{name:`default`,render:()=>H(z.Root,{children:H(z.Group,{children:[H(z.Label,{key:`label`,children:`Group A`}),H(z.Item,{key:`a1`,value:`a1`,children:`A1`})]})})}]},{id:`SelectLabel`,category:`dialogs`,title:`Select.Label`,variants:[{name:`default`,render:()=>H(z.Root,{children:H(z.Group,{children:[H(z.Label,{key:`label`,children:`A Group Label`}),H(z.Item,{key:`x`,value:`x`,children:`X`})]})})}]},{id:`SelectSeparator`,category:`dialogs`,title:`Select.Separator`,variants:[{name:`default`,render:()=>H(z.Root,{children:[H(z.Group,{key:`top`,children:[H(z.Label,{key:`label`,children:`Top`}),H(z.Item,{key:`t1`,value:`t1`,children:`T1`})]}),H(z.Separator,{key:`sep`}),H(z.Group,{key:`bottom`,children:[H(z.Label,{key:`label`,children:`Bottom`}),H(z.Item,{key:`b1`,value:`b1`,children:`B1`})]})]})}]},{id:`SelectContent`,category:`dialogs`,title:`Select.Content`,variants:[{name:`default`,render:()=>H(z.Root,{children:H(z.Content,{children:H(z.Item,{value:`only`,children:`Only Item`})})})}]},{id:`SelectTrigger`,category:`dialogs`,title:`Select.Trigger`,variants:[{name:`no-op-placeholder`,render:()=>H(z.Root,{children:[H(z.Trigger,{key:`trigger`}),H(z.Item,{key:`only`,value:`only`,children:`Only Item`})]})}]},{id:`Select`,category:`dialogs`,title:`Select (namespace)`,variants:[{name:`namespace-access`,render:()=>H(z.Root,{children:H(z.Item,{value:`a`,children:`Accessed via Select.Root`})})}]},{id:`ProgressDialog`,category:`dialogs`,title:`ProgressDialog`,variants:[{name:`running`,render:()=>H(rt,{title:`Installing plugin`,phases:[`Download`,`Extract`,`Register`],phaseIndex:1,phaseStatuses:[`done`,`active`,`pending`],percent:45,detail:`Extracting archive…`,status:`running`,onDismiss:$})},{name:`success`,render:()=>H(rt,{title:`Installing plugin`,phases:[`Download`,`Extract`,`Register`],phaseIndex:2,phaseStatuses:[`done`,`done`,`done`],percent:100,detail:``,status:`success`,onDismiss:$})},{name:`partial`,render:()=>H(rt,{title:`Installing plugin`,phases:[`Download`,`Extract`,`Register`],phaseIndex:1,phaseStatuses:[`done`,`error`,`done`],percent:100,detail:``,status:`partial`,errorMessage:`1 installed, 1 failed:demo-skill —— already exists`,nextStep:{kind:`force`,label:`Tip: add --force to overwrite the existing item`},onDismiss:$})},{name:`error`,render:()=>H(rt,{title:`Installing plugin`,phases:[`Download`,`Extract`,`Register`],phaseIndex:1,phaseStatuses:[`done`,`error`,`pending`],percent:100,detail:``,status:`error`,errorMessage:`2/2 failed:demo-skill —— already exists;other-skill —— already exists`,nextStep:{kind:`force`,label:`Tip: add --force to overwrite the existing item`},onDismiss:$})}]},{id:`ServicesDialog`,category:`dialogs`,title:`ServicesDialog`,variants:[{name:`one-service`,render:()=>H(Np,{tasks:bh,columns:80,rows:24,onDismiss:$})}]},{id:`ShortcutsDialog`,category:`dialogs`,title:`ShortcutsDialog`,variants:[{name:`list`,render:()=>H(mp,{shortcuts:[{name:`deploy`,text:`run the deploy script`}],onSave:$,onDelete:$,onDismiss:$})}]},{id:`QueueEditDialog`,category:`dialogs`,title:`QueueEditDialog`,variants:[{name:`edit-send`,render:()=>H(lf,{index:2,total:4,initialValue:`add unit tests for the parser`,mode:`send`,busy:!1,columns:80,onSendNow:$,onConfirm:$,onCancel:$})}]},{id:`ChipContentViewerDialog`,category:`dialogs`,title:`ChipContentViewerDialog`,variants:[{name:`paste-content`,render:()=>H(Op,{req:{label:`Pasted content #3`,content:`line one
91
+ line two
92
+ line three`,onDismiss:$},rows:24,columns:80})}]},{id:`A2uiFormDialog`,category:`dialogs`,title:`A2uiFormDialog`,variants:[{name:`form`,render:()=>H(xf,{component:{id:`form-1`,type:`Form`,formTitle:`Feedback`,fields:[{id:`name`,type:`text`,label:`Name`},{id:`subscribe`,type:`toggle`,label:`Subscribe`}]},columns:80,onAction:$,onDismiss:$})}]},{id:`OnboardingDialog`,category:`dialogs`,title:`OnboardingDialog`,variants:[{name:`step-0-nickname`,render:()=>H(wp,{columns:80,onComplete:$})}]},{id:`WizardDialog`,category:`dialogs`,title:`WizardDialog`,variants:[{name:`step-0-provider`,render:()=>H(lt,{request:xh})}]}];function Ch(e,t=72){return ae(e.replace(/\n/g,` ↵ `).replace(/\s+/g,` `).trim(),t)}function wh(e,t){let[n,r]=K(e);return U(()=>{if(n<=0){t();return}let e=setTimeout(()=>r(e=>e-1),1e3);return()=>clearTimeout(e)},[n,t]),n}function Th({item:e}){let t=h(),{attempt:n,max:r,delayMs:i,onExpired:a,reason:o,onStop:s,accelerate:c}=e,l=wh(Math.ceil(i/1e3),a),[u,d]=K(0),f=s!==void 0,m=f?2:1,g=()=>{c.skip=!0,a()},_=()=>{s?.()};return Re({tabIndex:0,id:`retry-countdown`,onAction:()=>(u===1&&f?_():g(),!0),onEscape:f?()=>(_(),!0):void 0}),j(`retry-countdown`,(e,t)=>{if(t.escape)return f?(_(),!0):!1;if(t.return)return u===1&&f?_():g(),!0;if(f&&(t.leftArrow||t.rightArrow||t.tab)){let e=E(t);return e!==0&&d(t=>Le(t,e,m)),!0}return e===`r`||e===`R`?(g(),!0):!1}),J(y,{header:q(p,{color:t.error,children:o?B.t(`retry.reason`,{reason:Ch(o)}):B.t(`retry.defaultTitle`)}),children:[q(X,{children:` `}),J(X,{children:[B.t(`retry.attempt`,{attempt:n,max:r}),B.t(`retry.progressSep`),B.t(`retry.countdown`,{s:l})]}),q(X,{children:` `}),J(Y,{flexDirection:`row`,gap:F.section,children:[q(I,{variant:`solid`,brackets:!0,color:`accent`,label:B.t(`retry.nowButton`),focused:u===0}),f&&q(I,{variant:`solid`,brackets:!0,color:`gray`,label:B.t(`retry.stopButton`),focused:u===1})]}),q(X,{children:` `}),q(X,{dimColor:!0,children:f?B.t(`retry.hintWithStop`):B.t(`retry.hint`)})]})}function Eh(e,t=72){return ae(e.replace(/\n/g,` ↵ `).replace(/\s+/g,` `).trim(),t)}function Dh(e,t=72){let n=e.replace(/\s+/g,` `).trim().split(` `),r=[],i=``;for(let e of n)i?(i+` `+e).length<=t?i+=` `+e:(r.push(i),i=e):i=e;return i&&r.push(i),r.length>0?r:[``]}function Oh(e){let t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function kh(e,t,n=30){let[r,i]=K(n);return U(()=>{i(n)},[n]),U(()=>{if(!e)return;if(r<=0){t();return}let n=setTimeout(()=>i(e=>e-1),1e3);return()=>clearTimeout(n)},[e,r,t]),r}function Ah(e,t,n,r){let[i,a]=K(t===void 0?null:Math.max(0,Math.round(t-r()/1e3)));return U(()=>{if(!e||t===void 0){a(null);return}let i=()=>{let e=Math.max(0,Math.round(t-r()/1e3));a(e),e<=0&&n()};i();let o=setInterval(i,1e3);return()=>clearInterval(o)},[e,t]),i}function jh({item:e,now:t=Date.now,rows:n,onFocusChange:r}){let i=h(),{reason:a,attempt:o,max:s,mode:c,resetsAt:l,limitType:u,actions:d,focusIndex:f,exhausted:m,pluginSource:g}=e,_=kh(c===`auto`&&!m,e.onExpired,e.intervalSeconds??30),v=Ah(c===`resetsAt`,l,e.onExpired,t),b=m?B.t(`error.exhaustedTitle`):a?B.t(`error.title`,{reason:Eh(a)}):B.t(`error.defaultTitle`),x=n==null?10:Math.min(10,Math.max(3,Math.floor(n/3))),S=(()=>{if(m||!a||a.length<=72)return null;let e=Dh(a,72);if(e.length<=x)return e;let t=e.slice(0,x-1),n=e.length-t.length;return[...t,B.t(`common.moreLinesLabel`,{n})]})(),C;C=m?B.t(`error.exhaustedBody`,{max:s}):c===`resetsAt`?v===null?B.t(`error.unknownReset`):B.t(`error.resetsIn`,{hms:Oh(v)}):c===`auto`?B.t(`error.autoCountdown`,{attempt:o,max:s,seconds:_}):u?B.t(`error.unknownReset`):B.t(`error.manualBody`,{attempt:o,max:s});let w=d.length+1,D=d.length,O=t=>{t<d.length?d[t].run():e.onCancel()};j(`error-retry-buttons`,(t,n)=>{if(n.escape)return r?.(D),e.onCancel(),!0;if(n.leftArrow||n.rightArrow||n.tab){let e=E(n);return e!==0&&r?.(Le(f,e,w)),!0}if(n.return)return O(f),!0;if(t.toLowerCase()===`r`){let e=d.findIndex(e=>e.kind===`retryNow`);if(e>=0)return r?.(e),d[e].run(),!0}return!1});let ee=e=>e===`retryNow`?`accent`:e===`login`?`amber`:`accent`;return J(y,{header:J(Y,{flexDirection:`column`,children:[J(p,{color:i.error,children:[R.cross,` `,b]}),S&&S.length>0&&J(Mt,{children:[q(X,{children:` `}),S.map((e,t)=>q(X,{dimColor:!0,children:e},t))]})]}),children:[u&&q(Y,{marginTop:F.tight,children:q(X,{dimColor:!0,children:B.t(`error.typeLabel`,{type:u.replace(/_/g,`-`)})})}),q(Y,{marginTop:F.tight,children:q(X,{color:c===`auto`&&!m?void 0:i.inactive,children:C})}),g&&q(Y,{marginTop:F.tight,children:q(X,{dimColor:!0,children:B.t(`cmd.errorRetryPluginSource`,{pluginId:g})})}),J(Y,{marginTop:F.tight,flexDirection:`row`,gap:F.section,flexWrap:`wrap`,children:[d.map((e,t)=>q(I,{variant:`solid`,brackets:!0,color:ee(e.kind),label:e.label,focused:f===t},e.kind)),q(I,{variant:`solid`,brackets:!0,color:`gray`,label:B.t(`common.genericCancelButton`),focused:f===D})]}),q(Y,{marginTop:F.tight,children:J(X,{dimColor:!0,children:[B.t(`error.hint`),d.some(e=>e.kind===`retryNow`)?` ${T.left}${T.right} ${B.t(`hint.switch`)} · r ${B.t(`hint.shortcut`)}`:``]})})]})}const Mh=()=>{};function Nh(){let e=[{label:`packages/tui/src/App.tsx`,value:`@packages/tui/src/App.tsx`,description:`TUI 根组件`,kind:`file`},{label:`packages/agent/src/agent.ts`,value:`@packages/agent/src/agent.ts`,description:`Agent 引擎入口`,kind:`file`},{label:`explore`,value:`@explore`,description:`代码探索子代理`,kind:`agent`},{label:`rfc-to-todos`,value:`@rfc-to-todos`,description:`RFC → TODO 工作流`,kind:`skill`,source:`extension`}];return{search:()=>e}}const Ph={role:`assistant`,content:[{type:`text`,text:`I found the relevant module. Here is a summary of what it does and how to use it.`}],tool_calls:[{id:`call_1`,type:`function`,function:{name:`read`,arguments:`{"path":"src/index.ts"}`}}],id:`msg_1`},Fh={role:`user`,content:`How does the retry backoff work in the stream error handler?`},Ih={role:`tool`,name:`read`,args:`src/index.ts`,result:`export function main() { ... }`},Lh={role:`compact_boundary`,before:1566,after:395},Rh={role:`prune_boundary`},zh={role:`model_switch`,label:`claude-haiku-4-5-20251001 (200K)`},Bh={role:`model_fallback`,configured:`anthropic/claude-haiku-4-5-20251001`,active:`deepseek-v4-pro (1M)`},Vh={role:`tool_completion`,content:`Background job "refactor-auth" completed successfully.`},Hh={role:`summary`,status:`done`,toolCount:6,elapsedMs:42e3,tokensUsed:18400,cacheHitRatio:.72,model:`claude-sonnet-4`},Uh=[{id:`PromptInput`,category:`input`,title:`PromptInput (simplified)`,variants:[{name:`empty-placeholder`,render:()=>H(Ai,{columns:80,placeholder:`Type a message…`,disabled:!0})}]},{id:`QueuedCommands`,category:`input`,title:`QueuedCommands`,variants:[{name:`three-queued`,render:()=>H(ji,{items:[{text:`review the PR`,mode:`send`},{text:`pnpm build`,mode:`bash`},{text:`remember to update the RFC`,mode:`memory`}]})}]},{id:`TextInput`,category:`input`,title:`TextInput`,variants:[{name:`send-mode`,render:()=>H(e,{value:`Hello, this is a sample message`,offset:31,columns:80,mode:`send`})},{name:`bash-mode`,render:()=>H(e,{value:`pnpm --filter @x-otto/tui typecheck`,offset:33,columns:80,mode:`bash`})},{name:`placeholder`,render:()=>H(e,{value:``,offset:0,columns:80,mode:`send`,placeholder:`Ask anything…`})},{name:`masked`,render:()=>H(e,{value:`sk-secret-api-key-value`,offset:23,columns:80,mode:`dialog`,mask:!0})}]},{id:`Message`,category:`messages`,title:`Message`,variants:[{name:`assistant`,render:()=>H(Fc,{message:Ph,columns:80})},{name:`user`,render:()=>H(Fc,{message:Fh,columns:80})},{name:`tool`,render:()=>H(Fc,{message:Ih,columns:80})},{name:`compact_boundary`,render:()=>H(Fc,{message:Lh,columns:80})},{name:`prune_boundary`,render:()=>H(Fc,{message:Rh,columns:80})},{name:`model_switch`,render:()=>H(Fc,{message:zh,columns:80})},{name:`model_fallback`,render:()=>H(Fc,{message:Bh,columns:80})},{name:`tool_completion`,render:()=>H(Fc,{message:Vh,columns:80})},{name:`summary`,render:()=>H(Fc,{message:Hh,columns:80})}]},{id:`ScrollableTranscript`,category:`messages`,title:`ScrollableTranscript`,variants:[{name:`bottom (live tail)`,render:()=>H(Gc,{messages:[Fh,Ph],columns:80,rows:12,scroll:0})},{name:`scrolled back (review hint)`,render:()=>H(Gc,{messages:[Fh,Ph],columns:80,rows:12,scroll:2,frozenNewCount:3})}]},{id:`REPLRegion`,category:`messages`,title:`REPLRegion (simplified)`,variants:[{name:`streaming`,render:()=>{let e=rl();return e.store.setState({processing:!0,streamingText:`Generating a response for the user request…`,spinnerMode:`responding`,toolTurnCount:2,maxToolTurns:12,activeTool:null}),H(sl,{streamStore:e,completedMessages:[Ph],columns:80,scrollStore:ta()})}}]},{id:`ContextBar`,category:`inspector`,title:`ContextBar (budget bar)`,variants:[{name:`default`,render:()=>H(Km,{budget:{modelName:`claude-sonnet-4 (200K)`,contextWindow:2e5,contextPercent:38,overheadTokens:14e3,messageTokens:62e3,messageCount:42,totalUsed:76e3,free:124e3,pruneLine:14e4,compactLine:17e4,lastInput:3200,lastOutput:640,totalInput:58e3,totalOutput:18e3,cost:.42},width:80})}]},{id:`SigilPane`,category:`sigil`,title:`SigilPane`,variants:[{name:`at-file-agent`,render:()=>H(xc,{sigil:`@`,initialQuery:``,registry:Nh(),active:!1,rows:24,onSelect:Mh,onClose:Mh})}]},{id:`RetryDialog`,category:`components`,title:`RetryDialog`,variants:[{name:`with-reason`,render:()=>H(Th,{item:{attempt:2,max:5,delayMs:8e3,accelerate:{skip:!1},onExpired:Mh,reason:`socket hang up`}})}]},{id:`ErrorRetryDialog`,category:`components`,title:`ErrorRetryDialog`,variants:[{name:`auto-30s`,render:()=>H(jh,{item:{reason:`socket hang up`,attempt:2,max:5,mode:`auto`,actions:[{kind:`retryNow`,label:`Retry now`,run:Mh}],focusIndex:0,exhausted:!1,onExpired:Mh,onCancel:Mh}})},{name:`resetsAt-known`,render:()=>H(jh,{item:{reason:`quota exhausted`,attempt:0,max:5,mode:`resetsAt`,resetsAt:Math.floor(Date.now()/1e3)+3*3600,limitType:`five_hour`,actions:[{kind:`retryNow`,label:`Retry now`,run:Mh},{kind:`switchModel`,label:`Switch model`,run:Mh}],focusIndex:0,exhausted:!1,onExpired:Mh,onCancel:Mh},now:()=>17e11})},{name:`manual-auth`,render:()=>H(jh,{item:{reason:`unauthorized (401)`,attempt:0,max:5,mode:`manual`,actions:[{kind:`login`,label:`Go to login`,run:Mh}],focusIndex:0,exhausted:!1,onExpired:Mh,onCancel:Mh}})},{name:`exhausted`,render:()=>H(jh,{item:{reason:`connection refused`,attempt:5,max:5,mode:`auto`,actions:[{kind:`retryNow`,label:`Retry now`,run:Mh}],focusIndex:0,exhausted:!0,onExpired:Mh,onCancel:Mh}})}]}],Wh=[...Am,...Vm,...hh,...yh,...Sh,...Uh],Gh=[`components`,`dialogs`,`input`,`messages`,`inspector`,`sigil`];function Kh(){let e=new Map;for(let t of Gh)e.set(t,[]);for(let t of Wh)e.get(t.category)?.push(t);return e}function qh({galleryStore:e,onDismiss:t,rows:n=24}){let r=h(),i=Z(e.store,e=>e),a=W(Kh,[]),o=W(()=>Gh.filter(e=>(a.get(e)?.length??0)>0),[a]),s=u(n),c=Math.max(3,s-12),l=o[i.categoryIndex%Math.max(1,o.length)],d=l?a.get(l)??[]:[],f=d[i.itemIndex],p=f?.variants[i.variantIndex],m=W(()=>{let e=Math.max(1,c-1);if(d.length<=e)return{items:d.map((e,t)=>({it:e,i:t})),end:d.length,hasMore:!1};let t=Math.floor(e/2),n=Math.min(Math.max(0,i.itemIndex-t),d.length-e),r=n+e;return{items:d.slice(n,r).map((e,t)=>({it:e,i:n+t})),end:r,hasMore:r<d.length}},[d,i.itemIndex,c]),g=Math.max(1,c-1),_=yt();return j(`gallery-pane`,(n,r)=>{if(r.escape){t();return}if(r.leftArrow||r.rightArrow){if(o.length===0)return;let t=r.leftArrow?-1:1,n=(i.categoryIndex+t+o.length)%o.length;e.setCategoryIndex(n);return}if(r.upArrow||r.downArrow){if(d.length===0)return;let t=r.upArrow?-1:1,n=(i.itemIndex+t+d.length)%d.length;e.setItemIndex(n);return}if(n===`[`||n===`]`||r.pageUp||r.pageDown){let t=f?.variants??[];if(t.length===0)return;let a=n===`[`||r.pageUp?-1:1,o=(i.variantIndex+a+t.length)%t.length;e.setVariantIndex(o)}},{isActive:_?_.currentPath===`/pane/gallery`:!0}),q(y,{header:J(Y,{flexDirection:`column`,children:[J(Y,{children:[q(X,{color:r.secondary,bold:!0,children:`Component Gallery`}),J(D,{type:`secondary`,children:[` `,Wh.length,` components`]})]}),q(Y,{marginTop:F.tight,children:o.map((e,t)=>q(X,{color:t===i.categoryIndex?r.selection:r.inactive,bold:t===i.categoryIndex,children:t===i.categoryIndex?`[${e}] `:`${e} `},e))})]}),footer:q(Mt,{children:`↑↓ component · ←→ category · [ ] variant · Esc close`}),children:J(Y,{marginTop:F.tight,flexDirection:`row`,children:[J(Y,{flexDirection:`column`,width:28,marginRight:F.section,children:[m.items.map(({it:e,i:t})=>J(X,{color:t===i.itemIndex?r.selection:r.text,bold:t===i.itemIndex,children:[t===i.itemIndex?`${R.pointer} `:` `,e.title]},e.id)),m.hasMore&&q(D,{type:`secondary`,children:` ↓ ${d.length-m.end} more`}),d.length===0&&q(D,{type:`secondary`,children:`no components in this category`})]}),J(Y,{flexDirection:`column`,flexGrow:1,children:[f&&q(Y,{marginBottom:F.tight,children:J(D,{type:`secondary`,children:[f.title,f.variants.length>1?` · ${p?.name} (${i.variantIndex+1}/${f.variants.length})`:``]})}),q(Y,{height:g,overflow:`hidden`,flexDirection:`column`,children:q(Y,{flexShrink:0,flexDirection:`column`,children:q(tp,{children:p?p.render():q(D,{type:`secondary`,children:`no variant selected`})},`${f?.id}-${i.variantIndex}`)})})]})]})})}const Jh=V.memo(function(e){let{perfOpen:t,perfStore:n,cacheStatsOpen:r,cacheStore:i,proxyOpen:a,proxyView:o,compactionLogOpen:s,compactionLogEntries:c,galleryOpen:l,galleryStore:u,columns:d,budget:f,contextStore:p,toast:m,subagentContext:h,retryCountdown:g,errorRetry:_,rows:y,pauseDialog:b,pulseSurvey:x,forcedUpgrade:S}=e,{onPerfDismiss:C,onPerfRefresh:w,onCacheDismiss:T,onProxyDismiss:E,onProxyOpenModal:D,onProxySubmitUrl:O,onProxyToggleEnabled:ee,onProxyClear:te,onProxyTest:ne,onCompactionLogDismiss:k,onGalleryDismiss:re,onContextDismiss:ie,onViewDetails:A,onBackToContextPane:ae,onDismissToast:j,onErrorRetryFocusChange:oe,onPulseSurveyChange:se,onUpgrade:M,onCancelUpgrade:N}=ql();return J(Mt,{children:[t&&q(Hp,{perfStore:n,onDismiss:C??(()=>{}),onRefresh:w??(()=>{})}),r&&q(Zp,{cacheStore:i,onDismiss:T??(()=>{})}),a&&q(tm,{view:o,onDismiss:E??(()=>{}),onOpenModal:D??Yh,onSubmitUrl:O??(()=>{}),onToggleEnabled:ee??(()=>{}),onClear:te??(()=>{}),onTest:ne}),s&&q(om,{entries:c,onClose:k??(()=>{})}),l&&q(qh,{galleryStore:u,onDismiss:re??(()=>{}),rows:y??24}),p&&J(Mt,{children:[q(v,{path:`/pane/context`,element:q(qm,{budget:f??null,columns:d,onDismiss:ie??(()=>{}),onViewDetails:A??(()=>{})})}),q(v,{path:`/pane/context/detail`,element:q(Qm,{ctxStore:p,columns:d,onBack:ae??(()=>{})})})]}),m&&q(v,{path:`/overlay/toast`,inStack:!0,element:q(wm,{toast:m,onDismiss:j})}),!h&&g&&q(v,{path:`/overlay/retry`,inStack:!0,element:q(Th,{item:g})}),!h&&_&&q(v,{path:`/overlay/error-retry`,inStack:!0,element:q(jh,{item:_,rows:y??24,onFocusChange:oe})}),b&&q(v,{path:`/overlay/pause`,inStack:!0,element:q(gh,{item:b})}),x&&q(v,{path:`/overlay/pulse-survey`,inStack:!0,element:q(dm,{item:x,onChange:se})}),S&&q(v,{path:`/overlay/forced-upgrade`,inStack:!0,element:q($m,{message:S,onUpgrade:M,onCancel:N})})]})});function Yh(e){if(e&&typeof e==`object`&&`kind`in e&&e.kind===`input`)return Promise.resolve(null)}function Xh(e){return J(Mt,{children:[q(Zh,{...e}),q(Qh,{...e}),q($h,{...e})]})}function Zh(e){return q(Fp,{...e,routeDerivedOwner:e.routeDerivedOwner})}function Qh(e){return q(kp,{...e,routeDerivedOwner:e.routeDerivedOwner})}function $h(e){let{stdout:t}=Bt(),{stack:n}=g(),r=e=>n.some(t=>t.path===e),{notificationStore:i,taskStore:a,budgetStore:o,proxyStore:s}=Vl(),c=Z(i.store,e=>e.toast),l=Z(i.store,e=>e.retryCountdown),u=Z(i.store,e=>e.errorRetry),d=Z(i.store,e=>e.pauseDialog),f=Z(i.store,e=>e.pulseSurvey),p=Z(a.store,e=>e.subagentContext),m=Z(a.store,e=>e.forcedUpgrade),h=Z(o.store,e=>e.budget),_=Z(s.store,e=>e.view);return q(Jh,{perfOpen:e.perfOpen,perfStore:e.perfStore,cacheStatsOpen:e.cacheStatsOpen,cacheStore:e.cacheStore,proxyOpen:r(`/pane/proxy`),proxyView:_,compactionLogOpen:e.compactionLogOpen,compactionLogEntries:e.compactionLogEntries,galleryOpen:e.galleryOpen,galleryStore:e.galleryStore,columns:e.columns,budget:h,contextStore:e.contextStore,toast:r(`/overlay/toast`)?c:null,subagentContext:!!p,retryCountdown:r(`/overlay/retry`)?l:null,errorRetry:r(`/overlay/error-retry`)?u:null,rows:t?.rows??e.rows,pauseDialog:r(`/overlay/pause`)?d:null,pulseSurvey:r(`/overlay/pulse-survey`)?f:null,focusOwner:e.routeDerivedOwner,forcedUpgrade:r(`/overlay/forced-upgrade`)?m:null})}function eg(e){let{taskStore:t,budgetStore:n,perfStore:r,notificationStore:i}=Vl(),a=Z(r.store,e=>e.indicatorLevel),o=Z(t.store,e=>e.modelName),s=Z(n.store,e=>e.budget),c=Z(t.store,e=>e.backgroundTasks),l=Z(t.store,e=>e.scheduleTasks),u=Z(t.store,e=>e.queued),d=Z(i.store,e=>e.notifications),f=Z(i.store,e=>e.paused),p=Z(i.store,e=>e.pausePending);return q(Om,{columns:e.columns,footerVisible:e.footerVisible,perfIndicatorLevel:a,perfIndicatorUsedPct:e.perfIndicatorUsedPct,modelName:o,budget:s,badgeEntries:e.badgeEntries,fullScreenPaneActive:e.fullScreenPaneActive,backgroundTasks:c,scheduleEnabledCount:l.filter(e=>e.enabled).length,agentProcessing:e.agentProcessing,queuedItems:u,notifications:d,language:e.language,welcome:e.welcome,messages:e.messages,hasHistory:e.hasHistory,paused:f,pausePending:p,shadow:e.shadow})}function tg(e){let t=df({showHome:!!e.showHome,agentProcessing:!!e.agentProcessing,hasTip:!!e.idleTip});return t<=0?null:q(Y,{flexDirection:`column`,height:t,overflow:`hidden`,flexShrink:0,children:e.idleTip?q(hm,{tip:e.idleTip}):null})}function ng(e){return J(Mt,{children:[q(Xh,{...e,routeDerivedOwner:e.routeDerivedOwner}),q(tg,{...e}),J(Y,{ref:e.inputChromeRef,flexDirection:`column`,flexShrink:0,children:[q(Qd,{fullScreenPaneActive:e.fullScreenPaneActive,taskPaneRendered:e.taskPaneRendered,tipVisible:!!e.idleTip,tasksCollapsed:e.tasksCollapsed,taskSelIndex:e.taskSelIndex,setTaskSelIndex:e.setTaskSelIndex,backgroundTasksOrdered:e.backgroundTasksOrdered,columns:e.columns,openEditedFileFull:e.openEditedFileFull,editedFileFullIndex:e.editedFileFullIndex,subagents:e.subagents}),q(ff,{...e}),q(eg,{...e})]})]})}function rg(e){let t=Hl(),n=V.useRef(null),r=It(n),i=r.hasMeasured?Math.max(1,Math.ceil(r.height)):15,a=Math.max(1,e.rows-1),o=Math.max(1,a-i);return q(ia,{value:e.scrollStore,children:J(Y,{flexDirection:`column`,width:e.columns,height:a,position:`relative`,overflow:`hidden`,children:[q(Y,{flexGrow:1,flexShrink:1,flexDirection:`column`,overflow:`hidden`,justifyContent:`flex-end`,children:q(wd,{...e,rows:o})}),q(Y,{flexShrink:0,flexDirection:`column`,children:q(ng,{...e,routeDerivedOwner:t,inputChromeRef:n})})]})})}const ig=V.memo(function({columns:e=80,rows:t=24,registerWrite:n,maxPreviewRows:r,hasHistory:i=!1,messages:a=[],windowMode:o=!1,scrollbackMode:s=!1,shadow:c=!1,scrollStore:l,loadHistory:u,messageStore:d,language:f,cost:p,pluginInput:m,readFileContent:h,resolveWholeFileDiff:_,getTurnMessages:v,initialHistory:y,externalHistoryCommands:b,residencyGovernor:x,welcome:S,contextStore:C,budgetStore:w,notificationStore:T,perfStore:E,cacheStore:D,proxyStore:O,compactionLogStore:ee,galleryStore:te,streamStore:ne,taskStore:k,registryRef:re,shellBackendRef:ie,shellExecution:A=null,a2uiButtons:ae,keybindingOverrides:oe}){let{write:se}=Bt(),M=ql();U(()=>{n?.(se)},[se,n]);let{taskStore:N,budgetStore:ce,perfStore:P,cacheStore:le,proxyStore:ue,compactionLogStore:de,galleryStore:fe,streamStore:pe}=ju({taskStore:k,budgetStore:w,perfStore:E,cacheStore:D,proxyStore:O,compactionLogStore:ee,galleryStore:te,streamStore:ne}),me=Z(N.store,e=>e.tasks),he=Z(N.store,e=>e.pendingEcho),F=Z(N.store,e=>e.pendingSteers),ge=Z(N.store,e=>e.editedFiles),_e=Z(N.store,e=>e.backgroundTasks),ve=Z(N.store,e=>e.subagentsAccum),ye=Z(N.store,e=>e.scheduleTasks),be=Z(N.store,e=>e.clipboardText),xe=Z(N.store,e=>e.drafts),Se=Z(N.store,e=>e.queued),Ce=Z(N.store,e=>e.pendingPermission),we=Z(N.store,e=>e.backgroundOutput),I=Z(N.store,e=>e.subagentContext),L=Z(N.store,e=>e.forcedUpgrade),Te=Z(N.store,e=>e.modelName),Ee=Z(N.store,e=>e.pluginStatusItems),De=Z(N.store,e=>e.statusWidgets),Oe=Z(N.store,e=>e.needsSetup),ke=Z(N.store,e=>e.permissionMode),Ae=W(()=>mo(_e),[_e]),{editedFileFullIndex:je,openEditedFileFull:Me,closeEditedFileFull:Ne,taskDetailTurn:Pe,openTaskDetail:Fe,closeTaskDetail:Ie,shellFullOutput:Le,setShellFullOutput:Re,queueEditIndex:ze,setQueueEditIndex:Be,queueCloseConfirm:Ve,setQueueCloseConfirm:He,queueEscSuppress:Ue,setQueueEscSuppress:We,interruptConfirm:Ge,setInterruptConfirm:Ke,popQueuedConfirm:qe,setPopQueuedConfirm:Je,fullScreenPaneActive:Ye}=Jl({editedFilesLength:ge.length,queuedItemsLength:Se.length,subagentContext:I,backgroundOutput:we}),[Xe,Ze]=K(0),[Qe,$e]=K(!1),{sigilState:et,setSigilState:tt,sigilApplyRef:nt,hadSigilFocusRef:rt,chipContentViewerRequest:it,pasteContent:at,handleSigilTrigger:ot,handleHistorySearch:st,handleChipReopen:ct,handleChipViewPaste:lt,handleSigilClose:R,handlePasteConfirmRequest:ut,handlePasteConfirm:z,handlePasteCancel:dt}=mu(),ft=G(null),pt=G(null),mt=At(e=>{let t=Math.max(0,Math.min(e,xe.length-1)),n=xe[t];n&&(ft.current?.fill(n.text),M.onDraftDelete?.(t)),M.onToggleDraftPane?.()},[xe,M.onToggleDraftPane,M.onDraftDelete]),ht=G(null),gt=re??ht,_t=Z(P.store,e=>e.indicatorLevel),vt=Z(P.store,e=>e.memory?.usedPct),yt=Z(ue.store,e=>e.view),bt=Z(de.store,e=>e.entries),{stack:xt,currentPath:St}=g(),Ct=e=>xt.some(t=>t.path===e),wt=Ct(`/pane/perf`),Tt=Ct(`/pane/cache`),Et=St.startsWith(`/pane/compaction-log`),Dt=Ct(`/pane/gallery`),Ot=l??V.useMemo(()=>ta(),[]),kt=T??V.useMemo(()=>jl(),[]),H=Z(kt.store,e=>e.providerUsage),jt=d??V.useMemo(()=>Fl(),[]),Mt=C??V.useMemo(()=>Rl(),[]),J=V.useMemo(()=>({taskStore:N,budgetStore:ce,perfStore:P,cacheStore:le,proxyStore:ue,compactionLogStore:de,galleryStore:fe,streamStore:pe,notificationStore:kt,contextStore:Mt,messageStore:jt,scrollStore:Ot}),[N,ce,P,le,ue,de,fe,pe,kt,Mt,jt,Ot]),Nt=Z(Ot.store,e=>e.offset),Y=Z(Ot.store,e=>e.totalLines>0),[Pt,X]=V.useState(!1),[Ft,It]=V.useState(!1),Lt=V.useRef(!1),Rt=V.useCallback(()=>{Lt.current||Ft||!u||!d||(Lt.current=!0,X(!0),u({limit:500}).then(e=>{e&&e.length>0?d.prependMany(e):It(!0)}).catch(()=>It(!0)).finally(()=>{Lt.current=!1,X(!1)}))},[Ft,u,d]),zt=V.useCallback(e=>{Ot.scrollBy(e)},[Ot]),[Vt,Ht]=V.useState(!1),[Ut,Wt]=V.useState(``),[Gt,Kt]=V.useState(-1),[qt,Jt]=V.useState(0),Yt=V.useCallback(e=>Jt(e),[]),Xt=V.useCallback(e=>Ot.setOffset(e),[Ot]),Zt=St===`/`&&!L&&!Ve&&!Ge&&!qe;j(`repl-scroll`,(e,n)=>{if(!Y)return!1;if(n.pageUp)return Ot.page(1,t),!0;if(n.pageDown)return Ot.page(-1,t),!0;if((n.upArrow||n.downArrow)&&(n.alt||n.meta))return Ot.scrollBy(n.upArrow?1:-1),!0;if(Nt===0)return!1;if(Vt){if(n.escape)return Ht(!1),Wt(``),Kt(-1),!0;if(n.return)return Ht(!1),Wt(``),Kt(-1),Ot.toBottom(),!0;if(n.backspace)return Wt(e=>e.slice(0,-1)),Kt(-1),!0;if((e===`n`||e===`N`)&&Ut.length>0){let t=e===`n`?1:-1;return Kt(e=>qt>0?(e+t+qt)%qt:-1),!0}return e.length===1?(Wt(t=>t+e),Kt(-1),!0):!0}if(e===`/`)return Ht(!0),Wt(``),Kt(-1),!0;if(n.upArrow)return Ot.scrollBy(1),!0;if(n.downArrow)return Ot.scrollBy(-1),!0;if(e===`g`)return Ot.toTop(),!0;if(e===`G`||n.escape||n.return)return Ot.toBottom(),!0;if(e.length>0){Ot.toBottom();let t=ft.current;return t?.append?t.append(e):t?.fill(e),!0}return!1},{isActive:Zt});let Qt=Ct(`/pane/edited-files`),$t=Ct(`/pane/subagents`),en=Ct(`/pane/schedule`),tn=Ct(`/pane/draft`),nn=Ct(`/pane/queue`),rn=At(()=>{He(!0)},[]),an=At(()=>{Ke(!0)},[]),on=At(()=>{Je(!0)},[]),sn=St.startsWith(`/pane/context/detail`),cn=Z(pe.store,e=>e.processing),ln=Z(ce.store,e=>e.budget),{footerVisible:un,badgeEntries:dn}=lu({columns:e,permissionMode:ke,cost:p,providerUsage:H,pluginStatusItems:Ee,statusWidgets:De,modelName:Te}),fn=W(()=>[...ve.values()],[ve]),pn=Hl(),mn=Ct(`/home`)&&!St.startsWith(`/dialog/`);U(()=>{M.onFocusOwnerChange?.(pn)},[pn,M.onFocusOwnerChange]),U(()=>{M.onScrollActiveChange?.(Zt)},[Zt,M.onScrollActiveChange]);let hn=Pe==null&&!Ye&&!I&&me.length>0;hu({sigilState:et,setSigilState:tt,sigilApplyRef:nt,hadSigilFocusRef:rt,focusOwner:pn,preempted:!!Ce});let gn=uu({shellExecution:A,subagentContext:I,agentProcessing:cn,queuedItems:Se,pendingEcho:he,pendingSteers:F,onRequestInterruptConfirm:an,onRequestPopQueuedConfirm:on});return eu({scrollOffset:Nt,showHome:mn,tasksLength:me.length,backgroundTasksLength:_e.length,editedFilesLength:ge.length,subagentsLength:fn.length,scheduleTasksLength:ye.length,scheduleOpen:en,draftsLength:xe.length,draftOpen:tn,queuedItemsLength:Se.length,queueOpen:nn,clipboardHasContent:be.length>0,shellExecutionRunning:A?.status===`running`,pendingEcho:he,pasteContent:at,forcedUpgrade:L,queueCloseConfirm:Ve,interruptConfirm:Ge,popQueuedConfirm:qe,routeDerivedOwner:pn,currentPath:St,backgroundOutput:we,a2uiButtons:ae,editedFilesOpen:Qt,subagentsOpen:$t,tasksCollapsed:Qe,setTasksCollapsed:$e,keybindingOverrides:oe}),q(Bl,{value:J,children:q(rg,{columns:e,rows:t,welcome:S,idleTip:Nu({active:St===`/`&&!L&&!cn&&!Oe,resetKey:`${St}|${cn?1:0}`,isZh:B.language?.startsWith(`zh`)??!1}),showHome:mn,messages:a,hasHistory:i,maxPreviewRows:r,windowMode:o,scrollbackMode:s,shadow:c,keybindingOverrides:oe,scrollStore:Ot,loadHistory:u,messageStore:d,earlierLoading:Pt,earlierEnded:Ft,onNeedEarlier:Rt,onPrepend:zt,findQuery:Vt?Ut:void 0,findActiveMatch:Gt,onFindNavigateTo:Xt,onFindCountChange:Yt,fullScreenPaneActive:Ye,streamStore:pe,pasteContent:at,handlePasteConfirm:z,handlePasteCancel:dt,queueCloseConfirm:Ve,queueEscSuppress:Ue,setQueueEscSuppress:We,setQueueCloseConfirm:He,interruptConfirm:Ge,setInterruptConfirm:Ke,popQueuedConfirm:qe,setPopQueuedConfirm:Je,onQueueEscConfirm:rn,contextDetail:sn,contextStore:C,shellExecution:A,taskDetailTurn:Pe,taskSelIndex:Xe,openTaskDetail:Fe,closeTaskDetail:Ie,tasksCollapsed:Qe,taskPaneRendered:hn,backgroundTasksOrdered:Ae,openEditedFileFull:Me,editedFileFullIndex:je,closeEditedFileFull:Ne,subagents:fn,shellFullOutput:Le,setShellFullOutput:Re,perfOpen:wt,perfStore:P,cacheStatsOpen:Tt,cacheStore:le,proxyView:yt,compactionLogOpen:Et,compactionLogEntries:bt,galleryOpen:Dt,galleryStore:fe,agentProcessing:cn,needsSetup:Oe,handlePromptEscape:gn,handleSigilTrigger:ot,handleSigilClose:R,handleHistorySearch:st,handleChipReopen:ct,handleChipViewPaste:lt,handlePasteConfirmRequest:ut,pluginInput:m,historyInsertRef:ft,pasteBridgeRef:pt,initialHistory:y,externalHistoryCommands:b,residencyGovernor:x,registryRef:gt,shellBackendRef:ie,sigilState:et,setSigilState:tt,sigilApplyRef:nt,readFileContent:h,handleDraftLoad:mt,queueEditIndex:ze,setQueueEditIndex:Be,footerVisible:un,perfIndicatorLevel:_t,perfIndicatorUsedPct:vt,modelName:Te,budget:ln,badgeEntries:dn,language:f,getTurnMessages:v,resolveWholeFileDiff:_,setTaskSelIndex:Ze,chipContentViewerRequest:it,cost:p,statusWidgets:De,pluginStatusItems:Ee})})}),ag=V.memo(function(e){let t=W(()=>Wl(e),[]);return St(e.language??Ct()),q(Vt,{i18n:B,children:q(ue,{systemTheme:e.systemTheme,themeRegistry:e.themeRegistry,presetSelection:e.presetSelection,children:q(Kl,{value:t,children:q(_e,{children:q(w,{initialPath:e.initialPath??`/home`,children:q(ig,{...e})})})})})})}),og=kt(null);function sg(){let e=jt(og);if(!e)throw Error(`useTabScope() must be used inside <TabScope>`);return e}function cg({scopeId:e,children:t}){let n=W(()=>new r,[]),[i,a]=K(null),o=G(null);o.current=i;let s=At((t,r)=>{le(n,o.current,r)||m(n,o.current,e,a,r)},[n,e]);Lt((e,t)=>{s(e,t)}),U(()=>{let t=n.getInitialFocus(e);t&&!o.current&&a(t)},[e,n]);let c=W(()=>({routePath:e,currentPath:e,activeId:i,registry:n,hasRouter:!1}),[e,i,n]),l=W(()=>({activeId:i,registry:n}),[i,n]);return q(og.Provider,{value:l,children:q(te.Provider,{value:c,children:t})})}const lg=globalThis;lg.React=V,lg.__ottoPanelInk=Nt,lg.__ottoPanelTui={Segmented:Dd,Tabs:Dd,DataList:Ye,Button:I,GroupDivider:xe,ScrollIndicatorAbove:ne,ScrollIndicatorBelow:f,Tabable:Be,useTabable:Re,TabScope:cg},lg.__ottoPanelFocusBridge={claim:()=>{},release:()=>{},usePanelFocusClaimed:ep,requestClose:()=>$f.requestClose(),setHint:e=>$f.setHint(e)},lg.__ottoPanelTheme={getTheme:()=>L,getFigures:()=>R},lg.__ottoPanelSpacing={SPACING:F,LAYOUT:fe},lg.__ottoPanelI18n={t:xt,i18next:B};function ug(e,t){let n={current:[]};return{a2uiButtonsRef:n,a2uiActionRef:{current:t},scanA2uiButtons:()=>{let t=[],r=0;for(let n of e.messageStore.getState().messages){let e=n.content;if(Array.isArray(e)){for(let n of e)if(n.type===`a2ui`){let e=bs(n.components,80,r);for(let n of e.buttons){if(r++,r>9)break;t.push({...n,key:String(r)})}let i=ws(n.components);for(let e of i){if(r++,r>9)break;t.push({...e,key:String(r)})}}if(r>=9)break}}n.current=t}}}function dg(e){let t=rl(),n=t.store,r=jl(),i=r.store,a=Cu({modelName:e.modelName,needsSetup:e.needsSetup,commands:e.commands,permissionMode:e.permissionMode,drafts:e.initialDrafts,recentMentions:e.initialRecentMentions}),o=a.store,s=Fl(),c=s.store,l=ta(),u=l.store,d=gu(),f=Rl(),p=wu(),m=Tu(),h=Du(),g=Ou(),_=Au(),v=zi(),y=v?new Wi(v):null,b={current:y},{a2uiButtonsRef:x,a2uiActionRef:S,scanA2uiButtons:C}=ug({messageStore:c},e.onA2uiAction);return{streamStoreHandle:t,streamStore:n,notificationStoreHandle:r,notificationStore:i,taskStoreHandle:a,taskStore:o,messageStoreHandle:s,messageStore:c,scrollStoreHandle:l,scrollStore:u,budgetStore:d,contextStore:f,perfStore:p,cacheStore:m,proxyStore:h,compactionLogStore:g,galleryStore:_,completer:y,shellBackendRef:b,a2uiButtonsRef:x,a2uiActionRef:S,scanA2uiButtons:C}}function fg({paneOwnsViewport:e,realWrite:t}){let n=[];return{write:r=>{if(r.includes(`\x1B[2J`)){n=[],t(r);return}if(e()){n.push(r);return}t(r)},flush:()=>{if(n.length===0)return;let e=n.join(``);n=[],t(e)},pending:()=>n.length}}function pg(e){if(e<=0)return`\x1B[2K\r`;let t=`\x1B[2K\r`;for(let n=0;n<e;n++)t+=`\x1B[1A\x1B[2K`;return t}function mg(e){let t=!1,n=t=>{if(e.isTTY)try{e.write(t)}catch{}};return{enter(){t||(t=!0,n(`\x1B[?1049h`))},exit(){t&&(t=!1,n(`\x1B[?1049l`))},active(){return t}}}async function hg(e){let t;try{let e=await import(Dt(import.meta.url).resolve(`ink`).replace(/index\.js$/,`log-update.js`));if(!e.default||typeof e.default.create!=`function`)return null;t=e.default}catch{return null}let n,r=t.create;return t.create=(t,i)=>{let a=r(t,i),o=(t=>e(t)?a(t):!0);for(let e of Object.keys(a)){let t=a[e];o[e]=typeof t==`function`?t.bind(a):t}let s=a.setCursorPosition;return o.setCursorPosition=e=>{n=e,s?.call(a,e)},o},{dispose(){t.create=r},cursorIntent:()=>n}}const gg=new Set(`+.-.|.←.↑.→.↓.↖.↗.↘.↙.─.━.│.┃.┌.┏.┐.┓.└.┗.┘.┛.═.║.╒.╓.╔.╕.╖.╗.╘.╙.╚.╛.╜.╝.╭.╮.╯.╰.▶.●.○.⋮`.split(`.`));function _g(e){if(e.length===0)return!1;let t=!1;for(let n of e)if(n.width!==0&&!(n.ch===` `||n.ch===``)){if(!gg.has(n.ch))return!1;t=!0}return t}const vg=`\x1B[27m`;function yg(e){return e===void 0||!Number.isFinite(e)?200:Math.max(200,Math.ceil(e*2.5))}const bg=/\x1b\[[0-9;]*m/y;var xg=class{minAnimationPeriod;constructor(e={}){this.minAnimationPeriod=e.minAnimationPeriod??(()=>We.minPeriodMs())}burstQuietMs(){return yg(this.minAnimationPeriod())}rows=[];selectionQuery;chromeWidths=null;damageTop=null;damageBottom=null;get height(){return this.rows.length}lineAt(e){return this.rows[e]}takeDamage(){if(this.damageTop===null||this.damageBottom===null)return null;let e={top:this.damageTop,bottom:this.damageBottom};return this.damageTop=null,this.damageBottom=null,e}markDirty(e){(this.damageTop===null||e<this.damageTop)&&(this.damageTop=e),(this.damageBottom===null||e>this.damageBottom)&&(this.damageBottom=e)}ingest(e){let t=e.split(`
93
+ `),n=e.endsWith(`
94
+ `)?t.slice(0,-1):t;if(n.length<this.rows.length){for(let e=n.length;e<this.rows.length;e++)this.markDirty(e);this.rows.length=n.length}for(let e=0;e<n.length;e++){let t=Cg(n[e]??``),r=Cg._lastChromeWidth??0;(r>0||this.chromeWidths)&&(this.chromeWidths||=new Int32Array(Math.max(n.length,this.rows.length)),e<this.chromeWidths.length&&(this.chromeWidths[e]=r)),!r&&_g(t)&&(this.chromeWidths||=new Int32Array(Math.max(n.length,this.rows.length)),e<this.chromeWidths.length&&(this.chromeWidths[e]=t.length));let i=this.rows[e];i&&Sg(i,t)||(this.rows[e]=t,this.markDirty(e))}}prevLineCount=0;prevCursor;cursorShown=!1;lastRedrawAt=0;cursorRow(){return this.prevCursor?this.prevCursor.y:Math.max(0,this.prevLineCount-1)}bookkeeping(){return{prevLineCount:this.prevLineCount,prevCursor:this.prevCursor,cursorShown:this.cursorShown}}buildCursorOnlySequence(e,t=Date.now()){let n=e===void 0&&this.prevCursor===void 0||e!==void 0&&this.prevCursor!==void 0&&e.x===this.prevCursor.x&&e.y===this.prevCursor.y,r=e!==void 0&&!this.cursorShown&&t-this.lastRedrawAt>=this.burstQuietMs();return n&&!r?``:this.buildFlushSequence({top:0,bottom:-1},e,t)}buildFlushSequence(e,t,n=Date.now()){let r=Math.max(this.rows.length,1),i=Math.max(r,this.prevLineCount),a=i-1,o=r-1,s=``;if(this.prevCursor){s+=`\x1B[?25l`;let e=Math.max(0,this.prevLineCount-1)-this.prevCursor.y;e>0&&(s+=`[${e}B`),s+=`\r`}else s+=`\x1B[?25l`;if(e.bottom>=e.top){let t=Math.max(0,this.prevLineCount-1)-e.top;t>0?s+=`[${t}A`:t<0&&(s+=`[${-t}B`),s+=`\r`;let n=Math.min(e.bottom,a);for(let t=e.top;t<=n;t++)s+=`\x1B[2K`,t<this.rows.length&&(s+=this.renderLine(t)),t<n&&(s+=`
95
+ \r`);let r=o-n;r>0?s+=`[${r}B`:r<0&&(s+=`[${-r}A`),s+=`\r`}let c=e.bottom>=e.top&&n-this.lastRedrawAt<this.burstQuietMs();e.bottom>=e.top&&(this.lastRedrawAt=n);let l=t!==void 0&&this.prevCursor!==void 0&&t.x===this.prevCursor.x&&t.y===this.prevCursor.y,u=e.bottom>=e.top&&t!==void 0&&t.y>=e.top&&t.y<=e.bottom;if(l&&!u&&e.bottom>=e.top){let n=`\x1B7`,a=t.y-e.top;a>0?n+=`[${a}A`:a<0&&(n+=`[${-a}B`),n+=`\r`;let o=Math.min(e.bottom,i-1);for(let t=e.top;t<=o;t++)n+=`\x1B[2K`,t<this.rows.length&&(n+=this.renderLine(t)),t<o&&(n+=`
96
+ \r`);return n+=`\x1B8`,this.prevLineCount=r,n}if(t){let e=o-Math.max(0,Math.min(t.y,o));e>0&&(s+=`[${e}A`),t.x>0?s+=`[${t.x+1}G`:s+=`\r`,c||(s+=`\x1B[?25h`)}return this.prevLineCount=r,this.prevCursor=t?{...t}:void 0,this.cursorShown=t!==void 0&&!c,s}renderLine(e){let t=this.rows[e];if(!t)return``;let n=this.selectionQuery,r=``,i=``,a=!1;for(let o=0;o<t.length;o++){let s=t[o];if(s.width===0)continue;s.style!==i&&(i&&(r+=`\x1B[0m`),r+=s.style,i=s.style,a=!1);let c=n?.(e,o)??!1;c!==a&&(r+=c?`\x1B[7m`:vg,a=c),r+=s.ch}return a&&(r+=vg),i&&(r+=`\x1B[0m`),r}setChromeWidths(e){if(!e||e.length===0){this.chromeWidths=null;return}this.chromeWidths=Int32Array.from(e)}chromeWidth(e){return!this.chromeWidths||e<0||e>=this.chromeWidths.length?0:this.chromeWidths[e]}setSelectionQuery(e){this.selectionQuery=e??void 0}buildSelectionRepaint(e,t){let n=Math.max(0,Math.min(e,t)),r=Math.min(this.rows.length-1,Math.max(e,t));if(r<n||this.rows.length===0)return``;let i=this.cursorRow(),a=`\x1B7`,o=i-n;o>0?a+=`[${o}A`:o<0&&(a+=`[${-o}B`),a+=`\r`;for(let e=n;e<=r;e++)a+=`${this.renderLine(e)}`,e<r&&(a+=`
97
+ \r`);return a+=`\x1B8`,a}markRowDirty(e){e>=0&&e<this.rows.length&&this.markDirty(e)}markAllDirty(){for(let e=0;e<this.rows.length;e++)this.markDirty(e)}};function Sg(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r.ch!==i.ch||r.style!==i.style||r.width!==i.width)return!1}return!0}function Cg(e){let t=[],n=``,r=0,i=0,a=/^\x1b\]9;cw=(\d+)\x07/.exec(e);for(a&&(i=parseInt(a[1],10),r=a[0].length),Cg._lastChromeWidth=i;r<e.length;){if(e.charCodeAt(r)===27){bg.lastIndex=r;let t=bg.exec(e);if(t){let e=t[0];n=/\x1b\[0?m/.test(e)?``:n+e,r=bg.lastIndex;continue}r++;continue}let i=String.fromCodePoint(e.codePointAt(r));r+=i.length,Ge(i)===2?(t.push({ch:i,style:n,width:2}),t.push({ch:``,style:n,width:0})):t.push({ch:i,style:n,width:1})}return t}function wg(e=process.env){return e.OTTO_TUI_CELL_BUFFER!==`0`}async function Tg(e,t=process.env){if(!wg(t)||!e.isTTY)return null;let n=new xg,r=0,i=0,a=null,o,s=()=>{a&&clearTimeout(a),a=setTimeout(()=>{if(a=null,o)try{let t=n.buildCursorOnlySequence(o);t&&e.write(t)}catch{}},210),a.unref?.()},c=null,l=null;return c=await hg(t=>{r++,n.ingest(t);let a=n.takeDamage();l?.(a);let u=c?.cursorIntent();if(o=u,!a)return i++,u&&e.write(n.buildCursorOnlySequence(u)),!1;try{e.write(n.buildFlushSequence(a,u)),s()}catch{return!0}return!1}),c?{buffer:n,dispose:()=>{a&&clearTimeout(a),l=null,c.dispose()},stats:()=>({frames:r,skipped:i}),onDamage:e=>{l=e}}:null}function Eg({anchor:e,focus:t}){return t.row<e.row||t.row===e.row&&t.col<e.col?{start:t,end:e}:{start:e,end:t}}function Dg(e){return e.anchor.row===e.focus.row&&e.anchor.col===e.focus.col}function Og(e,t,n,r){return!(t<e.start.row||t>e.end.row||r?.(t,n)||t===e.start.row&&n<e.start.col||t===e.end.row&&n>=e.end.col)}function kg(e,t,n){if(!n)return 0;for(let r=0;r<e.length;r++)if(!n(t,r))return r;return e.length}function Ag({selection:e,lineAt:t,noSelect:n}){if(Dg(e))return``;let r=Eg(e),i=[];for(let e=r.start.row;e<=r.end.row;e++){let a=t(e);if(!a||kg(a,e,n)>=a.length)continue;let o=``;for(let t=0;t<a.length;t++){let i=a[t];i.width!==0&&Og(r,e,t,n)&&(o+=i.ch)}i.push(o.replace(/\s+$/,``))}return i.join(`
98
+ `)}var jg=class{range=null;dragging=!1;begin(e){this.range={anchor:e,focus:e},this.dragging=!0}extend(e){!this.dragging||!this.range||(this.range={anchor:this.range.anchor,focus:e})}commit(){this.dragging=!1}clear(){this.range=null,this.dragging=!1}current(){return!this.range||Dg(this.range)?null:this.range}isDragging(){return this.dragging}};function Mg(e){let{buffer:t,terminalRows:n,writeSelectionRepaint:r,writeClipboard:i,onCopied:a}=e,o=e.noSelect??((e,n)=>n<t.chromeWidth(e)),s=(e,r)=>{let i=Math.max(0,r-1),a=Math.max(0,n()-t.height);return{row:Math.max(0,i-a),col:Math.max(0,e-1)}},c=new jg,l=null,u=()=>{let e=c.current(),n=null;if(!e)t.setSelectionQuery(null);else{let r=Eg(e);t.setSelectionQuery((e,t)=>Og(r,e,t,o)),n={top:r.start.row,bottom:r.end.row}}let i=Math.min(n?.top??1/0,l?.top??1/0),a=Math.max(n?.bottom??-1,l?.bottom??-1);l=n,!(a<i)&&r(t.buildSelectionRepaint(i,a))},d=({clearAfter:e})=>{let n=c.current();if(!n)return!1;let r=Ag({selection:n,lineAt:e=>t.lineAt(e),noSelect:o});if(r.length===0)return!1;let s=i(r);return a?.(r,s),e&&(c.clear(),u()),s};return{handleDrag(e){let t=s(e.x,e.y);switch(e.type){case`down`:c.begin(t),u();break;case`move`:if(!c.isDragging())return;c.extend(t),u();break;case`up`:c.extend(s(e.x,e.y)),c.commit(),u(),d({clearAfter:!1});break}},copySelection(){return d({clearAfter:!0})},onFrameDamage(e){if(!e)return!1;let t=c.current();if(!t||c.isDragging())return!1;let{start:n,end:r}=Eg(t);return e.bottom<n.row||e.top>r.row?!1:(c.clear(),u(),!0)},clear(){!c.current()&&!c.isDragging()||(c.clear(),u())},hasSelection(){return c.current()!==null}}}function Ng(e){return Array.from(e).length}const Pg=`\x1B[?1006h\x1B[?1002h`,Fg=`\x1B[?1002l\x1B[?1006l`;function Ig(e,t){let n=t;if(e[n]!==27||e[n+1]!==91||e[n+2]!==60)return null;if(n+=3,n>=e.length)return`pending`;let r=[],i=0,a=!1;for(;n<e.length;n++){let t=e[n];if(t>=48&&t<=57)i=i*10+(t-48),a=!0;else if(t===59){if(!a)return null;r.push(i),i=0,a=!1}else if(t===77||t===109)return!a||(r.push(i),r.length<3)?null:{b:r[0],x:r[1],y:r[2],final:t,end:n+1};else return null}return a||r.length>0?`pending`:null}function Lg(){let e=Buffer.alloc(0),t=!1;return n=>{let r=N(n),i=e.length?Buffer.concat([e,r]):r;e=Buffer.alloc(0);let a=[],o=[],s=[],c=0;return c=((n,r)=>{let s=n;for(;s<i.length;){if(t){let e=i.indexOf(`\x1B[201~`,s);if(e===-1){r.push(...i.subarray(s)),s=i.length;break}r.push(...i.subarray(s,e+6)),s=e+6,t=!1;continue}let n=i.indexOf(`\x1B[200~`,s),c=i[s]===27&&i[s+1]===91&&i[s+2]===60?s:-1;if(n!==-1&&(c===-1||n<c)){r.push(...i.subarray(s,n+6)),s=n+6,t=!0;continue}if(c!==-1){let t=Ig(i,c);if(t===`pending`)return e=Buffer.from(i.subarray(c)),s;if(t!==null){let{b:e,x:n,y:l,final:u}=t,d=t=>e===t||e===t+8||e===t+16;if(u===77&&(d(64)||d(65))){let r=d(64)?64:65;a.push({kind:`wheel`,delta:r===64?1:-1,x:n,y:l,shift:!!(e&4),ctrl:!!(e&16)}),s=t.end;continue}let f=!!(e&4),p=e&-29,m=u===77&&p===0,h=u===77&&p===32;if(!f&&(m||h||u===109)){o.push({kind:`drag`,type:m?`down`:h?`move`:`up`,x:n,y:l,ctrl:!!(e&16)}),s=t.end;continue}if(f){for(let e=c;e<t.end;e++)r.push(i[e]);s=t.end;continue}s=t.end;continue}r.push(i[s]),s++;continue}r.push(i[s]),s++}return s})(c,s),{wheels:a,drags:o,rest:Buffer.from(s)}}}function Rg(e,t=16){let n=0,r=null,i=()=>{if(r!==null&&(clearTimeout(r),r=null),n!==0){let t=n;n=0,e(t)}};return{push(e){n+=e,r===null&&(r=setTimeout(i,t))},flushNow:i}}function zg(e=process.platform,t=process.env){if(e===`darwin`)return{command:`pbcopy`,args:[]};if(e===`win32`)return{command:`powershell`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,`$input | Set-Clipboard`]};if(e===`linux`){if(t.WSL_DISTRO_NAME||t.WSLENV)return{command:`powershell.exe`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,`$input | Set-Clipboard`]};if(t.WAYLAND_DISPLAY)return{command:`wl-copy`,args:[]};if(t.DISPLAY)return{command:`xclip`,args:[`-selection`,`clipboard`]}}return null}function Bg(e,t=process.platform,n=process.env){let r=zg(t,n);if(!r)return!1;try{let t=fn(r.command,r.args,{stdio:[`pipe`,`ignore`,`ignore`],detached:!1});return t.on(`error`,()=>{}),t.stdin.on(`error`,()=>{}),t.stdin.end(e,`utf8`),!0}catch{return!1}}const Vg=`\x1B[<u`,Hg=/\x1b\[(\d+)(?:;(\d+))?u/g;function Ug(e,t){let n=t>0?t-1:0,r=!!(n&1),i=!!(n&2),a=!!(n&4),o=!!(n&8),s=i||o?`\x1B`:``;if(e===13)return a||i||o||r?`\x1B\r`:`\r`;if(e===9)return s+` `;if(e===27)return`\x1B`;if(e===127||e===8)return s+``;if(e>=65&&e<=90||e>=97&&e<=122){let t=e>=65&&e<=90?e+32:e;return a?s+String.fromCharCode(t&31):s+String.fromCharCode(r?t-32:t)}return e>=32?a?``:s+String.fromCodePoint(e):``}function Wg(e){let t=e.lastIndexOf(`\x1B`);if(t<0)return-1;let n=e.slice(t);return/^\x1b\[[\d;:]*[A-Za-z~]/.test(n)||/^\x1b[NO]./.test(n)||/^\x1b[^[NO]/.test(n)&&n.length>=2?-1:t}function Gg(){let e=``;return t=>{let n=e+(typeof t==`string`?t:t.toString(`latin1`));e=``;let r=Wg(n);r>=0&&(e=n.slice(r),n=n.slice(0,r));let i=n.replace(Hg,(e,t,n)=>Ug(parseInt(t,10),n?parseInt(n,10):1));return Buffer.from(i,`latin1`)}}function Kg(e){let{stdin:t,renderStdout:n,kittyOn:r,kittyExitHandler:i,focusOn:a,focusExitHandler:o,mouseOn:s,mouseExitHandler:c,onInterrupt:l,terminalInputCleanup:u}=e,d=!1,f=e=>{let t=N(e);t.length>=1&&t[0]===3&&l?.()},p=()=>l?.();return{setupRawInput:()=>{try{t.isTTY&&(t.on(`data`,f),d=!0)}catch{}process.on(`SIGINT`,p)},cleanup:()=>{if(r){try{n.write(Vg)}catch{}i&&process.removeListener(`exit`,i)}if(a&&o&&process.removeListener(`exit`,o),s){try{n.write(Fg)}catch{}c&&process.removeListener(`exit`,c)}d&&t.removeListener(`data`,f),process.removeListener(`SIGINT`,p),u();try{t.isTTY&&t.pause()}catch{}try{t.isTTY&&t.setRawMode(!1)}catch{}}}}const qg=/\x1b\[[0-9;]*m/g;function Jg(e){let t=``,n=0,r=0,i=!1,a=()=>Math.max(1,e.getColumns()-fe.borderInset),o=t=>{if(t.length===0)return;e.setHasHistory(!0);let n=!i,r=t.map((e,t)=>n&&t===0?`${Q(R.bullet,L.replyPrefix)} ${e}`:e.replace(qg,``).trim()===``?``:` ${e}`);i=!0,e.scrollbackBuffer.write((n?`
99
+ `:``)+r.join(`
100
+ `)+`
101
+ `)},s=()=>{t=``,n=0,r=0,i=!1,e.streamStore.setState({lastTail:void 0})},c=e=>{let t=Xa(Ts(e),a());if(t.length===0)return;let n=r===0?t:[``,...t];o(n),r+=n.length},l=(e,n)=>{if(n<=e)return;let r=t.slice(e,n);if((r.match(/\n/g)??[]).length+1>60){let e=r.split(`
102
+ `);for(let t=0;t<e.length;t+=60)c(e.slice(t,t+60).join(`
103
+ `));return}c(r)},u=(n,r,i)=>{if(r<=n){i();return}let a=t.slice(n,r);if((a.match(/\n/g)??[]).length+1<=60){c(a),i();return}let o=a.split(`
104
+ `),s=0;c(o.slice(0,60).join(`
105
+ `)),s=60;let l=()=>{if(s>=o.length){i();return}c(o.slice(s,s+60).join(`
106
+ `)),s+=60,e.notify(),setImmediate(l)};setImmediate(l)},d=r=>{if(r===``){u(n,t.length,()=>{s(),e.streamStore.setState({streamingText:``})});return}t=r;let i=Sc(r);i>n&&(l(n,i),n=i);let o=r.slice(n);o!==e.streamStore.getState().lastTail&&e.streamStore.setState({streamingText:o.trim()?Xa(Ts(qc(o)),a()).join(`
107
+ `):``,lastTail:o})},f=t=>{if(e.scrollbackMode){d(t);return}let{chunks:n,tail:r,state:i}=wc(e.streamStore.getState().streamCommit,t);if(n.length>0){let t=n.map(t=>{let n=e.incMsgCounter();return{role:`assistant_stream`,text:t.text,lead:t.lead,id:`s-${n}`}});e.messageStoreHandle.appendMany(t,()=>`s-${e.incMsgCounter()}`)}e.streamStore.setState({streamCommit:i,streamingText:r}),(t===``||n.length>0)&&e.notify()},p=t=>{e.streamStore.setState({streamingThinking:t})};return{applyStreamText:f,applyStreamThinking:p,streamTextCoalescer:Dc(f,e.coalesceMs),streamThinkingCoalescer:Dc(p,e.coalesceMs),outputTokensThrottle:il(e.streamStore,e.coalesceMs),resetController:()=>{t=``,n=0,r=0,i=!1}}}function Yg(e,t){if(e.length===0)return[];let n=Math.max(1,t);return e.map(e=>$s(e,n))}function Xg(e){let t=t=>{let n=Yg(t,e.getColumns()),{text:r,hasHistory:i}=Rc(t.map((e,t)=>({role:e.role??``,lines:n[t]??[]})),e.getHasHistory());return e.setHasHistory(i),r},n=null,r=r=>{let i=t(r);if(i){if(n){n.push(i);return}e.scrollbackBuffer.write(i)}},i=i=>{if(i.length<=60&&!n){r(i);return}if(n){let e=t(i);e&&n.push(e);return}n=[t(i.slice(0,60))];let a=60,o=()=>{if(a>=i.length){let t=(n??[]).join(``);n=null,t&&e.scrollbackBuffer.write(t),e.notify();return}let r=i.slice(a,a+60);a+=60,n?.push(t(r)),setImmediate(o)};setImmediate(o)};return{commitToHistory:e=>i([e]),commitManyToHistory:i}}function Zg(e){let{taskStore:t,notificationStore:n,resolvers:r,flushScrollbackIfIdle:i,paneOwnsViewport:a,setPaneOwnsViewport:o,getRouter:s=M}=e,c=null,l={},u=(e,t)=>{let n=s();n.navigate(`/dialog/plugin-panel`,{state:{panelInfo:e,onClose:()=>{n.goBack(),t?.()}}})};return{openModal:(e=>{switch(e.kind){case`select`:{let t=s();if(e.async){let n=!1;t.navigate(`/dialog/select`,{state:{title:e.title,subtitle:`Probing, please wait…`,options:[],layout:e.layout??`buttons`}}),r.select=e=>{if(e==null){n=!0;return}},(async()=>{try{let i=await e.async;if(n)return;r.select=t=>{t==null?e.onCancel?.():e.onSelect(t)},t.navigate(`/dialog/select`,{replace:!0,state:{title:i.title??e.title,subtitle:i.subtitle??e.subtitle,subtitleTone:e.subtitleTone,options:i.options,maxVisible:e.maxVisible,layout:e.layout,searchable:e.searchable,subtitleActions:e.subtitleActions,detailPlacement:e.detailPlacement,onHighlight:e.onHighlight}})}catch(i){if(n)return;r.select=()=>{},t.navigate(`/dialog/select`,{replace:!0,state:{title:e.title,subtitle:`Error: ${i instanceof Error?i.message:String(i)}`,options:[{label:`Close`,value:`close`,color:`gray`}],layout:`buttons`}})}})();return}process.env.NODE_ENV!==`production`&&t.currentPath===`/dialog/select`&&e.replace!==!0&&console.warn('[openModal] Detected re-entrant openModal({ kind: "select" }) — this pushes a new dialog stack entry instead of replacing the current one. Use the `async` field for loading→content transitions, or close the current dialog before opening a new one. See RFC-285 D2.');let n=e.replace===!0&&t.currentPath===`/dialog/select`;t.navigate(`/dialog/select`,{replace:n,state:{title:e.title,subtitle:e.subtitle,subtitleTone:e.subtitleTone,options:e.options,maxVisible:e.maxVisible,searchable:e.searchable,layout:e.layout,subtitleActions:e.subtitleActions,detailPlacement:e.detailPlacement,initialFilter:e.initialFilter,onFilterChange:e.onFilterChange,onHighlight:e.onHighlight,defaultSelectedValue:e.defaultSelectedValue}}),r.select=t=>{t==null?e.onCancel?.():e.onSelect(t)};return}case`extensionDetail`:{let t=s(),n=()=>{t.goBack()};t.navigate(`/dialog/extension`,{state:{title:e.title,meta:e.meta,metaStatus:e.metaStatus,metaSuffix:e.metaSuffix,actions:e.actions,panelInfo:e.panelInfo,info:e.info,healthStats:e.healthStats,logEntries:e.logEntries,onRefresh:e.onRefresh,dataListEntries:e.dataListEntries,fullText:e.fullText,onOpenPanel:e.panelInfo?()=>u(e.panelInfo):void 0,onAction:t=>{n(),e.onAction(t)},onClose:()=>{let r=t.stack,i=r.length>=2?r[r.length-2]?.path:void 0;n(),i!==`/dialog/extensions`&&e.onClose?.()}}});return}case`pluginPanel`:u(e.panelInfo,e.onClose);return;case`extensionsList`:{let t=s();t.navigate(`/dialog/extensions`,{state:{entries:e.entries,menuContributions:e.menuContributions,lastSelectedValue:l.value,onSelect:n=>{l.value=n,n.startsWith(`contrib:`)&&t.goBack(),e.onSelect(n)},onCancel:()=>{t.goBack(),e.onCancel?.()}}});return}case`input`:return new Promise(t=>{if(e.signal?.aborted){t(null);return}let n=!1,i=e=>{n||(n=!0,r.input===i&&(s()?.goBack(),r.input=null,r.inputAction=null),t(e))};r.input=i,e.actionButton?.onPress&&(r.inputAction=e.actionButton.onPress),e.signal?.addEventListener(`abort`,()=>i(null),{once:!0}),s().navigate(`/dialog/input`,{state:{title:e.title,description:e.description,placeholder:e.placeholder,defaultValue:e.defaultValue,mask:e.mask,actionButton:e.actionButton?{label:e.actionButton.label}:void 0}})});case`onboarding`:return new Promise(t=>{let n=!1,i=e=>{n||(n=!0,r.onboarding===i&&(s()?.navigate(`/`,{reset:!0}),r.onboarding=null),t(e))};r.onboarding=i,s().navigate(`/dialog/onboarding`,{state:{onLanguagePreview:e.onLanguagePreview}})});case`questions`:return new Promise(t=>{o(!0),r.questions=(e,n)=>{t(e?{answers:e,freeformText:n}:null)},s().navigate(`/dialog/questions`,{state:{title:e.title,questions:e.questions}})});case`confirm`:{let t=s();r.confirm=()=>e.onConfirm(),r.cancel=()=>e.onCancel?.(),r.extra=e.onExtra??null;let n=t.currentPath===`/dialog/confirm`;t.navigate(`/dialog/confirm`,{replace:n,state:{title:e.title,message:e.message,confirmLabel:e.confirmLabel,cancelLabel:e.cancelLabel,confirmColor:e.confirmColor,dangerous:e.dangerous,extraLabel:e.extraLabel,extraColor:e.extraColor}});return}case`permissions`:s().navigate(`/dialog/info`,{state:{title:`Permissions`,lines:e.lines}});return;case`info`:s().navigate(`/dialog/info`,{state:{title:e.title,lines:e.lines,action:e.action,lineTones:e.lineTones,dataListEntries:e.dataListEntries}});return;case`context`:s().navigate(`/pane/context`);return;case`memory`:s().navigate(`/dialog/memory`,{state:{projectIndex:e.projectIndex,userIndex:e.userIndex,onViewEntry:e.onViewEntry,onForget:e.onForget}});return;case`keybindingPanel`:s().navigate(`/dialog/keybindings`,{state:{overrides:e.overrides,onSave:e.onSave,onSaveReplace:e.onSaveReplace,onReset:e.onReset,onResetAll:e.onResetAll}});return;case`shortcutsPanel`:s().navigate(`/dialog/shortcuts`,{state:{bindings:e.shortcuts,onSave:e.onSave,onDelete:e.onDelete}});return;case`fileViewer`:s().navigate(`/viewer/file`,{state:{path:e.path,content:e.content,preTruncated:e.preTruncated,onDismiss:e.onDismiss}});return;case`helpViewer`:s().navigate(`/viewer/help`,{state:{title:e.title,lines:e.lines,onDismiss:e.onDismiss}});return;case`progress`:{let t=s();c={title:e.title,phases:e.phases,phaseIndex:0,phaseStatuses:[`active`,`pending`,`pending`,`pending`],percent:0,detail:e.phases[0]??``,status:`running`,onDismiss:()=>{c=null}},t.navigate(`/dialog/progress`,{state:c});return}case`wizard`:{let t=s();if(t?.currentPath===`/dialog/wizard`)return;t?.navigate(`/dialog/wizard`,{state:{...e,onDismiss:()=>{t.navigate(`/`,{reset:!0}),e.onDismiss?.()},onComplete:()=>{t.navigate(`/`,{reset:!0}),e.onComplete?.()}}});return}case`a2uiForm`:{let t=s();t.navigate(`/dialog/a2ui-form`,{state:{component:e.component,onAction:(n,r,i)=>{t.goBack(),e.onAction(n,r,i)},onDismiss:()=>{t.goBack()}}});return}default:return e}}),togglePane:(e,r)=>{let a=s();if(!a)return;let o=e=>a.currentPath===e||a.currentPath.startsWith(e+`/`),c=e=>{a.currentPath===e?a.goBack():a.navigate(`/`,{reset:!0})};switch(e){case`history`:pu()?.();return;case`backgroundTasks`:{let e=`/pane/delegates`;r??!o(e)?a.navigate(e):(c(e),t.setState({backgroundOutput:null}),i());return}case`draftPane`:{let e=`/pane/draft`;r??!o(e)?a.navigate(e):c(e);return}case`queuePane`:{let e=`/pane/queue`;r??!o(e)?a.navigate(e):c(e);return}case`notifications`:r??a.currentPath!==`/pane/notifications`?a.navigate(`/pane/notifications`):(a.goBack(),n.setState({notifications:n.getState().notifications.map(e=>({...e,read:!0}))}));return;case`schedulePane`:r??a.currentPath!==`/pane/schedule`?a.navigate(`/pane/schedule`):a.goBack();return;case`perf`:r??a.currentPath!==`/pane/perf`?a.navigate(`/pane/perf`):a.goBack();return;case`cacheStats`:r??a.currentPath!==`/pane/cache`?a.navigate(`/pane/cache`):a.goBack();return;case`compactionLog`:{let e=`/pane/compaction-log`;r??!o(e)?a.navigate(e):c(e);return}case`gallery`:r??a.currentPath!==`/pane/gallery`?a.navigate(`/pane/gallery`):a.goBack();return;case`proxy`:r??a.currentPath!==`/pane/proxy`?a.navigate(`/pane/proxy`):a.goBack();return;case`prompts`:{let e=`/pane/prompts`;r??!o(e)?a.navigate(e):c(e);return}default:return e}},getNotifyStats:e.getNotifyStats,isFullScreenPaneActive:()=>a(),getCurrentPath:()=>s()?.currentPath??`/`,isForcedUpgradeActive:()=>e.taskStore.getState().forcedUpgrade!==null,openAlert:e=>{r.alert=()=>e.onOk?.(),s().navigate(`/dialog/alert`,{state:{title:e.title,message:e.message,okLabel:e.okLabel}})},openPrompt:e=>new Promise(t=>{r.prompt=t,s().navigate(`/dialog/prompt`,{state:{title:e.title,message:e.message,placeholder:e.placeholder,initialValue:e.initialValue,submitLabel:e.submitLabel,cancelLabel:e.cancelLabel}})}),updateProgress(e){if(!c)return;let t=s();if(!t){c=null;return}c={...c,...e},t.navigate(`/dialog/progress`,{replace:!0,state:c})}}}function Qg(e){let{taskStore:t,state:n,notify:r,showToast:i,getRouter:a=M}=e;return{startShellExecution:e=>{n.shellTimer&&clearTimeout(n.shellTimer),t.setState({shellExecution:{command:e,output:``,status:`running`,exitCode:null}}),a()?.navigate(`/pane/shell`),r()},appendShellOutput:e=>{t.getState().shellExecution&&(t.setState({shellExecution:{...t.getState().shellExecution,output:t.getState().shellExecution.output+e}}),r())},finishShellExecution:(e,n,i)=>{t.getState().shellExecution&&(t.setState({shellExecution:{...t.getState().shellExecution,status:e===null?`error`:`done`,exitCode:e,terminated:i,output:n?t.getState().shellExecution.output+n:t.getState().shellExecution.output}}),r())},dismissShellExecution:()=>{n.shellTimer&&clearTimeout(n.shellTimer),t.setState({shellExecution:null}),a()?.currentPath===`/pane/shell`&&a()?.goBack(),n.shellTimer=null,r()},copyShellOutput:()=>{let e=t.getState().shellExecution;e&&(Kn(e.output),i(B.t(`shell.copiedTitle`),B.t(`shell.copiedBody`)))},getShellExecutionSnapshot:()=>{let e=t.getState().shellExecution;return e?{command:e.command,output:e.output,exitCode:e.exitCode,terminated:e.terminated}:null}}}function $g(e){let{notificationStore:t,state:n,counters:r,notify:i,getRouter:a=M}=e;return{showToast:(e,o)=>{n.toastTimer&&clearTimeout(n.toastTimer);let s={id:++r.toast,title:e,content:o};t.setState({toast:s}),Wr(a(),Nr,!0),n.toastTimer=setTimeout(()=>{t.setState({toast:null}),n.toastTimer=null,Wr(a(),Nr,!1),i()},Cm),i()},showRetryDialog:(e,n,r,o,s,c,l)=>{t.setState({retryCountdown:{attempt:e,max:n,delayMs:r,accelerate:o,reason:c,onExpired:()=>{t.setState({retryCountdown:null}),Wr(a(),Fr,!1),i(),s()},onStop:l?()=>{t.setState({retryCountdown:null}),Wr(a(),Fr,!1),i(),l()}:void 0}}),Wr(a(),Fr,!0),i()},clearRetryDialog:()=>{t.setState({retryCountdown:null}),Wr(a(),Fr,!1),i()},showErrorRetry:e=>{let n=e=>()=>{t.setState({errorRetry:null}),Wr(a(),Ir,!1),i(),e()};t.setState({errorRetry:{...e,actions:e.actions.map(e=>({...e,run:n(e.run)})),focusIndex:0,exhausted:e.exhausted??!1,onExpired:n(e.onExpired),onCancel:n(e.onCancel)}}),Wr(a(),Ir,!0),i()},clearErrorRetry:()=>{t.setState({errorRetry:null}),Wr(a(),Ir,!1),i()},pushNotification:(e,n,a=`system`,o=`info`)=>{t.setState({notifications:[{id:++r.notify,source:a,level:o,title:e,message:n,timestamp:Date.now(),read:!1},...t.getState().notifications.slice(0,49)]}),i()},dismissNotification:e=>{t.setState({notifications:t.getState().notifications.filter(t=>t.id!==e)}),t.getState().notifications.length===0&&a()?.goBack(),i()},markAllNotificationsRead:()=>{t.setState({notifications:t.getState().notifications.map(e=>({...e,read:!0}))}),i()}}}function e_(e){let{taskStore:t,messageStoreHandle:n,counters:r,pendingSteerMsgIds:i,scrollbackMode:a,commitToHistory:o,scanA2uiButtons:s,notify:c}=e;return{setPendingEcho:(e,r)=>{if(t.setState({pendingEcho:{text:e,mode:r}}),!a){let e=n.store.getState().messages.at(-1);e?.id?n.patchById(e.id,{streaming:!0}):n.patchLast({streaming:!0})}c()},clearPendingEcho:()=>{let e=t.getState().pendingEcho;if(e){if(a&&(o({role:`user`,content:e.text}),s()),t.setState({pendingEcho:null}),!a){let e=n.store.getState().messages.at(-1);e?.id?n.patchById(e.id,{streaming:!1}):n.patchLast({streaming:!1})}c()}},withdrawPendingEcho:()=>{if(t.getState().pendingEcho){if(t.setState({pendingEcho:null}),!a){let e=`u-${r.msg}`,t=n.store.getState().messages.findLastIndex(t=>t.id===e);if(t!==-1){let e=[...n.store.getState().messages];e.splice(t,1),n.store.setState({messages:e})}else n.removeLast()}c()}},setPendingSteer:(e,o)=>{if(t.setState({pendingSteers:[...t.getState().pendingSteers,{text:e,id:o}]}),!a){r.msg++;let t=`u-${r.msg}`;i.set(o,t),n.append({role:`user`,content:e,streaming:!0,id:t},t)}c()},commitPendingSteer:e=>{let r=t.getState().pendingSteers,l=r.find(t=>t.id===e);if(l){if(a)o({role:`user`,content:l.text}),s();else{let t=i.get(e);t&&(n.patchById(t,{streaming:!1}),i.delete(e))}t.setState({pendingSteers:r.filter(t=>t.id!==e)}),c()}},withdrawPendingSteer:e=>{let r=t.getState().pendingSteers;if(r.some(t=>t.id===e)){if(t.setState({pendingSteers:r.filter(t=>t.id!==e)}),!a){let t=i.get(e);if(t){let r=n.store.getState().messages.filter(e=>e.id!==t);n.store.setState({messages:r}),i.delete(e)}}c()}},clearPendingSteers:()=>{let e=t.getState().pendingSteers;if(e.length!==0){if(a){for(let t of e)o({role:`user`,content:t.text});s()}else for(let t of e){let e=i.get(t.id);e&&(n.patchById(e,{streaming:!1}),i.delete(t.id))}t.setState({pendingSteers:[]}),c()}}}}function t_(e){let{streamStore:t,streamTextCoalescer:n,streamThinkingCoalescer:r,outputTokensThrottle:i,perfStore:a,compactionLogStore:o,drainQueue:s,getRouterRef:c,notify:l}=e;return{pushEngineEvent:e=>{switch(e.kind){case`agentProcessing`:t.setState({processing:e.value}),e.value||s();break;case`streamingText`:n.push(e.text,e.text===``);break;case`streamingThinking`:r.push(e.text,e.text===``);break;case`activeTool`:t.setState({activeTool:e.name});break;case`spinnerMode`:t.setState(e.mode===`requesting`?{spinnerMode:e.mode,outputTokensThisTurn:0}:{spinnerMode:e.mode});break;case`outputTokensThisTurn`:i.push(e.n);break;case`maxOutputTokens`:t.setState({maxOutputTokens:e.n});break;case`toolBudget`:t.setState({toolTurnCount:e.toolTurnCount,maxToolTurns:e.maxToolTurns,promptOutputTokens:e.outputTokens??0,promptOutputTokenBudget:e.outputTokenBudget??0});break;case`perf`:{let t=!1;e.memory&&(a.setMemory(e.memory),t=!0),e.notify&&(a.setNotify(e.notify),t=!0),e.pluginMetrics&&(a.setPluginMetrics(e.pluginMetrics),t=!0),e.indicatorLevel&&a.setIndicatorLevel(e.indicatorLevel),t&&l();break}case`compactionLog`:switch(e.entryKind){case`compact`:o.recordCompaction(e.before,e.after,e.summary);break;case`prune`:o.recordPrune(e.tokensSaved,e.prunedCount??0);break;case`history_capped`:o.recordHistoryCapped(e.removedCount);break}c()?.currentPath.startsWith(`/pane/compaction-log`)&&l();break}}}}function n_(e){let{modalHandleMethods:t,permResolvers:n,counters:r,taskStore:i,getRouterRef:a,notify:o,onConfirmResolve:s}=e;return{...t,resolveConfirm:e=>{s(e)},requestPermission:e=>{let t=`perm-${++r.perm}`;return new Promise(r=>{n.set(t,r);let s={id:t,tool:e.tool,input:e.input,risk:e.risk,description:e.description,alwaysAllowLabel:e.alwaysAllowLabel};i.setState({pendingPermission:s}),o(),a()?.navigate(`/dialog/permission`,{state:s})})}}}function r_(e){let{pendingMethods:t,restoreInputRef:n,pasteBridgeRef:r}=e;return{...t,restoreInputText:e=>{n.current?.fill(e)},hydratePaste:e=>{r.current?.hydrate(e)},exportPaste:()=>r.current?.export()??null}}function i_(e){let{lifecycleFlags:t,scrollbackBuffer:n,streamTextCoalescer:r,streamThinkingCoalescer:i,notifyScheduler:a,state:o,registryUnregisterAll:s,unmount:c,windowMode:l,scopedViewport:u,hasHistoryRef:d,resetStreamController:f,messageStoreHandle:p,scrollStoreHandle:m,streamStoreHandle:h,taskStoreHandle:g,notificationStoreHandle:_,perfStore:v,contextStore:y,budgetStore:b,taskStore:x,notificationStore:S,a2uiButtonsRef:C,resetStatusWidgetBreakers:w,getRouterRef:T,overlayPaths:E,syncOverlayRoute:D,notify:O,i18next:ee,detectLanguage:te,setLanguage:ne,getThemeRef:k,setTerminalTitle:re}=e;return{stop:()=>{if(!t.stopped){t.stopped=!0,t.unmounted=!0,e.detachSessionSource?.(),s();try{n.flush()}catch{}r.cancel(),i.cancel(),a.cancel(),o.toastTimer&&=(clearTimeout(o.toastTimer),null),c(),e.onStop?.()}},clearSession:()=>{l||n.write(u?`\x1B[2J\x1B[H`:`\x1B[2J\x1B[3J\x1B[H`),d.set(!1),f(),p.reset(),m.toBottom(),h.reset(),g.reset(),_.reset(),v.reset(),y.reset(),b.reset(),x.setState({tasks:[]}),x.setState({tasksTitle:void 0}),x.setState({turnBoundaries:[]}),x.setState({editedFiles:[]}),x.setState({subagentsAccum:new Map}),S.setState({toast:null}),S.setState({retryCountdown:null}),S.setState({errorRetry:null});let e=T();if(e)for(let t of E)D(e,t,!1);S.setState({providerUsage:null}),o.toastTimer&&=(clearTimeout(o.toastTimer),null),C.current=[],s(),w(),e?.currentPath!==`/home`&&e?.navigate(`/home`,{reset:!0}),O()},setLanguage:e=>{let t=e===`auto`?te():e;return ee.changeLanguage(t),ne(t),O(),t},setPresetSelection:e=>{k()?.setPresetSelection(e)},setTerminalTitle:e=>re(e)}}function a_(e){let{messageStoreHandle:t,notify:n}=e,r=null,i=()=>{let e=r;e&&(r=null,e.stop())};return{attachSessionSource:async e=>{if(r)throw Error(`attachSessionSource: a session data source is already attached`);return r={stop:await e.start({messageStore:{setState:e=>t.store.setState(e)}})},n(),i},detachSessionSource:i}}function o_(e){let{scrollbackMode:t,commitToHistory:n,commitManyToHistory:r,messageStoreHandle:i,counters:a,getTurnMessagesFor:o,taskStore:s,notify:c,scanA2uiButtons:l}=e;return{pushMessage:e=>{if(t){n(e),c(),l();return}a.msg++,i.append(e,`m-${a.msg}`),c(),l()},pushMessages:e=>{if(e.length!==0){if(t){r(e),c(),l();return}i.appendMany(e,()=>(a.msg++,`m-${a.msg}`)),c(),l()}},echoUserInput:(e,r)=>{let o=r?.pending===!0;if(t){if(o)return;n({role:`user`,content:e}),l();return}a.msg++;let s=`u-${a.msg}`;i.append({role:`user`,content:e,streaming:o,id:s},s),c(),l()},getTurnMessages:o,getTurnBoundaries:()=>s.getState().turnBoundaries,getEditedFiles:()=>s.getState().editedFiles}}function s_(e){let{streamMethods:t,taskStore:n,notificationStore:r,notificationMethods:i,getRouterRef:a,syncOverlayRoute:o,overlayPause:s,drainQueue:c,notify:l}=e;return{pushEngineEvent:t.pushEngineEvent,hasQueuedFollowUp:()=>n.getState().queued.length>0,takeLastQueuedFollowUp:()=>{let e=n.getState().queued,t=e.at(-1);if(t)return n.setState({queued:e.slice(0,-1)}),l(),t},enqueueFollowUp:(e,t=`send`)=>{n.setState({queued:[...n.getState().queued,{text:e,mode:t}]}),l(),c()},setPauseDialog:e=>{r.setState({pauseDialog:e}),o(a(),s,!!e),l()},showRetryDialog:i.showRetryDialog,clearRetryDialog:i.clearRetryDialog,showErrorRetry:i.showErrorRetry,clearErrorRetry:i.clearErrorRetry}}function c_(e){let{modalHandleMethods:t,taskStore:n,getRouterRef:r,syncOverlayRoute:i,overlayServices:a,flushScrollbackIfIdle:o,notify:s}=e;return{togglePane:t.togglePane,setServices:e=>{i(r(),a,e),s()},switchToSubagentContext:e=>{n.setState({subagentContext:e});let t=r();e&&t?.currentPath!==`/subagent`&&t?.navigate(`/subagent`),o(),s()},toggleEditedFiles:e=>{if(n.getState().editedFiles.length===0)return;let t=r();if(!t)return;let i=`/pane/edited-files`,a=t.currentPath===i||t.currentPath.startsWith(i+`/`),o=e??!a;o&&!a?t.navigate(i):!o&&a&&t.currentPath===i&&t.goBack()},clearEditedFiles:()=>{n.setState({editedFiles:[]}),s()},removeQueuedAt:e=>{n.setState({queued:n.getState().queued.filter((t,n)=>n!==e)}),s()},clearQueue:()=>{n.setState({queued:[]}),s()},moveQueuedItem:(e,t)=>{let r=e,i=e+t;if(i<0||i>=n.getState().queued.length||r<0||r>=n.getState().queued.length)return;let a=[...n.getState().queued],[o]=a.splice(r,1);o&&a.splice(i,0,o),n.setState({queued:a}),s()}}}function l_(e){let{taskStore:t,taskStoreHandle:n,registerPlugin:r,registryUnregister:i,computeStalePluginIds:a,getRegistrySnapshot:o,getStatusItems:s,getStatusWidgets:c,resetStatusWidgetBreakers:l,registryRef:u,a2uiButtonsRef:d,subagentRestoreFields:f,notify:p}=e;return{setPluginRegistrations:e=>{let n=new Set;for(let t of e)n.add(t.pluginId),r(t.pluginId,t);for(let e of a(n,o()))i(e);l(),t.setState({pluginStatusItems:s(),statusWidgets:c()}),p()},unregisterPluginSource:e=>{i(e),l(),t.setState({pluginStatusItems:s(),statusWidgets:c()}),p()},setPluginStatusItems:e=>{n.actions.setPluginStatusItems(e.map(e=>({id:e.icon,text:e.text})))},setCommands:e=>{t.setState({commands:e}),r(`cli-commands`,{pluginId:`cli-commands`,commands:[...e]}),p()},registerArgumentSuggester:(e,t)=>{u?.current&&u.current.registerArgumentSuggester(e,t)},setA2uiButtons:e=>{d.current=e},addSubagent:e=>{let n=new Map(t.getState().subagentsAccum);n.set(e.id,{id:e.id,command:e.name,type:`agent-session`,startedAt:e.startedAt??Date.now(),...f(e.status)}),t.setState({subagentsAccum:n}),p()},getSubagents:()=>t.getState().subagentsAccum,clearSubagents:()=>{t.setState({subagentsAccum:new Map}),p()}}}function u_(e){let{notificationMethods:t,notifyScheduler:n,taskStore:r,modalHandleMethods:i,shellMethods:a,contextStore:o,getRouterRef:s,scrollStoreHandle:c}=e;return{pushNotification:t.pushNotification,dismissNotification:t.dismissNotification,markAllNotificationsRead:t.markAllNotificationsRead,getNotifyStats:()=>n.getStats(),getCurrentPath:()=>s()?.currentPath??`/`,isForcedUpgradeActive:()=>r.getState().forcedUpgrade!==null,isFullScreenPaneActive:()=>i.isFullScreenPaneActive(),getShellExecutionSnapshot:a.getShellExecutionSnapshot,addContextTurn:e=>o.addTurn(e),markContextTurns:e=>o.markTurns(e),showToast:t.showToast,setTopView:e=>{let t=s();t&&t.currentPath===`/home`&&t.navigate(`/`,{reset:!0}),c.toBottom(),c.setTotalLines(0)}}}function d_(e){let t=e.intervalMs??5e3,n=e.minIntervalMs??2e3,{stdout:r,enabled:i}=e,a=null,o=0,s=()=>{try{r.write(`\x1B]11;?\x07`),o=Date.now()}catch{}};return{start:()=>{i&&r.isTTY&&(a||(s(),a=setInterval(s,t),a.unref?.()))},stop:()=>{a&&=(clearInterval(a),null)},pollNow:()=>{i&&r.isTTY&&(Date.now()-o<n||s())}}}function f_(e,t,n,r,i){return{onPermissionDecision:(e,n,i)=>{let a=t.get(e);t.delete(e),r.setState({pendingPermission:null}),M()?.goBack(),a?.({approved:n,mode:i})},onSelectResolve:e=>{let t=n.select;n.select=null,M()?.goBack(),t?.(e)},onInputResolve:e=>{let t=n.input;t&&(n.input=null,M()?.currentPath===`/dialog/input`&&M()?.goBack(),t(e))},onOnboardingResolve:e=>{n.onboarding?.(e)},onInputAction:()=>{let e=n.inputAction;e?.()},onQuestionsResolve:(e,t)=>{let r=n.questions;r&&(i?.(!1),n.questions=null,M()?.currentPath===`/dialog/questions`&&M()?.goBack(),r(e,t))},onConfirmResolve:(e,t)=>{let r=n.confirm,i=n.cancel,a=n.extra;n.confirm=null,n.cancel=null,n.extra=null,M()?.currentPath===`/dialog/confirm`&&M()?.goBack(),!(!r&&!i&&!a)&&(t?a?.():e?r?.():i?.())},onAlertResolve:()=>{let e=n.alert;n.alert=null,M()?.goBack(),e?.()},onPromptResolve:e=>{let t=n.prompt;n.prompt=null,M()?.goBack(),t?.(e)},getTurnMessagesFor:t=>{let n=r.getState().turnBoundaries,i=e.getMessages(),a=t>1?n[t-2]??0:0,o=n[t-1]??i.length;return i.slice(a,o)}}}function p_(e,t,n,r,i){return()=>{if(t()||i.getState().queued.length===0)return;let[e,...a]=i.getState().queued;i.setState({queued:a}),n(),queueMicrotask(()=>r?.(e.text,e.mode))}}function m_(e){let[,t]=K(0);V.useEffect(()=>{let n=()=>t(e=>e+1);return e.state.listener=n,()=>{e.state.listener===n&&(e.state.listener=null)}},[]);let n=V.useCallback(()=>{Yl(),e.taskStore.setState({backgroundOutput:null}),e.opts.onBackgroundOutputClose?.(),e.flushScrollbackIfIdle(),e.notify()},[]),r=V.useCallback(()=>{M()?.goBack(),e.taskStore.setState({backgroundOutput:null}),e.opts.onBackgroundOutputClose?.(),e.flushScrollbackIfIdle(),e.notify()},[]),i=V.useCallback(()=>{M()?.currentPath===`/subagent`&&M()?.goBack(),e.opts.onSubagentExit?.(),e.taskStore.setState({subagentContext:null}),e.flushScrollbackIfIdle(),e.notify()},[]),a=V.useCallback(()=>{e.taskStore.getState().queued.length!==0&&(e.taskStore.setState({queued:e.taskStore.getState().queued.slice(0,-1)}),e.notify())},[]),o=V.useCallback(()=>{M()?.currentPath===`/dialog/info`&&M()?.goBack(),e.notify()},[]),s=V.useCallback(()=>{M()?.currentPath===`/dialog/memory`&&M()?.goBack(),e.notify()},[]),c=V.useCallback(()=>{M()?.currentPath===`/dialog/keybindings`&&M()?.goBack(),e.notify()},[]),l=V.useCallback(()=>{M()?.currentPath===`/dialog/shortcuts`&&M()?.goBack(),e.notify()},[]),u=V.useCallback(()=>{M()?.navigate(`/pane/context/detail`)},[]),d=V.useCallback(()=>{M()?.currentPath===`/pane/context/detail`&&M()?.goBack()},[]),f=V.useCallback(()=>{let e=M();e?.currentPath.startsWith(`/pane/context`)&&e.navigate(`/`,{reset:!0})},[]),p=V.useCallback(()=>{let e=M();e&&(e.currentPath===`/pane/notifications`?e.goBack():e.navigate(`/pane/notifications`))},[]),m=V.useCallback(t=>{e.notificationStore.setState({notifications:e.notificationStore.getState().notifications.filter(e=>e.id!==t)}),e.notificationStore.getState().notifications.length===0&&M()?.goBack()},[]),h=V.useCallback(()=>{e.notificationStore.setState({notifications:e.notificationStore.getState().notifications.map(e=>({...e,read:!0}))}),M()?.goBack()},[]),g=V.useCallback(()=>{e.opts.onSubmit?.(`/upgrade`,`send`)},[]),_=V.useCallback(()=>{e.stopRef.current?.()},[]),v=V.useCallback((t,n)=>{e.state.toastTimer&&clearTimeout(e.state.toastTimer);let r={id:++e.toastCounterRef.current,title:t,content:n};e.notificationStore.setState({toast:r}),Wr(M(),Nr,!0),e.state.toastTimer=setTimeout(()=>{e.notificationStore.setState({toast:null}),e.state.toastTimer=null,Wr(M(),Nr,!1),e.notify()},Cm),e.notify()},[]),y=V.useCallback(()=>{e.state.toastTimer&&(clearTimeout(e.state.toastTimer),e.state.toastTimer=null),e.notificationStore.getState().toast&&(e.notificationStore.setState({toast:null}),Wr(M(),Nr,!1),e.notify())},[]),b=e.scrollbackMode?V.useCallback(t=>{e.inkWriteRef.current=t},[]):void 0,x=e.opts.welcome?.cwd?V.useCallback(async t=>{let{content:n,truncated:r}=await Zt(ln(e.opts.welcome.cwd,t));return{content:n,truncated:r}},[]):void 0,S=V.useCallback(()=>{if(e.taskStore.getState().editedFiles.length===0)return;let t=M();if(!t)return;let n=`/pane/edited-files`;t.currentPath===n||t.currentPath.startsWith(n+`/`)?t.navigate(`/`,{reset:!0}):t.navigate(n,{replace:!0})},[]),C=V.useCallback(()=>{if(e.taskStore.getState().subagentsAccum.size===0)return;let t=M();t&&(t.currentPath===`/pane/subagents`?t.navigate(`/`,{reset:!0}):t.navigate(`/pane/subagents`,{replace:!0}))},[]),w=V.useCallback(()=>{if(e.taskStore.getState().scheduleTasks.length===0)return;let t=M();t&&(t.currentPath===`/pane/schedule`?t.navigate(`/`,{reset:!0}):t.navigate(`/pane/schedule`,{replace:!0}))},[]),T=V.useCallback(e=>{let t=M();if(!t)return;let n=`/pane/draft`,r=t.currentPath===n||t.currentPath.startsWith(n+`/`),i=e??!r;i&&!r?t.navigate(n,{replace:!0}):!i&&r&&t.navigate(`/`,{reset:!0})},[]),E=V.useCallback(e=>{let t=M();if(!t)return;let n=`/pane/queue`,r=t.currentPath===n||t.currentPath.startsWith(n+`/`),i=e??!r;i&&!r?t.navigate(n,{replace:!0}):!i&&r&&t.navigate(`/`,{reset:!0})},[]),D=V.useCallback(()=>{let e=M();if(!e)return;let t=`/pane/prompts`;e.currentPath===t||e.currentPath.startsWith(t+`/`)?Yl():e.navigate(t,{replace:!0})},[]),O=V.useCallback(t=>{e.opts.onDraftSave?.(t)},[]),ee=V.useCallback(t=>{let n=e.taskStore.getState().drafts[t];n&&e.opts.onDraftDelete?.(n.id)},[]),te=V.useCallback(t=>{e.opts.onDraftDeleteMany?.(t)},[]),ne=V.useCallback(t=>{e.taskStore.setState({queued:e.taskStore.getState().queued.filter((e,n)=>n!==t)}),e.notify()},[]),k=V.useCallback((t,n)=>{let r=t,i=t+n;if(i<0||i>=e.taskStore.getState().queued.length||r<0||r>=e.taskStore.getState().queued.length)return;let a=[...e.taskStore.getState().queued],[o]=a.splice(r,1);o&&a.splice(i,0,o),e.taskStore.setState({queued:a}),e.notify()},[]),re=V.useCallback((t,n)=>{let r=e.taskStore.getState().queued;if(t<0||t>=r.length)return;let i=[...r],a=i[t];a&&(i[t]={...a,text:n}),e.taskStore.setState({queued:i}),e.notify()},[]),ie=V.useCallback((t,n)=>{let r=e.taskStore.getState().queued;if(t<0||t>=r.length)return;let i=r[t].mode;e.taskStore.setState({queued:r.filter((e,n)=>n!==t)}),e.notify(),e.opts.onQueueSendNow?.(n,i)},[]),A=V.useCallback(t=>{let n=e.notificationStore.getState().errorRetry;n&&(e.notificationStore.setState({errorRetry:{...n,focusIndex:t}}),e.notify())},[]),ae=V.useCallback(t=>{let n=e.notificationStore.getState().pulseSurvey;n&&(e.notificationStore.setState({pulseSurvey:{...n,...t}}),e.notify())},[]),j=V.useCallback(()=>{if(e.taskStore.getState().backgroundTasks.length===0)return;let t=M();if(!t)return;let n=`/pane/delegates`;t.currentPath===n||t.currentPath.startsWith(n+`/`)?(t.navigate(`/`,{reset:!0}),e.taskStore.setState({backgroundOutput:null}),e.flushScrollbackIfIdle()):t.navigate(n,{replace:!0})},[]),oe=V.useCallback(()=>{e.state.shellTimer&&clearTimeout(e.state.shellTimer),e.taskStore.setState({shellExecution:null}),e.state.shellTimer=null,M()?.currentPath===`/pane/shell`&&M()?.goBack(),e.notify()},[]),se=V.useCallback(()=>{let t=e.taskStore.getState().shellExecution;t&&(Kn(t.output),v(B.t(`shell.copiedTitle`),B.t(`shell.copiedBody`)))},[]);return V.useEffect(()=>{let t=null,n=()=>{t&&clearTimeout(t),t=setTimeout(()=>{let t=e.opts.columns||(e.stdout.columns>0?e.stdout.columns:process.stdout.columns>0?process.stdout.columns:80),n=e.opts.rows||(e.stdout.rows>0?e.stdout.rows:process.stdout.rows>0?process.stdout.rows:24);(t!==e.columnsRef.current||n!==e.rowsRef.current)&&(e.columnsRef.current=t,e.rowsRef.current=n,e.notify())},100)};return e.stdout.on(`resize`,n),()=>{t&&clearTimeout(t),e.stdout.off(`resize`,n)}},[]),V.createElement(ag,{columns:e.columnsRef.current,rows:e.rowsRef.current,registerWrite:e.scrollbackMode?b:void 0,maxPreviewRows:e.scrollbackMode?1:void 0,hasHistory:e.hasHistoryRef.current,messages:e.messageStore.getState().messages,scrollStore:e.scrollStore,loadHistory:e.opts.loadHistory,messageStore:e.messageStoreHandle,windowMode:e.windowMode,scrollbackMode:e.scrollbackMode,shadow:e.opts.shadow??!1,language:e.languageRef.current,systemTheme:e.systemTheme,themeRegistry:e.themeRegistry,presetSelection:e.presetSelection,keybindingOverrides:e.opts.keybindingOverrides,onCyclePermissionMode:e.opts.onCyclePermissionMode,pluginInput:e.opts.pluginInput,readFileContent:x,getTurnMessages:e.getTurnMessagesFor,editedFilesOpen:!1,onToggleEditedFiles:S,subagentsOpen:!1,onToggleSubagents:C,onToggleSchedule:w,initialHistory:e.opts.initialHistory,externalHistoryCommands:e.opts.externalHistoryCommands,onHistoryPush:e.opts.onHistoryPush,residencyGovernor:e.opts.residencyGovernor,resolveWholeFileDiff:e.opts.resolveWholeFileDiff,restoreInputRef:e.restoreInputRef,pasteBridgeRef:e.pasteBridgeRef,scheduleOpen:!1,draftOpen:!1,onToggleDraftPane:T,onDraftSave:O,onDraftDelete:ee,onDraftDeleteMany:te,onSigilSelect:e.opts.onSigilSelect,queueOpen:!1,onToggleQueuePane:E,onTogglePrompts:D,onQueueDelete:ne,onQueueMove:k,onQueueEditText:re,onQueueSendNow:ie,pendingEcho:e.taskStore.getState().pendingEcho,onErrorRetryFocusChange:A,onPulseSurveyChange:ae,backgroundTasksOpen:!1,onToggleDelegates:j,onBackgroundClose:n,onBackgroundKill:e.opts.onBackgroundKill,onBackgroundViewOutput:e.opts.onBackgroundViewOutput,onBackgroundOutputClose:r,onBackgroundApply:e.opts.onBackgroundApply,onBackgroundSwitch:e.opts.onBackgroundSwitch,onBackgroundDelete:e.opts.onBackgroundDelete,onExitSubagentContext:i,onPaneOwnsViewportChange:e.scrollbackMode?e.setPaneOwnsViewport:void 0,onFocusOwnerChange:e.scrollbackMode?e.setFocusOwnerForBuffer:void 0,onScrollActiveChange:e.setScrollActive,onDelegateSupply:e.opts.onDelegateSupply,welcome:e.opts.welcome,onSessionSelect:e.opts.onSessionSelect,budgetStore:e.budgetStore,contextStore:e.contextStore,notificationStore:e.notificationStoreHandle,perfStore:e.perfStore,onPerfDismiss:()=>{M()?.currentPath===`/pane/perf`&&M()?.goBack()},cacheStore:e.cacheStore,onCacheDismiss:()=>{M()?.currentPath===`/pane/cache`&&M()?.goBack()},proxyStore:e.proxyStore,proxyOpen:!1,onProxyDismiss:()=>{M()?.goBack()},onProxyOpenModal:e.proxyOpenModal,onProxySubmitUrl:e.opts.onProxySubmitUrl,onProxyToggleEnabled:e.opts.onProxyToggleEnabled,onProxyClear:e.opts.onProxyClear,compactionLogStore:e.compactionLogStore,onCompactionLogDismiss:()=>{let e=M();e?.currentPath.startsWith(`/pane/compaction-log`)&&e.navigate(`/`,{reset:!0})},galleryStore:e.galleryStore,onGalleryDismiss:()=>{M()?.currentPath===`/pane/gallery`&&M()?.goBack()},streamStore:e.streamStoreHandle,taskStore:e.taskStoreHandle,initialPath:e.opts.initialPath,onPerfRefresh:e.opts.onPerfRefresh,onSubmit:e.submitOrQueue,onInterrupt:e.opts.onInterrupt,onWithdrawPending:e.opts.onWithdrawPending,onWithdrawSteer:e.opts.onWithdrawSteer,onPopQueued:a,onPermissionDecision:e.onPermissionDecision,onSelectResolve:e.onSelectResolve,onInputResolve:e.onInputResolve,onOnboardingResolve:e.onOnboardingResolve,onInputAction:e.onInputAction,onQuestionsResolve:e.onQuestionsResolve,onConfirmResolve:e.onConfirmResolve,onAlertResolve:e.onAlertResolve,onPromptResolve:e.onPromptResolve,onInfoDismiss:o,onMemoryDismiss:s,onKeybindingPanelDismiss:c,onShortcutsDialogDismiss:l,onViewDetails:u,onBackToContextPane:d,onContextDismiss:f,notificationsOpen:!1,onToggleNotifications:p,onDismissNotification:m,onCloseNotifications:h,onUpgrade:g,onCancelUpgrade:_,onToast:v,onDismissToast:y,registryRef:e.registryRef,shellBackendRef:e.shellBackendRef,shellExecution:e.taskStore.getState().shellExecution,onShellAbort:e.opts.onInterrupt,onShellDismiss:oe,onShellCopyOutput:se,onShellAskAi:e.opts.onShellAskAi,a2uiButtons:e.a2uiButtonsRef.current,onA2uiAction:e.a2uiActionRef.current})}function h_(){let e=Buffer.alloc(0);return t=>{let n=N(t),r=e.length?Buffer.concat([e,n]):n;e=Buffer.alloc(0);let i=r.length;i>=2&&r[i-2]===27&&r[i-1]===91&&(e=Buffer.from(r.subarray(i-2)),i-=2);let a,o=[],s=0;for(;s<i;){if(r[s]===27&&r[s+1]===91&&(r[s+2]===73||r[s+2]===79)){a=r[s+2]===73,s+=3;continue}o.push(r[s]),s++}return{focused:a,rest:Buffer.from(o)}}}var g_=class{pending=null;feed(e){let t=N(e),n=this.pending?Buffer.concat([this.pending,t]):t;this.pending=null;let r=[],i=null,a=0;for(;a<n.length;){let e=n.indexOf(`\x1B]`,a,`latin1`);if(e<0){a<n.length&&r.push(n.slice(a));break}e>a&&r.push(n.slice(a,e));let t=n.indexOf(7,e),o=n.indexOf(`\x1B\\`,e,`latin1`),s=-1,c=0;if(t>=0&&(o<0||t<o)?(s=t,c=1):o>=0&&(s=o,c=2),s<0){let t=n.slice(e);t.length>64?r.push(t):this.pending=t;break}let l=__(n.slice(e,s).toString(`latin1`));l&&(i=l),a=s+c}return{keys:r.length>0?Buffer.concat(r):Buffer.alloc(0),osc11:i}}};function __(e){let t=e.match(/\]11;rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(!t)return null;let n=parseInt(t[1].slice(0,2),16),r=parseInt(t[2].slice(0,2),16),i=parseInt(t[3].slice(0,2),16);return Number.isNaN(n)||Number.isNaN(r)||Number.isNaN(i)?null:{r:n,g:r,b:i}}function v_(e,t,n){return .2126*e+.7152*t+.0722*n<128?`dark`:`light`}function y_(e){let{stdin:t,renderStdout:n,onInterrupt:r,onFocusChange:i,onTerminalBgDetected:a,onMouseWheel:o,onMouseDrag:s}=e,c=[],l=process.env.OTTO_TUI_MOUSE===`0`,u=(typeof o==`function`||typeof s==`function`)&&!!t.isTTY,d=u&&!l,f=u?Lg():null,p=d,m;if(d)try{n.write(Pg)}catch{}u&&(m=()=>{try{n.write(Fg)}catch{}},process.once(`exit`,m));let h=e=>{if(!u)return!1;if(e===p)return p;p=e;try{n.write(e?Pg:Fg)}catch{}return p},g=new g_,_=e=>{if(!a)return N(e);let{keys:t,osc11:n}=g.feed(e);return n&&a(v_(n.r,n.g,n.b)),t},v=e=>{if(!f)return _(e);let{wheels:t,drags:n,rest:r}=f(e);if(p){for(let e of t)o?.(e.delta);for(let e of n)s?.(e)}return _(r)},y=process.env.OTTO_TUI_KITTY===`1`&&!!t.isTTY,b,x=t;if(y){try{n.write(`\x1B[>1u`)}catch{}b=()=>{try{n.write(Vg)}catch{}},process.once(`exit`,b);let e=Gg(),i=new vn;Object.assign(i,{isTTY:!0,setRawMode:e=>{try{t.setRawMode?.(e)}catch{}return i},ref:()=>{try{t.ref?.()}catch{}return i},unref:()=>{try{t.unref?.()}catch{}return i}});let a=t=>{let n=v(t);if(n.length===0)return;let a=e(n);a.includes(3)&&r?.(),i.write(a)};t.on(`data`,a),c.push({stream:t,fn:a}),x=i}let S=process.env.OTTO_TUI_FOCUS===`1`&&!!t.isTTY&&typeof i==`function`,C;if(S){try{n.write(`\x1B[?1004h`)}catch{}C=()=>{try{n.write(`\x1B[?1004l`)}catch{}},process.once(`exit`,C);let e=x,t=h_(),r=new vn;Object.assign(r,{isTTY:!0,setRawMode:t=>{try{e.setRawMode?.(t)}catch{}return r},ref:()=>{try{e.ref?.()}catch{}return r},unref:()=>{try{e.unref?.()}catch{}return r}});let a=e=>{let n=v(e);if(n.length===0)return;let{focused:a,rest:o}=t(n);a!==void 0&&i?.(a),o.length&&r.write(o)};e.on(`data`,a),c.push({stream:e,fn:a}),x=r}if(!y&&!S&&(a||d)){let e=x,t=new vn;Object.assign(t,{isTTY:!0,setRawMode:n=>(e.setRawMode?.(n),t),ref:()=>(e.ref?.(),t),unref:()=>(e.unref?.(),t)});let n=e=>{let n=v(e);n.length>0&&t.write(n)};e.on(`data`,n),c.push({stream:e,fn:n}),e.resume(),x=t}return{renderStdin:x,kittyOn:y,focusOn:S,mouseOn:d,kittyExitHandler:b,focusExitHandler:C,mouseExitHandler:m,setMouseEnabled:h,isMouseEnabled:()=>p,cleanup:()=>{for(let{stream:e,fn:t}of c)e.removeListener(`data`,t);c.length=0}}}const b_=12e3;async function x_(e){let{stdin:t,stdout:n,onStop:r}=e,i=Tc(e.maxFps??30),a=e.renderMaxFps??90;Sa();let o=e.columns||(n.columns>0?n.columns:process.stdout.columns>0?process.stdout.columns:80),s=e.rows||(n.rows>0?n.rows:process.stdout.rows>0?process.stdout.rows:24),c=e.language&&e.language!==`auto`?e.language:Ct();St(c);let l=await P(),u=e.themeRegistry,d=e.presetSelection,f=process.env.OTTO_TUI_SCOPED_VIEWPORT!==`0`,p=mg(n),m=()=>Math.max(1,s-1);process.once(`exit`,()=>p.exit());let h=e.scrollback===!0||process.env.OTTO_TUI_SCROLLBACK===`1`,g=e.scrollback===!1||process.env.OTTO_TUI_SCROLLBACK===`0`,_=!h&&!g,v=er()?$n(n):n;h&&!f&&(v=rr(v));let y=e=>{v.write(e)},b=!1,{streamStoreHandle:x,streamStore:S,notificationStoreHandle:C,notificationStore:w,taskStoreHandle:T,taskStore:E,messageStoreHandle:D,messageStore:O,scrollStoreHandle:ee,budgetStore:te,contextStore:ne,perfStore:k,cacheStore:re,proxyStore:ie,compactionLogStore:A,galleryStore:ae,completer:j,shellBackendRef:oe,a2uiButtonsRef:se,a2uiActionRef:N,scanA2uiButtons:ce}=dg(e),le={toastTimer:null,listener:null,shellTimer:null},ue={current:null},de={current:null},fe=process.env.OTTO_TUI_PANE_BUFFER!==`0`,pe=`prompt`,me=()=>fe&&(E.getState().subagentContext!=null||E.getState().backgroundOutput!=null||E.getState().paneOwnsViewportFlag||pe!==`prompt`),he=fg({paneOwnsViewport:me,realWrite:e=>y(e)}),F=()=>{me()||he.flush()},ge=e=>{let t=pe===`prompt`;pe=e,e===`prompt`&&!t&&F()},_e=!0,ve=e=>{_e=e},ye=e=>{E.setState({paneOwnsViewportFlag:e}),e||F()},be={msg:0,perm:0,toast:0,notify:0},xe=new Map,Se=new Map,Ce={select:null,input:null,inputAction:null,questions:null,confirm:null,cancel:null,extra:null,alert:null,prompt:null,onboarding:null},we={current:null},I={current:null},L=(e=>I.current?I.current.openModal(e):e.kind===`input`?Promise.resolve(null):void 0),Te=Oc({listener:()=>le.listener?.(),intervalMs:i}),Ee=()=>Te.immediate();T.setNotify(Ee),C.setNotify(Ee);let{commitToHistory:De,commitManyToHistory:Oe}=Xg({scrollbackBuffer:he,getColumns:()=>o,getHasHistory:()=>b,setHasHistory:e=>{b=e},notify:Ee}),{streamTextCoalescer:ke,streamThinkingCoalescer:Ae,outputTokensThrottle:je,resetController:Me}=Jg({streamStore:S,messageStore:O,messageStoreHandle:D,scrollbackBuffer:he,scrollbackMode:h,coalesceMs:i,getColumns:()=>o,getHasHistory:()=>b,setHasHistory:e=>{b=e},getMsgCounter:()=>be.msg,incMsgCounter:()=>++be.msg,notify:Ee}),Ne=()=>Yi(Ji(Ki(e.isAgentBusy,S.getState().processing),!!w.getState().errorRetry),!!e.isPaused?.()),Pe=(t,n,r)=>{let i=Xi(t,n,r??!1,{processing:Ne(),isImmediateCommand:t=>e.isImmediateCommand?.(t)??!1,isInterruptCommand:t=>e.isInterruptCommand?.(t)??!1});if(i===`queue`){E.setState({queued:[...E.getState().queued,{text:t,mode:n}]}),Ee();return}e.onSubmit?.(t,n,i===`steer`?`steer`:`send`)},Fe=p_(le,Ne,Ee,e.onSubmit,E);T.setEffects({syncForcedUpgradeRoute:e=>Wr(M(),Rr,e),backgroundOutputRoute:e=>{e?M()?.navigate(`/pane/delegates/output`):M()?.currentPath===`/pane/delegates/output`&&M()?.goBack()},flushScrollbackIfIdle:F,registerStatusItems:e=>Vo(`cli-status`,{pluginId:`cli-status`,statusItems:[...e]})}),C.setEffects({drainQueueOnResume:()=>Fe(),syncPulseSurveyRoute:e=>Wr(M(),Lr,e)});let{onPermissionDecision:Ie,onSelectResolve:Le,onInputResolve:Re,onOnboardingResolve:ze,onInputAction:Be,onQuestionsResolve:Ve,onConfirmResolve:He,onAlertResolve:Ue,onPromptResolve:We,getTurnMessagesFor:Ge}=f_({getMessages:()=>O.getState().messages},Se,Ce,E,ye),Ke={state:le,columnsRef:{get current(){return o},set current(e){o=e}},rowsRef:{get current(){return s},set current(e){s=e}},hasHistoryRef:{get current(){return b},set current(e){b=e}},inkWriteRef:{get current(){return y},set current(e){y=e}},toastCounterRef:{get current(){return be.toast},set current(e){be.toast=e}},languageRef:{get current(){return c},set current(e){c=e}},systemTheme:l,themeRegistry:u,presetSelection:d,stopRef:{},taskStore:E,notificationStore:w,messageStore:O,streamStoreHandle:x,taskStoreHandle:T,notificationStoreHandle:C,messageStoreHandle:D,budgetStore:te,contextStore:ne,perfStore:k,cacheStore:re,proxyStore:ie,compactionLogStore:A,galleryStore:ae,opts:e,notify:Ee,flushScrollbackIfIdle:F,setPaneOwnsViewport:ye,setFocusOwnerForBuffer:ge,setScrollActive:ve,getTurnMessagesFor:Ge,submitOrQueue:Pe,onPermissionDecision:Ie,onSelectResolve:Le,onInputResolve:Re,onOnboardingResolve:ze,onInputAction:Be,onQuestionsResolve:Ve,onConfirmResolve:He,onAlertResolve:Ue,onPromptResolve:We,proxyOpenModal:L,restoreInputRef:ue,pasteBridgeRef:de,registryRef:we,shellBackendRef:oe,a2uiButtonsRef:se,a2uiActionRef:N,scrollbackMode:h,windowMode:_,scrollStore:ee,stdout:n},qe=()=>m_(Ke),Je=d_({stdout:v,enabled:!0}),Ye=Rg(e=>{ee.dispatchWheel(e)||pe===`prompt`&&_e&&ee.scrollBy(e*3)}),Xe={current:null};$l(ee.store,()=>Xe.current?.clear());let{renderStdin:Ze,kittyOn:Qe,focusOn:$e,mouseOn:et,kittyExitHandler:tt,focusExitHandler:rt,mouseExitHandler:it,setMouseEnabled:at,isMouseEnabled:ot,cleanup:st}=y_({stdin:t,renderStdout:v,onInterrupt:e.onInterrupt,onFocusChange:e.onFocusChange,onMouseWheel:e=>Ye.push(e),onMouseDrag:e=>{Xe.current?.handleDrag(e)},onTerminalBgDetected:e=>{process.env.OTTO_DEBUG_THEME&&process.stderr.write(`[RFC-282] OSC detected: ${e} themeRef=${!!nt()}\n`),nt()?.setSystemTheme(e)}}),ct=e.concurrent??process.env.OTTO_TUI_CONCURRENT===`1`;f&&p.enter();let lt=await Tg(v);lt&&(Xe.current=Mg({buffer:lt.buffer,terminalRows:()=>m(),writeSelectionRepaint:e=>{if(e)try{v.write(e)}catch{}},writeClipboard:e=>{let t=Bg(e),n=!1;try{Kn(e),n=!0}catch{n=!1}return t||n},onCopied:(e,t)=>{let n=Ng(e);t?(E.setState({clipboardChars:n,clipboardText:e,clipboardFailed:!1}),setTimeout(()=>{E.getState().clipboardChars===n&&E.setState({clipboardChars:0})},b_)):(E.setState({clipboardFailed:!0,clipboardChars:0}),setTimeout(()=>{E.getState().clipboardFailed&&E.setState({clipboardFailed:!1})},b_))}}),Zl(Xe.current),lt.onDamage(e=>{Xe.current?.onFrameDamage(e)}));let{waitUntilExit:R,unmount:ut}=Ft(V.createElement(qe),{stdout:v,stdin:Ze,exitOnCtrlC:!1,maxFps:a,concurrent:ct});ct&&await new Promise(e=>{let t=Date.now()+1e3,n=()=>{le.listener||Date.now()>t?e():setImmediate(n)};n()});let z=Kg({stdin:t,stdout:n,renderStdout:v,kittyOn:Qe,kittyExitHandler:tt,focusOn:$e,focusExitHandler:rt,mouseOn:et,mouseExitHandler:it,onInterrupt:e.onInterrupt,unmount:()=>ut(),terminalInputCleanup:st});z.setupRawInput(),Je.start();let dt=()=>Je.pollNow();n.on(`resize`,dt),process.once(`exit`,()=>{n.removeListener(`resize`,dt),Je.stop()});let ft={stopped:!1,unmounted:!1},pt=Zg({taskStore:E,notificationStore:w,cacheStore:re,proxyStore:ie,resolvers:Ce,getNotifyStats:()=>Te.getStats(),flushScrollbackIfIdle:F,paneOwnsViewport:me,setPaneOwnsViewport:ye});I.current=pt;let mt=Qg({taskStore:E,state:le,notify:Ee,showToast:(...e)=>Et.info.showToast(...e)}),ht=$g({notificationStore:w,state:le,counters:be,notify:Ee}),gt=r_({pendingMethods:e_({taskStore:E,messageStoreHandle:D,counters:be,pendingSteerMsgIds:xe,scrollbackMode:h,commitToHistory:De,scanA2uiButtons:ce,notify:Ee}),restoreInputRef:ue,pasteBridgeRef:de}),_t=a_({messageStoreHandle:D,notify:Ee}),vt=i_({lifecycleFlags:ft,scrollbackBuffer:he,streamTextCoalescer:ke,streamThinkingCoalescer:Ae,notifyScheduler:Te,state:le,registryUnregisterAll:Uo,unmount:ut,windowMode:_,scopedViewport:f,hasHistoryRef:{set:e=>{b=e}},resetStreamController:Me,messageStoreHandle:D,scrollStoreHandle:ee,streamStoreHandle:x,taskStoreHandle:T,notificationStoreHandle:C,perfStore:k,contextStore:ne,budgetStore:te,taskStore:E,notificationStore:w,a2uiButtonsRef:se,resetStatusWidgetBreakers:ou,getRouterRef:M,overlayPaths:Hr,syncOverlayRoute:Wr,notify:Ee,i18next:B,detectLanguage:Ct,setLanguage:e=>{c=e},getThemeRef:nt,setTerminalTitle:Hn,onStop:r,detachSessionSource:_t.detachSessionSource}),yt=c_({modalHandleMethods:pt,taskStore:E,getRouterRef:M,syncOverlayRoute:Wr,overlayServices:Br,flushScrollbackIfIdle:F,notify:Ee}),bt=l_({taskStore:E,taskStoreHandle:T,registerPlugin:Vo,registryUnregister:Ho,computeStalePluginIds:Ko,getRegistrySnapshot:Wo,getStatusItems:Jo,getStatusWidgets:Xo,resetStatusWidgetBreakers:ou,registryRef:we,a2uiButtonsRef:se,subagentRestoreFields:Co,notify:Ee}),xt=u_({notificationMethods:ht,notifyScheduler:Te,taskStore:E,modalHandleMethods:pt,shellMethods:mt,contextStore:ne,getRouterRef:M,scrollStoreHandle:ee}),wt=s_({streamMethods:t_({streamStore:S,streamTextCoalescer:ke,streamThinkingCoalescer:Ae,outputTokensThrottle:je,perfStore:k,compactionLogStore:A,drainQueue:Fe,getRouterRef:M,notify:Ee}),taskStore:E,notificationStore:w,notificationMethods:ht,getRouterRef:M,syncOverlayRoute:Wr,overlayPause:Pr,drainQueue:Fe,notify:Ee}),Tt=o_({scrollbackMode:h,commitToHistory:De,commitManyToHistory:Oe,messageStoreHandle:D,counters:be,getTurnMessagesFor:Ge,taskStore:E,notify:Ee,scanA2uiButtons:ce}),Et={modal:n_({modalHandleMethods:pt,permResolvers:Se,counters:be,taskStore:E,getRouterRef:M,notify:Ee,onConfirmResolve:He}),pending:gt,lifecycle:{...vt,..._t,toggleMouse:()=>{let e=at(!ot());return Et.info.showToast(B.t(`mouse.toggleTitle`),e?B.t(`mouse.enabledBody`,{modifier:Zd()}):B.t(`mouse.disabledBody`)),e}},messages:Tt,engine:wt,panes:yt,plugins:bt,info:xt,shell:mt,stores:{tasks:T.actions,budget:{setBudget:te.setBudget},context:{setBudget:ne.setBudget,addTurn:ne.addTurn,markTurns:ne.markTurns},cache:{setView:re.setView},proxy:{setView:ie.setView},notification:{setProviderUsage:C.setProviderUsage,setPausePending:C.setPausePending,setPaused:C.setPaused,setPulseSurvey:C.setPulseSurvey}}};return Ke.stopRef.current=()=>Et.lifecycle.stop(),R().then(()=>{ft.unmounted||(ft.unmounted=!0,z.cleanup(),lt?.dispose(),ut(),p.active()||n.write(pg(m())),n.write(`\x1B[?25h`),p.exit())}),Et}function S_(){return{streamBuf:``,thinkBuf:``,turnStart:0,turnToolCount:0,lastTasks:[],messageIndex:0}}function C_(e,t){let n=[];e.forEach((e,t)=>{e?.role===`user`&&n.push(t)});let r=n.length,i=Math.max(t,r);if(r===0||i<=1)return[];let a=n[0],o=Array(i-1).fill(a);for(let e=0;e<r;e++){let t=i-r-1+e;t>=0&&t<o.length&&(o[t]=n[e])}return o}function w_(e){return e.filter(e=>e.status!==`done`&&e.status!==`skipped`&&e.status!==`failed`).length}function T_(e,t,n){if(t.length===0)return[...e];let r=[];e.forEach((e,t)=>{e?.role===`user`&&r.push(t)});let i=r.length,a=Math.max(n,i);if(i===0||a<=0)return[...e];let o=a-i+1,s=new Map;for(let e of t)s.set(e.turn,e);let c=new Map;for(let t of s.values()){if(t.turn<o||t.turn>a)continue;let n=t.turn-o,s=n+1<i?r[n+1]:e.length,{turn:l,...u}=t,d={role:`summary`,...u},f=c.get(s);f?f.push(d):c.set(s,[d])}if(c.size===0)return[...e];let l=[];for(let t=0;t<e.length;t++){l.push(e[t]);let n=c.get(t+1);n&&l.push(...n)}return l}function E_(e,t){let n=w_(t.lastTasks),r=e.stopReason??`completed`,i=r===`error`?`error`:r===`interrupted`?`interrupted`:n>0?`incomplete`:`done`,a={toolCount:t.turnToolCount,elapsedMs:t.turnStart>0?performance.now()-t.turnStart:0,tokensUsed:e.tokens??void 0,model:e.model||void 0,effort:e.effort||void 0,cacheHitRatio:e.cacheHitRatio??void 0};return i===`incomplete`?{...a,status:i,tasksDone:t.lastTasks.length-n,tasksTotal:t.lastTasks.length}:{...a,status:i}}function D_(e,t,n){let r=()=>{n.thinkBuf.trim()&&(t.pushMessage({role:`assistant`,content:[{type:`thinking`,thinking:n.thinkBuf}]}),n.messageIndex++),n.thinkBuf=``,t.pushEngineEvent({kind:`streamingThinking`,text:``})};switch(e.kind){case`prompt.start`:n.turnStart=performance.now(),n.turnToolCount=0,t.addTurnBoundary?.(n.messageIndex);return;case`prompt.end`:{n.thinkBuf.trim()&&(t.pushMessage({role:`assistant`,content:[{type:`thinking`,thinking:n.thinkBuf}]}),n.messageIndex++),n.streamBuf=``,n.thinkBuf=``,t.pushEngineEvent({kind:`streamingText`,text:``}),t.pushEngineEvent({kind:`streamingThinking`,text:``});let r={role:`summary`,...E_(e,n)};t.pushMessage(r),n.messageIndex++;return}case`stream.text.delta`:n.streamBuf+=e.delta,t.pushEngineEvent({kind:`streamingText`,text:n.streamBuf});return;case`stream.thinking.delta`:n.thinkBuf+=e.delta,t.pushEngineEvent({kind:`streamingThinking`,text:n.thinkBuf});return;case`stream.text.start`:r(),n.streamBuf=``;return;case`stream.text.end`:t.pushEngineEvent({kind:`streamingText`,text:``}),n.streamBuf=``;return;case`stream.thinking.start`:n.thinkBuf=``;return;case`stream.thinking.end`:r();return;case`tool.start`:t.pushEngineEvent({kind:`activeTool`,name:e.call.name});return;case`tool.end`:{if(t.pushEngineEvent({kind:`activeTool`,name:null}),n.turnToolCount++,e.suppressMessage)return;let r=e.call.arguments??{},i=r,a=i.command??i.path??i.file_path??i.pattern??i.query??JSON.stringify(r);t.pushMessage({role:`tool`,name:e.call.name,args:typeof a==`string`?a:JSON.stringify(a),argsObj:r,result:e.resultText,isError:e.isError}),n.messageIndex++;return}case`tasks.update`:n.lastTasks=e.tasks,t.setTasks(e.tasks,e.title);return;case`turn.budget`:t.pushEngineEvent({kind:`toolBudget`,toolTurnCount:e.toolTurnCount,maxToolTurns:e.maxToolTurns,outputTokens:e.outputTokens,outputTokenBudget:e.outputTokenBudget});return;case`delegate.update`:return}}function O_(e,t={}){for(let t of e){let e=t.role??`unknown`,n=t.content??[],r=Array.isArray(n)?n.filter(e=>e.type===`text`).map(e=>String(e.text??``)).join(`
108
+ `):String(n);if(e===`user`)process.stdout.write(`\x1b[34m▸ ${r}\x1b[0m\n`);else if(e===`assistant`){process.stdout.write(`${r}\n`);let e=t.tool_calls??[];for(let t of e){let e=t.function;process.stdout.write(`\x1b[33m ⚙ ${e?.name??`unknown`}\x1b[0m\n`)}}else e===`system`?process.stdout.write(`\x1b[2m${r}\x1b[0m\n`):process.stdout.write(`${r}\n`)}}function k_(e,t){return{search:n=>Jt(e,n,t)}}function A_(){return{start(e){return()=>{}}}}function j_(e){let{transport:t,sessionId:n,onSessionEvent:r,hydrateMessages:i,onGap:a}=e;return{async start(e){let o=null,s=!1,c=!1,l=0,u=1,d=new Map,f=e=>{s||(o?.(),l=e,u=e+1,d.clear(),o=t.subscribe(n,e,e=>{if(!(s||e.seq<u||d.has(e.seq)))for(d.set(e.seq,e);d.has(u);){let e=d.get(u);d.delete(u),r(e),l=u,u+=1}},e=>{s||c||(a(e),p())}))},p=async()=>{if(!c){c=!0;try{let r=await t.fetchSnapshot(n);if(s)return;i(e,r.session.messages),f(r.cursor)}catch{a({reason:`gap`,oldestAvailable:l})}finally{c=!1}}};try{let r=await t.fetchSnapshot(n);if(s)return()=>{};i(e,r.session.messages),f(r.cursor)}catch(e){throw s=!0,e}return()=>{s=!0,o?.(),o=null}}}}function M_(e){let t=S_();return{handle(n){D_(n.payload,e,t)},reset(e=0){t={...S_(),messageIndex:e}}}}function N_(e){return{pushMessage:e.pushMessage,echoUserInput:e.echoUserInput,pushEngineEvent:e.pushEngineEvent,getNotifyStats:e.getNotifyStats,setTasks:e.setTasks,addTurnBoundary:e.addTurnBoundary}}export{Ol as AlertDialog,ag as App,ti as BASH_HISTFILE_SOURCE,Dl as BashPermissionDialog,Fn as BracketedPasteHandler,I as Button,lo as COMPACTING_SENTINEL,wt as CommandRegistry,Ve as ConfirmDialog,Ue as Cursor,Gr as DEFAULT_SENSITIVE_PATTERNS,ie as DIALOG_BORDER,Ye as DataList,R as FIGURES,ai as FISH_HISTFILE_SOURCE,xe as GroupDivider,cd as Home,fe as LAYOUT,ft as MeasuredText,hl as MemoryDialog,Fc as Message,ui as OTTO_SESSION_SOURCE,He as PALETTE,t as PANEL_BORDER,Cl as PermissionDialogDialog,kl as PromptDialog,Ai as PromptInput,ji as QueuedCommands,sl as REPLRegion,F as SPACING,dt as STATUS,Ec as STREAM_COALESCE_MS,ne as ScrollIndicatorAbove,f as ScrollIndicatorBelow,Dd as Segmented,Dd as Tabs,z as Select,xc as SigilPane,gd as Spinner,L as THEME,cg as TabScope,Be as Tabable,e as TextInput,x as ThemeRegistry,qr as ZSH_HISTFILE_SOURCE,nn as applySigilCompletion,xr as applySlashCompletion,Jn as beginSyncFrame,E_ as buildTurnSummary,$o as clearPluginRenderers,jc as collapseMessages,j_ as createAttachSessionDataSource,gu as createBudgetStore,Tt as createBuiltinCommands,me as createBuiltinThemeRegistry,_r as createCommandRegistry,k_ as createIncrementalSearcher,ir as createInputBuffer,or as createInputHistory,A_ as createLocalSessionDataSource,_i as createMergedHistoryProvider,gr as createPasteStore,kc as createQueryGuard,S_ as createReducerState,Qe as createSelectState,M_ as createSessionEventReduceBridge,N_ as createStoreTuiSink,Le as cycleIndex,C_ as deriveTurnBoundaries,Ct as detectLanguage,it as displayWidth,qi as effectiveBusy,Yn as endSyncFrame,gi as entriesToCommands,Nc as expandCollapsed,on as extractSigilPrefix,vr as extractSlashPrefix,Ao as formatAgentDiagnosticsText,pl as formatKeyValueLines,Dn as formatProviderUsageLimitTypeFull,fl as formatTranscriptText,Oo as formatTurnTimeline,yr as getCommandSuggestions,ut as getInputViewport,Je as getKillRingEntries,ja as getMarkdownThemeUserOverrides,rr as guardScrollbackStdout,at as handleEditingKey,Ie as handleEditingKeyExtended,B as i18next,St as initI18n,Cc as initStreamCommit,Fe as insertHistory,ye as insertHistorySequence,T_ as insertTurnSummaries,Kr as isSensitiveCommand,kn as isUsingOverage,Dc as makeCoalescer,Oc as makeNotifyScheduler,Gt as matchSubsequence,fi as mergeHistoryEntries,br as navigateSuggestions,ei as normalizeCommand,wo as observationLiveFields,Eo as observationRow,qn as osc52QuerySequence,Kn as osc52Write,Gn as osc8FilePath,Wn as osc8Hyperlink,ni as parseBashHistory,zn as parseExtendedKey,oi as parseFishHistory,Zr as parseZshHistory,Xe as pickInsertMode,qt as positionsToHighlightRanges,st as preWrapLine,Ce as preWrapLines,O_ as printMessages,wn as promptParentWorkspaceChoice,xn as promptWorkspaceTrust,Jt as rankCandidates,Yt as rankLabeledItems,Xt as rankNamedItems,D_ as reduceToTui,Qo as registerPluginRenderers,Ia as renderInline,Xa as renderMarkdownToLines,$s as renderMessageLines,be as resetKillRing,E as resolveHorizontalStep,Xi as routeSubmit,Sc as safeCommitBoundary,Qt as scoreSubsequence,Aa as setMarkdownThemeUserOverrides,er as shouldStripSyncOutput,ct as shouldUseViewport,Et as showCommandPalette,Gi as slashCommandName,x_ as startTui,wc as streamCommitStep,Ge as stringWidth,nr as stripScrollbackClear,Qn as stripSyncSequences,$n as stripSyncStdout,So as subagentEntryStatus,Co as subagentRestoreFields,xt as t,Mc as toggleCollapse,Z as useAppState,sg as useTabScope,Re as useTabable,Xn as withSyncFrame};
109
+ //# sourceMappingURL=index.js.map