@robota-sdk/agent-cli 3.0.1 → 3.0.2
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/CHANGELOG.md +5 -0
- package/dist/node/bin.js +5 -5
- package/dist/node/{cli-core-Cus9ebuT.js → cli-core-Cg4H6FH2.js} +315 -315
- package/dist/node/desktop-host.js +1 -1
- package/dist/node/headless.js +1 -1
- package/dist/node/host.js +1 -1
- package/dist/node/index.js +1 -1
- package/dist/node/node-DdB-oeq6.js.map +1 -1
- package/dist/node/{node-oHeP4vDn.js → node-DwQY2ITL.js} +3 -3
- package/dist/node/node-DwQY2ITL.js.map +1 -0
- package/dist/node/{node-BsDZQcvi.js → node-TUI6iwZA.js} +2 -2
- package/dist/node/{product-host-C-IQQ6ph.js → product-host-BsT1Xq4C.js} +358 -358
- package/dist/node/product-host-BsT1Xq4C.js.map +1 -0
- package/dist/node/{src-B9UMvThT-fOIUDLqp.js → src-B9UMvThT-B4p8y1ba.js} +1 -1
- package/dist/node/{src-B9UMvThT-C1A4E6i9.js → src-B9UMvThT-DInbihOf.js} +2 -2
- package/dist/node/{src-B9UMvThT-C1A4E6i9.js.map → src-B9UMvThT-DInbihOf.js.map} +1 -1
- package/dist/node/{src-BzaNFPZx-Cn-T7595.js → src-BzaNFPZx-E-faT9I-.js} +2 -2
- package/dist/node/{src-BzaNFPZx-Cn-T7595.js.map → src-BzaNFPZx-E-faT9I-.js.map} +1 -1
- package/dist/node/{src-BzaNFPZx-Df7aFS3N.js → src-BzaNFPZx-PaYEuPZc.js} +1 -1
- package/dist/node/{src-DwAfU-9z-DU29KIpt.js → src-DwAfU-9z-DLr4gyAc.js} +2 -2
- package/dist/node/{src-DwAfU-9z-DU29KIpt.js.map → src-DwAfU-9z-DLr4gyAc.js.map} +1 -1
- package/dist/node/{src-DwAfU-9z-B8gxThPt.js → src-DwAfU-9z-YAG_fVg1.js} +1 -1
- package/dist/node/{src-UPsd6jNY-DPPw_--T.js → src-UPsd6jNY-BT0Qq67D.js} +2 -2
- package/dist/node/{src-UPsd6jNY-DPPw_--T.js.map → src-UPsd6jNY-BT0Qq67D.js.map} +1 -1
- package/dist/node/{src-UPsd6jNY-B387swGC.js → src-UPsd6jNY-CPmh5JTO.js} +1 -1
- package/package.json +37 -37
- package/dist/node/node-oHeP4vDn.js.map +0 -1
- package/dist/node/product-host-C-IQQ6ph.js.map +0 -1
package/dist/node/bin.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
;(function(){var v=parseInt(process.versions.node.split('.')[0],10);if(v<22){process.stderr.write('\n✗ Node.js 22+ is required (current: '+process.version+')\n\nUpgrade:\n nvm: nvm install 22 && nvm use 22\n Volta: volta install node@22\n Download: https://nodejs.org/en/download\n\n');process.exit(1);}})();
|
|
3
|
-
import{D as e,Et as t,Ft as n,Rt as r,Vt as i,Y as a,nt as o,ut as s}from"./node-PhNl8kvo.js";import{A as c,C as l,D as u,E as d,F as f,H as p,I as m,L as h,M as g,N as _,O as v,P as ee,R as y,S as te,T as b,_ as ne,b as re,d as ie,g as ae,h as oe,j as se,k as ce,m as x,p as le,t as S,u as ue,v as de,w as C,x as w,y as fe,z as T}from"./cli-core-
|
|
3
|
+
import{D as e,Et as t,Ft as n,Rt as r,Vt as i,Y as a,nt as o,ut as s}from"./node-PhNl8kvo.js";import{A as c,C as l,D as u,E as d,F as f,H as p,I as m,L as h,M as g,N as _,O as v,P as ee,R as y,S as te,T as b,_ as ne,b as re,d as ie,g as ae,h as oe,j as se,k as ce,m as x,p as le,t as S,u as ue,v as de,w as C,x as w,y as fe,z as T}from"./cli-core-Cg4H6FH2.js";import{watch as pe}from"node:fs";import{basename as me,dirname as he,join as ge}from"node:path";import{mkdir as _e,readFile as E,writeFile as ve}from"node:fs/promises";import{Readable as ye}from"node:stream";import D,{Chalk as be,backgroundColorNames as xe,foregroundColorNames as O}from"chalk";import{Box as k,Static as Se,Text as A,render as Ce,useApp as we,useBoxMetrics as j,useCursor as Te,useInput as Ee,usePaste as De,useStdout as Oe,useWindowSize as ke}from"ink";import M,{createContext as N,useCallback as P,useContext as F,useEffect as I,useLayoutEffect as Ae,useMemo as L,useRef as R,useState as z}from"react";import{Fragment as B,jsx as V,jsxs as H}from"react/jsx-runtime";import je from"string-width";import{marked as Me}from"marked";import Ne from"marked-terminal";let Pe=null,Fe=!1,Ie=`robota`;function Le(){return Fe}const U=[`string-width`,`setCursorPosition`,`getStringWidth`,`slice`,`charCodeAt`];function Re(e,t){if(!t)return`rethrow`;let n=e.message??``;return U.some(e=>n.includes(e))?`ime-hint`:`guard-owned`}function ze(e){Pe=e}function Be(e,t){try{if(Pe){Pe.getSession().reportBackgroundError(e,t);return}}catch{}process.stderr.write(`\n[${Ie}] ${t}: ${e.message}\n`)}function Ve(e=`robota`){Ie=e,!Fe&&(Fe=!0,process.on(`unhandledRejection`,e=>{Be(e instanceof Error?e:Error(String(e)),`unhandled rejection`)}),process.on(`uncaughtException`,e=>{Be(e instanceof Error?e:Error(String(e)),`uncaught exception`)}))}let He=!1,Ue=`CLI`;function We(e){return`\n[${e}] CJK/IME input error — this is a known issue with macOS Terminal.app.\n Workaround: use iTerm2 (https://iterm2.com) or input your prompt in English.
|
|
4
4
|
Alternatively, use headless mode: -p "your prompt here"
|
|
5
5
|
|
|
6
6
|
`}function Ge(e){Ue=e,!He&&(He=!0,process.on(`uncaughtException`,e=>{let t=Re(e,Le());if(t===`ime-hint`){process.stderr.write(We(Ue));return}if(t!==`guard-owned`)throw e}))}const Ke=e=>typeof e==`string`,qe=e=>t=>t===void 0||e(t),Je={user:!0,"agent-wakeup":!0,peer:!0,external:!0},Ye={driverId:qe(Ke)};({...Ye}),{...Ye},{...Ye},{...Ye},{...Ye},{...Ye},{...Ye},{...Ye},{...Ye},Object.keys(Je);const Xe=new Set([`get-messages`,`get-history`,`get-context`,`get-status`,`get-commands`,`list-models`,`get-executing`,`get-pending`,`get-execution-workspace`,`read-execution-detail`,`get-agent-definitions`,`get-usage-report`,`list-sessions`,`get-background-tasks`,`get-background-task`,`get-background-job-groups`,`get-background-job-group`,`wait-background-job-group`,`read-background-task-log`,`get-settings`,`project-status`,`project-diff`,`project-memory`]);function Ze(e){return Xe.has(e)}const Qe=new Set([` `,`
|
|
@@ -16,7 +16,7 @@ import{D as e,Et as t,Ft as n,Rt as r,Vt as i,Y as a,nt as o,ut as s}from"./node
|
|
|
16
16
|
`);return r.length===0?{state:e,effect:{type:`none`}}:r.includes(`
|
|
17
17
|
`)&&n.canPaste?{state:e,effect:{type:`paste`,text:r,cursor:e.cursor}}:Yr(e,r)}function Vr(e,t,n){if(t===Fr||t.startsWith(Fr))return Kr(e,t);if(e.isPasting)return qr(e,t,n)}function Hr(e,t,n,r){if(n.ctrl===!0&&t===`c`||n.tab===!0)return{state:e,effect:{type:`none`}};if(n.ctrl===!0&&(t===`w`||t===`u`)){let n=t===`w`?`word`:`line`;return Jr(e,(n===`word`?Nr:Pr)(e.value,e.cursor),n)}if(n.return===!0)return{state:e,effect:{type:`submit`,value:e.value}};if(t.length>1&&(t.includes(`
|
|
18
18
|
`)||t.includes(`\r`))&&r.canPaste)return{state:e,effect:{type:`paste`,text:t.replace(/\r\n?/g,`
|
|
19
|
-
`),cursor:e.cursor}}}function Ur(e,t,n){if(t.upArrow===!0||t.downArrow===!0)return n.enableVerticalNavigation===!1?{state:e,effect:{type:`none`}}:Ar(e,t.upArrow===!0?`up`:`down`,n.availableWidth);if(t.leftArrow===!0)return jr(e,`left`);if(t.rightArrow===!0)return jr(e,`right`);if(t.backspace===!0||t.delete===!0)return Jr(e,Mr(e.value,e.cursor))}function Wr(e){if(!e||e.length===0)return``;let t=``;for(let n of e){let e=n.charCodeAt(0);e>31&&e!==127&&(t+=n)}return t}function Gr(e,t,n){return{value:e.slice(0,t)+n+e.slice(t),cursor:t+n.length}}function Kr(e,t){return{state:{...e,isPasting:!0,pasteBuffer:t.slice(5)},effect:{type:`none`}}}function qr(e,t,n){if(t!==Ir&&!t.includes(Ir))return{state:{...e,pasteBuffer:e.pasteBuffer+t},effect:{type:`none`}};let r=t.split(Ir)[0]??``;return Br({...e,isPasting:!1,pasteBuffer:``},e.pasteBuffer+r,n)}function Jr(e,t,n){return t===void 0?{state:e,effect:{type:`none`}}:{state:{...e,value:t.value,cursor:t.cursor},effect:{type:`change`,value:t.value,...n===void 0?{}:{deleted:t.deleted,deletedScope:n}}}}function Yr(e,t){let n=Wr(t);if(n.length===0)return{state:e,effect:{type:`none`}};let r=Gr(e.value,e.cursor,n);return{state:{...e,value:r.value,cursor:r.cursor},effect:{type:`change`,value:r.value}}}function Xr(){return{timer:null,isSubmitting:!1}}function Zr(e,t,n,r=50,i=setTimeout){e.isSubmitting||(e.isSubmitting=!0,e.timer=i(()=>{e.timer=null,e.isSubmitting=!1,n(t())},r))}function Qr(e,t=clearTimeout){e.timer!==null&&(t(e.timer),e.timer=null),e.isSubmitting=!1}function $r(e){let t=[...e.value],n=Math.min(Math.max(e.cursor,0),t.length),r=e.availableWidth!==void 0&&e.availableWidth>0?e.availableWidth:void 0,i=Or(t,n,r??2**53-1);return r===void 0?{x:e.absX+i,y:e.absY}:{x:e.absX+i%r,y:e.absY+Math.floor(i/r)}}function ei(e){return!(!e.capability||!e.hasMeasured||e.viewportRows<=0||e.frameHeight<=0||e.frameHeight>=e.viewportRows||e.y<0||e.y>=e.frameHeight)}function ti(e){if(e.yogaNode===void 0)return;let t=0,n=0,r=e,i=e;for(;r!==void 0;){let e=r.yogaNode?.getComputedLayout();t+=e?.left??0,n+=e?.top??0,i=r,r=r.parentNode}let a=i.yogaNode?.getComputedLayout().height??0;return{x:t,y:n,frameHeight:a}}function ni(e,t){return e===void 0||t===void 0?e===t:e.x===t.x&&e.y===t.y&&e.frameHeight===t.frameHeight}function ri(e){let{setCursorPosition:t}=Te(),n=j(e.boxRef),{rows:r}=ke(),[i,a]=z(void 0);I(()=>{let t=e.boxRef.current,n=t===null?void 0:ti(t);a(e=>ni(e,n)?e:n)});let o=i!==void 0&&e.enabled?$r({absX:i.x,absY:i.y,value:e.value,cursor:e.cursor,...e.availableWidth===void 0?{}:{availableWidth:e.availableWidth}}):void 0,s=o!==void 0&&i!==void 0&&ei({hasMeasured:n.hasMeasured,y:o.y,frameHeight:i.frameHeight,viewportRows:r,capability:e.enabled});return t(s&&o!==void 0?{x:o.x,y:o.y}:void 0),{realCursorActive:s}}const ii=N({armEchoRelease(){},write(e){process.stdout.write(e)}});function ai({port:e,children:t}){return V(ii.Provider,{value:e,children:t})}function oi(){return F(ii)}const si=N({});function ci({overrides:e,children:t}){return V(si.Provider,{value:e??{},children:t})}function li(){return F(si)}function ui({value:e,onChange:t,onSubmit:n,onPaste:r,placeholder:i=``,focus:a=!0,showCursor:o=!0,availableWidth:s,cursorHint:c=null,enableVerticalNavigation:l=!0,onDeletedText:u,keybindingContext:d=`text-input`}){let f=R(Lr(e)),[,p]=z(0),m=R(Xr());I(()=>()=>Qr(m.current),[]),f.current=Rr(f.current,e,c),fi({stateRef:f,onChange:t,onSubmit:n,onPaste:r,availableWidth:s,focus:a,enableVerticalNavigation:l,...u===void 0?{}:{onDeletedText:u},forceRender:p,deferState:m.current,keybindingContext:d});let h=q(),g=L(()=>J(h.text.muted),[h.text.muted]),_=R(null),v=li(),{realCursorActive:ee}=ri({boxRef:_,enabled:a&&o&&dt({override:v.imeCursorPositioning}),value:f.current.value,cursor:f.current.cursor,...s===void 0?{}:{availableWidth:s}});return V(k,{ref:_,children:V(nt,{children:_i(f.current.value,f.current.cursor,i,o&&a&&!ee,g)})})}function di(e,t){return e===`delete-backward`||e===`delete-word`||e===`delete-line`||t.key.return!==!0&&t.key.ctrl!==!0&&t.key.tab!==!0&&t.input.length>0}function fi(e){let t=oi();De(n=>{t.armEchoRelease(),hi(e,()=>Br(e.stateRef.current,n,mi(e)))},{isActive:e.focus}),Q(e.keybindingContext,(n,r,i,a,o)=>{let s=pi(o,n,r,i,a);s!==void 0&&(di(n[0],s)&&t.armEchoRelease(),hi(e,()=>zr(e.stateRef.current,s.input,s.key,mi(e))))},{isActive:e.focus,...e.keybindingContext===`autocomplete-menu`?{fallbackContext:`chat-input`}:{}})}function pi(e,t,n,r,i){let a=t[0];if(a===`submit`||a===`execute`)return{input:``,key:{return:!0}};if(!(e===`autocomplete-menu`&&i)){if(a===`cursor-left`)return{input:``,key:{leftArrow:!0}};if(a===`cursor-right`)return{input:``,key:{rightArrow:!0}};if(a===`cursor-up`)return{input:``,key:{upArrow:!0}};if(a===`cursor-down`)return{input:``,key:{downArrow:!0}};if(a===`delete-backward`)return{input:``,key:{backspace:!0}};if(a===`delete-word`)return{input:`w`,key:{ctrl:!0}};if(a===`delete-line`)return{input:`u`,key:{ctrl:!0}};if(!i)return r.ctrl!==!0&&r.meta!==!0&&!r.return&&!r.escape&&!r.tab&&!r.upArrow&&!r.downArrow&&!r.leftArrow&&!r.rightArrow&&!r.backspace&&!r.delete||r.ctrl===!0&&n===`c`||r.tab?{input:n,key:r}:void 0}}function mi(e){return{availableWidth:e.availableWidth,canPaste:e.onPaste!==void 0,enableVerticalNavigation:e.enableVerticalNavigation}}function hi(e,t){try{let n=t();e.stateRef.current=n.state,gi(e,n.effect)}catch{}}function gi(e,t){if(t.type===`change`)t.deleted!==void 0&&e.onDeletedText?.(t.deleted),e.onChange(t.value);else if(t.type===`submit`){let t=e.onSubmit;t&&Zr(e.deferState,()=>e.stateRef.current.value,t)}else t.type===`paste`?e.onPaste?.(t.text,t.cursor):t.type===`render`&&e.forceRender(e=>e+1)}function _i(e,t,n,r,i){let a=W(e),o=W(n);if(!r)return a.length>0?a:o?i(o):``;if(a.length===0)return o.length>0?D.inverse(o[0])+i(o.slice(1)):D.inverse(` `);let s=[...a],c=``;for(let e=0;e<s.length;e++){let n=s[e]??``;c+=e===t?D.inverse(n):n}return t>=s.length&&(c+=D.inverse(` `)),c}const vi=`Prompt from an external link`;function yi(e){if(e.length!==0)return e.length>1e3?`${vi} — ${e.length} characters; scroll and review the full text before sending`:vi}function bi({value:e}){let t=yi(e);return t===void 0?null:V(G,{dimColor:!0,children:t})}function xi(){return{selectedIndex:null,draft:``}}function Si(e,t,n,r){if(t.length===0)return{value:e,cursorHint:e.length,state:n};if(r===`previous`){let r=n.selectedIndex===null?t.length-1:Math.max(0,n.selectedIndex-1),i=t[r]??e;return{value:i,cursorHint:i.length,state:{selectedIndex:r,draft:n.selectedIndex===null?e:n.draft}}}if(n.selectedIndex===null)return{value:e,cursorHint:e.length,state:n};if(n.selectedIndex<t.length-1){let r=n.selectedIndex+1,i=t[r]??e;return{value:i,cursorHint:i.length,state:{...n,selectedIndex:r}}}return{value:n.draft,cursorHint:n.draft.length,state:xi()}}function Ci(e,t){let n=t.trim();return n.length===0||e[e.length-1]===n?[...e]:[...e,n]}function wi(e){let t=[];for(let n of e){if(n.category!==`chat`||n.type!==`user`)continue;let e=n.data;typeof e?.content==`string`&&(t=Ci(t,e.content))}return t}function Ti(e,t,n){return t===0?0:n===`previous`?e>0?e-1:t-1:e<t-1?e+1:0}function Ei(e,t){if(
|
|
19
|
+
`),cursor:e.cursor}}}function Ur(e,t,n){if(t.upArrow===!0||t.downArrow===!0)return n.enableVerticalNavigation===!1?{state:e,effect:{type:`none`}}:Ar(e,t.upArrow===!0?`up`:`down`,n.availableWidth);if(t.leftArrow===!0)return jr(e,`left`);if(t.rightArrow===!0)return jr(e,`right`);if(t.backspace===!0||t.delete===!0)return Jr(e,Mr(e.value,e.cursor))}function Wr(e){if(!e||e.length===0)return``;let t=``;for(let n of e){let e=n.charCodeAt(0);e>31&&e!==127&&(t+=n)}return t}function Gr(e,t,n){return{value:e.slice(0,t)+n+e.slice(t),cursor:t+n.length}}function Kr(e,t){return{state:{...e,isPasting:!0,pasteBuffer:t.slice(5)},effect:{type:`none`}}}function qr(e,t,n){if(t!==Ir&&!t.includes(Ir))return{state:{...e,pasteBuffer:e.pasteBuffer+t},effect:{type:`none`}};let r=t.split(Ir)[0]??``;return Br({...e,isPasting:!1,pasteBuffer:``},e.pasteBuffer+r,n)}function Jr(e,t,n){return t===void 0?{state:e,effect:{type:`none`}}:{state:{...e,value:t.value,cursor:t.cursor},effect:{type:`change`,value:t.value,...n===void 0?{}:{deleted:t.deleted,deletedScope:n}}}}function Yr(e,t){let n=Wr(t);if(n.length===0)return{state:e,effect:{type:`none`}};let r=Gr(e.value,e.cursor,n);return{state:{...e,value:r.value,cursor:r.cursor},effect:{type:`change`,value:r.value}}}function Xr(){return{timer:null,isSubmitting:!1}}function Zr(e,t,n,r=50,i=setTimeout){e.isSubmitting||(e.isSubmitting=!0,e.timer=i(()=>{e.timer=null,e.isSubmitting=!1,n(t())},r))}function Qr(e,t=clearTimeout){e.timer!==null&&(t(e.timer),e.timer=null),e.isSubmitting=!1}function $r(e){let t=[...e.value],n=Math.min(Math.max(e.cursor,0),t.length),r=e.availableWidth!==void 0&&e.availableWidth>0?e.availableWidth:void 0,i=Or(t,n,r??2**53-1);return r===void 0?{x:e.absX+i,y:e.absY}:{x:e.absX+i%r,y:e.absY+Math.floor(i/r)}}function ei(e){return!(!e.capability||!e.hasMeasured||e.viewportRows<=0||e.frameHeight<=0||e.frameHeight>=e.viewportRows||e.y<0||e.y>=e.frameHeight)}function ti(e){if(e.yogaNode===void 0)return;let t=0,n=0,r=e,i=e;for(;r!==void 0;){let e=r.yogaNode?.getComputedLayout();t+=e?.left??0,n+=e?.top??0,i=r,r=r.parentNode}let a=i.yogaNode?.getComputedLayout().height??0;return{x:t,y:n,frameHeight:a}}function ni(e,t){return e===void 0||t===void 0?e===t:e.x===t.x&&e.y===t.y&&e.frameHeight===t.frameHeight}function ri(e){let{setCursorPosition:t}=Te(),n=j(e.boxRef),{rows:r}=ke(),[i,a]=z(void 0);I(()=>{let t=e.boxRef.current,n=t===null?void 0:ti(t);a(e=>ni(e,n)?e:n)});let o=i!==void 0&&e.enabled?$r({absX:i.x,absY:i.y,value:e.value,cursor:e.cursor,...e.availableWidth===void 0?{}:{availableWidth:e.availableWidth}}):void 0,s=o!==void 0&&i!==void 0&&ei({hasMeasured:n.hasMeasured,y:o.y,frameHeight:i.frameHeight,viewportRows:r,capability:e.enabled});return t(s&&o!==void 0?{x:o.x,y:o.y}:void 0),{realCursorActive:s}}const ii=N({armEchoRelease(){},write(e){process.stdout.write(e)}});function ai({port:e,children:t}){return V(ii.Provider,{value:e,children:t})}function oi(){return F(ii)}const si=N({});function ci({overrides:e,children:t}){return V(si.Provider,{value:e??{},children:t})}function li(){return F(si)}function ui({value:e,onChange:t,onSubmit:n,onPaste:r,placeholder:i=``,focus:a=!0,showCursor:o=!0,availableWidth:s,cursorHint:c=null,enableVerticalNavigation:l=!0,onDeletedText:u,keybindingContext:d=`text-input`}){let f=R(Lr(e)),[,p]=z(0),m=R(Xr());I(()=>()=>Qr(m.current),[]),f.current=Rr(f.current,e,c),fi({stateRef:f,onChange:t,onSubmit:n,onPaste:r,availableWidth:s,focus:a,enableVerticalNavigation:l,...u===void 0?{}:{onDeletedText:u},forceRender:p,deferState:m.current,keybindingContext:d});let h=q(),g=L(()=>J(h.text.muted),[h.text.muted]),_=R(null),v=li(),{realCursorActive:ee}=ri({boxRef:_,enabled:a&&o&&dt({override:v.imeCursorPositioning}),value:f.current.value,cursor:f.current.cursor,...s===void 0?{}:{availableWidth:s}});return V(k,{ref:_,children:V(nt,{children:_i(f.current.value,f.current.cursor,i,o&&a&&!ee,g)})})}function di(e,t){return e===`delete-backward`||e===`delete-word`||e===`delete-line`||t.key.return!==!0&&t.key.ctrl!==!0&&t.key.tab!==!0&&t.input.length>0}function fi(e){let t=oi();De(n=>{t.armEchoRelease(),hi(e,()=>Br(e.stateRef.current,n,mi(e)))},{isActive:e.focus}),Q(e.keybindingContext,(n,r,i,a,o)=>{let s=pi(o,n,r,i,a);s!==void 0&&(di(n[0],s)&&t.armEchoRelease(),hi(e,()=>zr(e.stateRef.current,s.input,s.key,mi(e))))},{isActive:e.focus,...e.keybindingContext===`autocomplete-menu`?{fallbackContext:`chat-input`}:{}})}function pi(e,t,n,r,i){let a=t[0];if(a===`submit`||a===`execute`)return{input:``,key:{return:!0}};if(!(e===`autocomplete-menu`&&i)){if(a===`cursor-left`)return{input:``,key:{leftArrow:!0}};if(a===`cursor-right`)return{input:``,key:{rightArrow:!0}};if(a===`cursor-up`)return{input:``,key:{upArrow:!0}};if(a===`cursor-down`)return{input:``,key:{downArrow:!0}};if(a===`delete-backward`)return{input:``,key:{backspace:!0}};if(a===`delete-word`)return{input:`w`,key:{ctrl:!0}};if(a===`delete-line`)return{input:`u`,key:{ctrl:!0}};if(!i)return r.ctrl!==!0&&r.meta!==!0&&!r.return&&!r.escape&&!r.tab&&!r.upArrow&&!r.downArrow&&!r.leftArrow&&!r.rightArrow&&!r.backspace&&!r.delete||r.ctrl===!0&&n===`c`||r.tab?{input:n,key:r}:void 0}}function mi(e){return{availableWidth:e.availableWidth,canPaste:e.onPaste!==void 0,enableVerticalNavigation:e.enableVerticalNavigation}}function hi(e,t){try{let n=t();e.stateRef.current=n.state,gi(e,n.effect)}catch{}}function gi(e,t){if(t.type===`change`)t.deleted!==void 0&&e.onDeletedText?.(t.deleted),e.onChange(t.value);else if(t.type===`submit`){let t=e.onSubmit;t&&Zr(e.deferState,()=>e.stateRef.current.value,t)}else t.type===`paste`?e.onPaste?.(t.text,t.cursor):t.type===`render`&&e.forceRender(e=>e+1)}function _i(e,t,n,r,i){let a=W(e),o=W(n);if(!r)return a.length>0?a:o?i(o):``;if(a.length===0)return o.length>0?D.inverse(o[0])+i(o.slice(1)):D.inverse(` `);let s=[...a],c=``;for(let e=0;e<s.length;e++){let n=s[e]??``;c+=e===t?D.inverse(n):n}return t>=s.length&&(c+=D.inverse(` `)),c}const vi=`Prompt from an external link`;function yi(e){if(e.length!==0)return e.length>1e3?`${vi} — ${e.length} characters; scroll and review the full text before sending`:vi}function bi({value:e}){let t=yi(e);return t===void 0?null:V(G,{dimColor:!0,children:t})}function xi(){return{selectedIndex:null,draft:``}}function Si(e,t,n,r){if(t.length===0)return{value:e,cursorHint:e.length,state:n};if(r===`previous`){let r=n.selectedIndex===null?t.length-1:Math.max(0,n.selectedIndex-1),i=t[r]??e;return{value:i,cursorHint:i.length,state:{selectedIndex:r,draft:n.selectedIndex===null?e:n.draft}}}if(n.selectedIndex===null)return{value:e,cursorHint:e.length,state:n};if(n.selectedIndex<t.length-1){let r=n.selectedIndex+1,i=t[r]??e;return{value:i,cursorHint:i.length,state:{...n,selectedIndex:r}}}return{value:n.draft,cursorHint:n.draft.length,state:xi()}}function Ci(e,t){let n=t.trim();return n.length===0||e[e.length-1]===n?[...e]:[...e,n]}function wi(e){let t=[];for(let n of e){if(n.category!==`chat`||n.type!==`user`)continue;let e=n.data;typeof e?.content==`string`&&(t=Ci(t,e.content))}return t}function Ti(e,t,n){return t===0?0:n===`previous`?e>0?e-1:t-1:e<t-1?e+1:0}function Ei(e,t){if(d(e)&&e.slice(1).includes(` `)){let{name:n}=b(e);return{type:`insert`,value:`/${n} ${t.name} `}}return t.subcommands&&t.subcommands.length>0?{type:`insert`,value:`/${t.name} `,selectedIndex:0}:{type:`insert`,value:`/${t.name} `}}function Di(e,t){if(d(e)&&e.slice(1).includes(` `)){let{name:n}=b(e);return{type:`submit`,value:`/${n} ${t.name}`}}return t.subcommands&&t.subcommands.length>0&&t.runsBare!==!0?{type:`insert`,value:`/${t.name} `,selectedIndex:0}:{type:`submit`,value:`/${t.name}`}}function Oi(e,t,n,r){let i=r.split(`
|
|
20
20
|
`).length,a=`[Pasted text #${n} +${i} lines]`;return{value:e.slice(0,t)+a+e.slice(t),cursorHint:t+a.length,label:a,lineCount:i}}function ki(e){return e.trim().length>0}const Ai=[`all`,`session`,`project`];function ji(e){let t=Ai.indexOf(e);return Ai[(t+1)%Ai.length]??`all`}function Mi(e,t,n){switch(t){case`all`:return!0;case`session`:return e.sessionId===n.sessionId;case`project`:return e.project===n.project}}function Ni(e){let t=new Set,n=[];for(let r of e){let e=r.text.trim();t.has(e)||(t.add(e),n.push(r))}return n}function Pi(e,t){let n=t.toLowerCase();if(n.length===0)return e.map(e=>({entry:e,ranges:[]}));let r=[];for(let t of e){let e=t.text.toLowerCase(),i=[],a=0;for(;;){let t=e.indexOf(n,a);if(t===-1)break;i.push([t,t+n.length]),a=t+n.length}i.length>0&&r.push({entry:t,ranges:i})}return r}function Fi(e,t){let n=[],r=0;for(let[i,a]of t)i>r&&n.push({text:e.slice(r,i),matched:!1}),n.push({text:e.slice(i,a),matched:!0}),r=a;return r<e.length&&n.push({text:e.slice(r),matched:!1}),n}function Ii(e,t){return t<=8||e<8?0:Math.min(e-8+1,t-8)}function Li(e){return`${e} unreadable ${e===1?`line`:`lines`} skipped`}function Ri(e){let t=q(),{match:n,selected:r,rowNumber:i,color:a}=e,o=i===void 0?r?`> `:` `:xr(i),s=Fi(n.entry.text.replace(/\r\n|[\r\n]/gu,e=>e.length===2?` ↵`:`↵`),n.ranges);return H(G,{color:r?t.text.accent:void 0,dimColor:!r,wrap:`truncate-end`,children:[o,s.map((e,t)=>e.matched?V(G,{bold:!0,inverse:a,children:a?e.text:`[${e.text}]`},t):V(G,{children:e.text},t))]})}function zi({view:e}){let t=q();if(e.error!==void 0)return H(G,{color:t.text.error,children:[`History could not be read: `,e.error]});let n=[];return e.matches.length===0?n.push(e.loading?`loading…`:e.query.length===0?`no stored prompts yet`:`no match`):(n.push(`${e.matches.length} match${e.matches.length===1?``:`es`}`),e.loading&&n.push(`loading…`)),e.skippedLines>0&&n.push(Li(e.skippedLines)),V(G,{dimColor:!0,children:n.join(` · `)})}function Bi({view:e}){let t=q(),n=K(),r=ut(),i=Z(`history-search`,[[[`previous`,`next`],`Navigate`],[`cycle-scope`,`Scope`],[`insert`,`Insert`],[`execute`,`Run`],[`cancel`,`Close`]]);if(!e.open)return null;let a=Ii(e.selectedIndex,e.matches.length),o=e.matches.slice(a,a+8);return H(k,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.muted},paddingX:1,children:[H(G,{children:[V(G,{color:t.text.accent,children:`(reverse-i-search)`}),` scope: `,e.scope,` · query:`,` `,e.query]}),o.map((t,i)=>V(Ri,{match:t,selected:a+i===e.selectedIndex,rowNumber:n?a+i:void 0,color:r},`${t.entry.at}:${a+i}`)),V(zi,{view:e}),V(Y,{hints:i})]})}function Vi(e){if(!e.startsWith(`/`))return{isSlash:!1,parentCommand:``,filter:``};let t=e.slice(1),n=t.indexOf(` `);return n===-1?{isSlash:!0,parentCommand:``,filter:t}:{isSlash:!0,parentCommand:t.slice(0,n),filter:t.slice(n+1)}}function Hi(e,t){let[n,r]=z(0),[i,a]=z(!1),o=M.useRef(e);o.current!==e&&(o.current=e,i&&a(!1));let s=Vi(e),c=s.isSlash&&s.parentCommand.length>0,l=M.useRef(s.parentCommand);I(()=>{l.current!==s.parentCommand&&(l.current=s.parentCommand,r(0))},[s.parentCommand]);let u=L(()=>{if(!t||!s.isSlash||i)return[];if(c){let e=t.getSubcommands(s.parentCommand);if(e.length===0)return[];if(!s.filter)return e;let n=s.filter.toLowerCase();return e.filter(e=>e.name.toLowerCase().startsWith(n))}return t.getCommands(s.filter)},[t,s.isSlash,s.parentCommand,s.filter,i,c]),d=s.isSlash&&u.length>0&&!i;return n>=u.length&&u.length>0&&r(u.length-1),{showPopup:d,filteredCommands:u,selectedIndex:n,setSelectedIndex:r,isSubcommandMode:c,setShowPopup:e=>{a(typeof e==`function`?t=>!e(!t):!e)}}}const Ui={entries:[],skippedLines:0};function Wi(e,t){let n=t.ctrl===!0||t.meta===!0||!!(t.return||t.escape||t.tab)||!!(t.upArrow||t.downArrow||t.leftArrow||t.rightArrow)||!!(t.backspace||t.delete);return e.length>0&&!n}function Gi(e,t){return[...e].reverse().map(e=>({at:``,sessionId:t.sessionId,project:t.project,text:e}))}const Ki=()=>new Promise(e=>setImmediate(e));async function qi(e){try{for await(let t of e.source.read({signal:e.signal})){if(e.signal.aborted)return;e.pending.current={entries:[...e.pending.current.entries,...t.entries],skippedLines:e.pending.current.skippedLines+t.skippedLines},e.publishEachBlock&&(e.publish(),await Ki())}e.signal.aborted||e.publish()}catch(t){e.signal.aborted||e.setError(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||e.setLoading(!1)}}function Ji(e,t){let[n,r]=z(Ui),[i,a]=z(!1),[o,s]=z(void 0),c=R(void 0),l=R(Ui),u=P(()=>r(l.current),[]),d=P(()=>{c.current?.abort(),c.current=void 0,a(!1)},[]),f=P(()=>{if(d(),l.current=Ui,r(Ui),s(void 0),e===void 0)return;let n=new AbortController;c.current=n,a(!0),qi({source:e.source,signal:n.signal,pending:l,publishEachBlock:!t,publish:u,setError:s,setLoading:a})},[u,t,d,e]);return I(()=>d,[d]),{loaded:n,loading:i,error:o,start:f,stop:d,publish:u}}function Yi(e){let t=t=>{e.setQuery(t),e.setSelectedIndex(0),e.screenReader&&e.loader.publish()},n=t=>{let n=e.matches[e.selected]?.entry.text;n!==void 0&&(e.close(),(t===`insert`?e.onInsert:e.onExecute)(n))},r=t=>{e.matches.length!==0&&e.setSelectedIndex((e.selected+t+e.matches.length)%e.matches.length)};Q(`history-search`,(i,a,o,s)=>{let c=i[0];c===`cancel`?e.close():c===`insert`||c===`execute`?n(c):c===`previous`?r(-1):c===`next`?r(1):c===`cycle-scope`?(e.setScope(ji(e.scope)),e.setSelectedIndex(0)):!s&&(o.backspace||o.delete)?t(e=>e.slice(0,-1)):!s&&Wi(a,o)&&t(e=>e+a)},{isActive:e.open})}function Xi(e,t,n,r,i){let a=t?.sessionId,o=t?.project;return L(()=>{if(!e||a===void 0||o===void 0)return[];let t={sessionId:a,project:o};return Ni(n===`session`?Gi(r,t):i.filter(e=>Mi(e,n,t)))},[i,e,o,n,a,r])}const Zi={query:``,scope:`all`,selectedIndex:0};function Qi(){let[e,t]=z(Zi);return{state:e,reset:P(()=>t(Zi),[]),setters:L(()=>({setScope:e=>t(t=>({...t,scope:e})),setSelectedIndex:e=>t(t=>({...t,selectedIndex:e})),setQuery:e=>t(t=>({...t,query:e(t.query)}))}),[])}}function $i(e,t,n,r){let[i,a]=z(!1);return{open:i,openSearch:P(()=>{!t||i||(n(),a(!0),r?.(!0),e.start())},[t,e,r,i,n]),closeSearch:P(()=>{e.stop(),a(!1),r?.(!1)},[e,r])}}function ea(e){let t=K(),n=Ji(e.surface,t),{state:r,reset:i,setters:a}=Qi(),{query:o,scope:s}=r,{surface:c,onInsert:l,onExecute:u}=e,{open:d,openSearch:f,closeSearch:p}=$i(n,c!==void 0,i,e.onOpenChange),m=Xi(d,c,s,e.sessionPrompts,n.loaded.entries),h=L(()=>Pi(m,o),[m,o]),g=Math.min(r.selectedIndex,Math.max(0,h.length-1));Yi({open:d,matches:h,selected:g,scope:s,screenReader:t,loader:n,close:p,onInsert:l,onExecute:u,...a});let{loading:_,error:v,loaded:ee}=n;return{view:{...r,open:d,selectedIndex:g,matches:h,loading:_,error:v,skippedLines:ee.skippedLines},openSearch:f,closeSearch:p}}function ta(e){let{historySearch:t,setValue:n,setCursorHint:r,submitPrompt:i,composerActive:a}=e,o=P(e=>{n(e),r(null)},[r,n]),s=P(e=>{n(``),i(e)},[n,i]),{view:c,openSearch:l,closeSearch:u}=ea({surface:t,sessionPrompts:e.sessionPrompts,onInsert:o,onExecute:s,onOpenChange:t?.onOpenChange});return Q(`chat-input`,e=>{e.includes(`history-search`)&&l()},{isActive:a&&!c.open&&t!==void 0}),I(()=>{c.open&&!a&&u()},[u,a,c.open]),c}function na(e){let{showPopup:t,isDisabled:n,filteredCommands:r,selectedIndex:i}=e;Q(`autocomplete-menu`,n=>{if(t){for(let t of n)if(t===`previous`||t===`next`)e.setSelectedIndex(e=>Ti(e,r.length,t));else if(t===`close`)e.setShowPopup(!1);else if(t===`accept`){let t=r[i];t&&e.tabCompleteCommand(t)}}},{isActive:t&&!n})}function ra(e){let{showPopup:t,isDisabled:n,isQueueCancellationDisabled:r,pendingPrompt:i,searchOpen:a}=e;na(e),Q(`chat-input`,t=>{let n=t.find(e=>e===`history-previous`||e===`history-next`);if(n===void 0)return;let r=n===`history-previous`?`previous`:`next`;if(r===`next`&&e.historyState.selectedIndex===null&&e.value.length===0){e.onRequestFocusBackgroundList?.();return}let i=Si(e.value,e.promptHistory,e.historyState,r);e.setValue(i.value),e.setCursorHint(i.cursorHint),e.setHistoryState(i.state)},{isActive:!t&&!n&&!i&&!a}),Q(`queued-prompt`,t=>{t.includes(`cancel`)&&i&&e.onCancelQueue?.()},{isActive:!!i&&!r})}function ia(e,t){if(t){let n=` "${t}" `,r=Math.max(0,e-n.length-2);return{left:`─`.repeat(r),label:n,right:`─`.repeat(2)}}return{left:`─`.repeat(e),label:``,right:``}}function aa(e){return`[deleted: ${e}]`}function oa({screenReader:e,innerWidth:t,borderColor:n,sessionName:r}){let i=q();if(e)return null;let a=ia(t,r);return H(G,{color:n,children:[a.left,a.label?V(G,{backgroundColor:n,color:i.text.onAccent,bold:!0,children:a.label}):null,a.right]})}function sa({screenReader:e,innerWidth:t,borderColor:n}){return e?null:V(G,{color:n,children:`─`.repeat(t)})}function ca({deleted:e}){return e===null?null:V(G,{children:aa(e)})}function la(){let{stdout:e}=Oe(),t=()=>Math.max(40,(e.columns??80)-4),[n,r]=z(t);return I(()=>{let n=()=>r(t());return e.on(`resize`,n),()=>{e.off(`resize`,n)}},[e]),n}function ua(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e.padEnd(t)}function da(e){let t=q(),{cmd:n,isSelected:r,showSlash:i,rowWidth:a,nameColWidth:o,rowNumber:s}=e,c=s===void 0?r?`> `:` `:xr(s),l=r?t.text.accent:void 0,u=!r,d=ua(n.name,o);return V(k,{width:a,children:V(G,{color:l,dimColor:u,wrap:`truncate-end`,children:i?`${c}/${d} ${n.description??``}`:`${c}${d} ${n.description??``}`})})}function fa({commands:e,selectedIndex:t,visible:n,isSubcommandMode:r}){let i=q(),a=la(),o=K(),s=Z(`autocomplete-menu`,[[[`previous`,`next`],`Navigate`],[`accept`,`Complete`],[`execute`,`Select`],[`close`,`Close`]]);if(!n||e.length===0)return null;let c=pa(t,e.length),l=e.slice(c,c+8),u=Math.min(20,Math.max(...l.map(e=>e.name.length)));return H(k,{flexDirection:`column`,...o?{}:{borderStyle:`round`,borderColor:i.border.muted},paddingX:1,children:[l.map((e,n)=>V(da,{cmd:e,isSelected:c+n===t,showSlash:!r,rowWidth:a,nameColWidth:u,...o?{rowNumber:c+n}:{}},e.name)),V(Y,{hints:s})]})}function pa(e,t){if(t<=8||e<8)return 0;let n=t-8;return Math.min(e-8+1,n)}const ma=/\[Pasted text #(\d+)(?: \+\d+ lines)?\]/g;function ha(e,t){return e.replace(ma,(e,n)=>t.get(Number(n))??``)}function ga({text:e}){let t=K(),n=q(),r=yt(),i=bt(),[a,o]=z(0);return I(()=>{if(!i)return;let e=setInterval(()=>{o(e=>e+1)},400);return()=>clearInterval(e)},[i]),t?V(G,{children:e}):i?V(G,{children:[...e].map((e,t)=>{let n=Math.floor(t/4),i=(a+n)%r.wave.length;return V(G,{color:r.wave[i],children:e},t)})}):V(G,{color:n.text.muted,children:e})}function _a({onSubmit:e,onCancelQueue:t,isDisabled:n,isQueueCancellationDisabled:r,isAborting:i,pendingPrompt:a,pendingCount:o,commandQueryPort:s,sessionName:c,history:l,onRequestFocusBackgroundList:u,historySearch:d,initialValue:f,consumeInitialValue:p,externalPromptOrigin:m}){let h=q(),[g,_]=z(f??``),[v]=z(m===!0?f??``:``);I(()=>{f!==void 0&&f.length!==0&&p?.()},[f,p]);let[ee,y]=z(null),te=K(),[b,ne]=z(null),[re,ie]=z(xi),[ae,oe]=z([]),se=L(()=>wi(l??[]),[l]),ce=L(()=>ae.reduce((e,t)=>Ci(e,t),se),[se,ae]),x=R(new Map),{columns:le}=ke(),S=le>0?le:80,ue=Math.max(1,S-3),de=R(0),C=Z(`chat-input`,[[`submit`,`Submit`]]),{showPopup:w,filteredCommands:fe,selectedIndex:T,setSelectedIndex:pe,isSubcommandMode:me,setShowPopup:he}=Hi(g,s),ge=P((e,t)=>{de.current+=1;let n=de.current;x.current.set(n,e),_(r=>{let i=Oi(r,t,n,e);return y(i.cursorHint),i.value})},[]),_e=P(()=>{ie(xi())},[]),E=P(e=>{oe(t=>Ci(t,e))},[]),ve=P(t=>{E(t),_e(),e(t)},[e,E,_e]),ye=P(e=>{let t=Ei(g,e);t.type===`insert`&&(_(t.value),t.selectedIndex!==void 0&&pe(t.selectedIndex))},[g,pe]),D=P(e=>{let t=Di(g,e);if(t.type===`insert`){_(t.value),t.selectedIndex!==void 0&&pe(t.selectedIndex);return}t.type===`submit`&&(_(``),ve(t.value))},[g,ve,pe]),be=P(e=>{if(!ki(e))return;if(w&&fe[T]){D(fe[T]);return}let t=ha(e.trim(),x.current);_(``),x.current.clear(),de.current=0,ve(t)},[w,fe,T,D,ve]),xe=ta({historySearch:d,sessionPrompts:ce,composerActive:!w&&!n&&!a,setValue:_,setCursorHint:y,submitPrompt:ve});ra({value:g,isDisabled:n,searchOpen:xe.open,isQueueCancellationDisabled:r??n,pendingPrompt:a,showPopup:w,setShowPopup:he,filteredCommands:fe,selectedIndex:T,setSelectedIndex:pe,tabCompleteCommand:ye,promptHistory:ce,historyState:re,setValue:_,setCursorHint:y,setHistoryState:ie,onRequestFocusBackgroundList:u,onCancelQueue:t});let O=i?h.border.attention:a?h.border.focused:n?h.border.muted:h.border.active,Se=Math.max(1,S-0);return H(k,{flexDirection:`column`,children:[w&&V(fa,{commands:fe,selectedIndex:T,visible:w,isSubcommandMode:me}),V(Bi,{view:xe}),V(ca,{deleted:te?b:null}),V(oa,{screenReader:te,innerWidth:Se,borderColor:O,...c===void 0?{}:{sessionName:c}}),V(k,{paddingLeft:1,children:i?V(G,{color:h.text.warning,children:` Interrupting...`}):a?H(G,{color:h.text.accent,children:[` `,`Queued:`,` `,a.length>50?a.slice(0,47)+`...`:a,` `,typeof o==`number`&&o>1&&H(G,{dimColor:!0,children:[`(+`,o-1,` co-driver queued) `]}),V(G,{dimColor:!0,children:`(Backspace to cancel)`})]}):n?V(ga,{text:` Waiting for response... (ESC to interrupt)`}):H(k,{children:[V(G,{color:h.text.success,bold:!0,children:`> `}),V(ui,{value:g,onChange:e=>{_(e),_e(),y(null)},onDeletedText:ne,onSubmit:be,onPaste:ge,placeholder:`Type a message or /help`,availableWidth:ue,cursorHint:ee,enableVerticalNavigation:!1,keybindingContext:w?`autocomplete-menu`:`chat-input`,focus:!xe.open})]})}),!te&&!n&&!a&&!xe.open&&V(Y,{hints:C}),V(sa,{screenReader:te,innerWidth:Se,borderColor:O}),v.length>0&&g===v&&V(bi,{value:g})]})}const va=new Set([`Shell`,`Bash`,`BackgroundProcess`]);function ya(e){if(!va.has(e.toolName)||!e.toolResultData)return;let t=ba(e.toolResultData),n=Oa(t,`exitCode`),r=ka(t,`success`),i=wa(Ca(xa(e.toolResultData,t))),a=i.slice(0,4).map(W),o=Math.max(0,i.length-a.length),s=e.result===`error`||r===!1||n!==void 0&&n!==0;return{status:s?`error`:`success`,statusLabel:Sa(s,n),previewLines:a,omittedLineCount:o,transcriptHint:o>0?`... +${o} lines (full output in session transcript)`:void 0}}function ba(e){try{return JSON.parse(e)}catch{return e}}function xa(e,t){if(!Ea(t))return e;let n=Da(t,`output`);if(n!==void 0)return n;let r=Da(t,`stdout`),i=Da(t,`stderr`),a=Da(t,`error`),o=[];return r&&o.push(r),i&&o.push(Ta(i,`[stderr] `)),!r&&!i&&a&&o.push(a),o.join(`
|
|
21
21
|
`)}function Sa(e,t){return t!==void 0&&t!==0?`exit ${t}`:e?`error`:`ok`}function Ca(e){return e?e.replace(/\r\n/g,`
|
|
22
22
|
`).split(`
|
|
@@ -28,10 +28,10 @@ import{D as e,Et as t,Ft as n,Rt as r,Vt as i,Y as a,nt as o,ut as s}from"./node
|
|
|
28
28
|
|
|
29
29
|
`)}\n\n`}}function Ba(e,t,n,r,i){let a=new ja(Ft(r.markdown),{ignoreIllegals:!0,theme:It(r.syntax)}),o=a.code.bind(a),s=Lt(r);return a.code=(n,r,a)=>Na(r)?La(n,e,t,s):i?o(n,r,a):`${n.split(`
|
|
30
30
|
`).map(e=>`${Aa}${e}`).join(`
|
|
31
|
-
`)}\n\n`,n&&za(a),a}function Va(e,t={}){let n=W(e),r=Me.parse(n,{renderer:Ba(Ma(t.color),t.codeBlockWidth,t.screenReader===!0,st(t.theme),t.syntaxHighlighting!==!1)});return typeof r==`string`?r.trimEnd():n}function Ha(){let e=vt(),t=xt(),n=K();return(r,i={})=>Va(r,{...i,theme:e,syntaxHighlighting:t,screenReader:n})}const Ua=/_[0-9a-f]{8}$/;function Wa(e,t=
|
|
31
|
+
`)}\n\n`,n&&za(a),a}function Va(e,t={}){let n=W(e),r=Me.parse(n,{renderer:Ba(Ma(t.color),t.codeBlockWidth,t.screenReader===!0,st(t.theme),t.syntaxHighlighting!==!1)});return typeof r==`string`?r.trimEnd():n}function Ha(){let e=vt(),t=xt(),n=K();return(r,i={})=>Va(r,{...i,theme:e,syntaxHighlighting:t,screenReader:n})}const Ua=/_[0-9a-f]{8}$/;function Wa(e,t=se){if(!e.startsWith(t))return W(e);let n=e.slice(t.length).replace(Ua,``);return W(n.length>0?n:e)}function Ga(e){return e===void 0?``:W(e)}const Ka=N(`Assistant`),qa=N(void 0);function Ja({name:e,modelCommandToolPrefix:t,children:n}){return V(Ka.Provider,{value:e?.trim()||`Assistant`,children:V(qa.Provider,{value:t,children:n})})}function Ya(){return F(Ka)}function Xa(){return F(qa)}const Za={user:`you:`,assistant:`assistant:`,thinking:`thinking:`,tool:`tool:`,toolError:`tool error:`,error:`error:`,warning:`warning:`,permissionRequired:`permission required:`,cost:`cost:`};function Qa(e){switch(e){case`user`:return Za.user;case`assistant`:return Za.assistant;case`tool`:return Za.tool;case`system`:return Za.warning}}function $a(e){return e===T?`You`:e}function eo({role:e,driverId:t}){let n=q(),r=K(),i=Ya();if(r)return H(G,{children:[e===`user`&&t!==void 0&&t!==T?`${t}:`:Qa(e),` `]});switch(e){case`user`:return H(G,{color:n.text.success,bold:!0,children:[t===void 0?`You`:$a(t),`:`,` `]});case`assistant`:return H(G,{color:n.text.accent,bold:!0,children:[i,`:`,` `]});case`system`:return H(G,{color:n.text.warning,bold:!0,children:[`System:`,` `]});case`tool`:return H(G,{color:n.text.emphasis,bold:!0,children:[`Tool:`,` `]})}}function to(e,t){if(t)return`error`;let n=e.result===`success`||e.result===`error`||e.result===`denied`?e.result:void 0;return un({toolName:e.toolName,firstArg:e.firstArg??``,isRunning:e.isRunning??!1,result:n})}function no(e,t,n){let r=Ga(e.firstArg);return`${cn[t]} ${Wa(e.toolName,n)}${r?`(${r})`:``}`}function ro({tool:e}){let t=q(),n=ya(e);if(!n||n.statusLabel===`ok`&&n.previewLines.length===0&&!n.transcriptHint)return null;let r=n.status===`error`?ln(t,`error`):t.text.emphasis;return H(k,{flexDirection:`column`,marginLeft:4,children:[n.statusLabel!==`ok`&&V(G,{color:r,dimColor:!0,children:n.statusLabel}),n.previewLines.map((e,t)=>V(G,{color:r,dimColor:!0,children:e},`${e}-${t}`)),n.transcriptHint&&V(G,{dimColor:!0,children:n.transcriptHint})]})}function io(e){let t=e.lines.length>12?oo(e.lines):e.lines,n=Math.max(...t.map(e=>e.lineNumber),0).toString().length,r=t.map(e=>ao(e,n)),i=e.lines.length>12;return{file:e.file,markdown:["```diff",...r,"```"].join(`
|
|
32
32
|
`),truncated:i,remainingLineCount:i?e.lines.length-t.length:0}}function ao(e,t){if(e.type===`hunk`)return e.text;let n=e.lineNumber.toString().padStart(t,` `);return e.type===`remove`?`- ${n} | ${e.text}`:e.type===`add`?`+ ${n} | ${e.text}`:` ${n} | ${e.text}`}function oo(e){let t=so(e),n=[];for(let e of t){if(n.length===0&&e.length>10)return e.slice(0,10);if(n.length+e.length>10)break;n.push(...e)}return n.length>0?n:e.slice(0,10)}function so(e){let t=[],n=[];for(let r of e){if(r.type===`hunk`&&n.length>0){t.push(n),n=[r];continue}n.push(r)}return n.length>0&&t.push(n),t}function co({file:e,lines:t}){let n=q(),r=Ha(),i=io({file:e,lines:t}),a=K()?``:`│ `;return H(k,{flexDirection:`column`,marginLeft:4,children:[i.file&&H(G,{color:n.text.emphasis,dimColor:!0,children:[a,W(i.file)]}),V(nt,{children:r(i.markdown)}),i.truncated&&H(G,{color:n.text.emphasis,dimColor:!0,children:[a,`... and `,i.remainingLineCount,` more lines`]})]})}function lo({entry:e}){let n=q(),r=e.data;if(!r)return V(B,{});let i=r.promptTokens===void 0?`?`:uo(r.promptTokens),a=r.completionTokens===void 0?`?`:uo(r.completionTokens),o=uo(r.totalTokens),s=r.source!==void 0&&r.source.scope!==`main`?r.source:void 0,c=s?s.label??s.id??s.scope:void 0,l=s?``:` · Context ${Math.round(r.contextUsedPercentage)}% (${t(r.contextUsedTokens)}/${t(r.contextMaxTokens)})`,u=r.costStatus===`unknown`?`cost unknown`:`cost ${r.costStatus}`;return V(k,{flexDirection:`column`,marginBottom:1,children:H(k,{children:[H(G,{color:n.text.emphasis,bold:!0,children:[c?`Usage (${c}):`:`Usage:`,` `]}),H(G,{dimColor:!0,children:[r.kind,` `,o,` tokens (in `,i,` / out `,a,`)`,l,` · `,u]})]})})}function uo(e){return e<1e3?e.toLocaleString():t(e)}function fo({kind:e,text:t,color:n}){return K()?H(G,{children:[Za[e],` `]}):V(G,{color:n,bold:!0,children:t})}function po({message:e}){let t=q(),n=Xa();if(!r(e))return V(B,{});let i=e.name,a=e.content,o=null;try{let e=JSON.parse(a);Array.isArray(e)&&e.length>0&&typeof e[0].line==`string`&&(o=e)}catch{}if(o)return H(k,{flexDirection:`column`,marginBottom:1,children:[H(k,{children:[V(fo,{kind:`tool`,text:`Tool: `,color:t.text.emphasis}),i&&H(G,{color:t.text.emphasis,dimColor:!0,children:[`[`,Wa(i,n),`]`]})]}),V(G,{children:` `}),o.map((e,n)=>H(k,{flexDirection:`column`,children:[H(G,{color:t.text.success,children:[` `,`✓`,` `,W(e.line)]}),e.diffLines&&e.diffLines.length>0&&V(co,{file:e.diffFile,lines:e.diffLines})]},n))]});let s=a.split(`
|
|
33
33
|
`).filter(e=>e.trim());return H(k,{flexDirection:`column`,marginBottom:1,children:[H(k,{children:[V(fo,{kind:`tool`,text:`Tool: `,color:t.text.emphasis}),i&&H(G,{color:t.text.emphasis,dimColor:!0,children:[`[`,W(i),`]`]})]}),V(G,{children:` `}),s.map((e,n)=>H(G,{color:t.text.success,children:[` `,`✓`,` `,W(e)]},n))]})}function mo({message:e}){let t=q(),n=W((e.content??``).replace(/^Error:\s*/,``));return H(k,{flexDirection:`column`,marginBottom:1,children:[V(k,{children:V(fo,{kind:`error`,text:`✖ Error: `,color:t.text.error})}),H(k,{marginLeft:2,flexDirection:`column`,children:[V(G,{color:t.text.error,wrap:`wrap`,children:n}),V(G,{dimColor:!0,wrap:`wrap`,children:`The session is still alive — type your next prompt when ready.`})]})]})}const ho=M.memo(function({message:e}){let t=Ha();if(r(e))return V(po,{message:e});if(e.role===`system`&&e.metadata?.kind===`error`)return V(mo,{message:e});let n=e.content??``,i=e.state===`interrupted`;return H(k,{flexDirection:`column`,marginBottom:1,children:[V(k,{children:V(eo,{role:e.role,...typeof e.metadata?.driverId==`string`?{driverId:e.metadata.driverId}:{}})}),V(G,{children:` `}),V(k,{marginLeft:2,children:o(e)?V(nt,{wrap:`wrap`,children:t(n+(i?`
|
|
34
34
|
|
|
35
35
|
_(interrupted)_`:``))}):V(G,{wrap:`wrap`,children:n})})]})});function go({entry:e}){let t=q(),n=Xa(),r=e.data,i=r?.tools,a=r?.summary?.split(`
|
|
36
|
-
`)??[];return i&&i.length>0?H(k,{flexDirection:`column`,marginBottom:1,children:[V(k,{children:V(fo,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),V(G,{children:` `}),i.map((e,r)=>{let i=to(e,ya(e)?.status===`error`);return H(k,{flexDirection:`column`,children:[H(G,{color:ln(t,i),children:[` `,no(e,i,n)]}),V(ro,{tool:e}),e.diffLines&&e.diffLines.length>0&&V(co,{file:e.diffFile,lines:e.diffLines})]},r)})]}):H(k,{flexDirection:`column`,marginBottom:1,children:[V(k,{children:V(fo,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),V(G,{children:` `}),a.map((e,n)=>H(G,{color:t.text.success,children:[` `,W(e)]},n))]})}function _o({entry:e}){let t=q(),n=e.data,r=typeof n?.message==`string`?n.message:typeof n?.content==`string`?n.content:void 0;if(r===void 0)return V(B,{});let i=W(r);return H(k,{flexDirection:`column`,marginBottom:1,children:[V(k,{children:V(fo,{kind:`warning`,text:`System: `,color:t.text.warning})}),V(G,{children:` `}),V(k,{marginLeft:2,children:V(G,{wrap:`wrap`,children:i})})]})}function vo({entry:e}){if(e.category===`chat`){let t=e.data;return V(ho,{message:t})}return e.type===`tool-summary`?V(go,{entry:e}):e.type===`usage-summary`?V(lo,{entry:e}):e.type===`tool-start`||e.type===`tool-end`?V(B,{}):V(_o,{entry:e})}const yo=[{keys:`↑↓`,label:`Navigate`},{keys:`Enter`,label:`Select`},{keys:`Esc`,label:`Cancel`}];function bo({items:e,renderItem:t,onSelect:n,onCancel:r,maxVisible:i=3,footerHints:a=yo,initialIndex:o=0}){let[s,c]=z(()=>{let t=o>=0&&o<e.length?o:0;return{...Pn(t),scrollOffset:Math.max(0,t-i+1)}}),l=R(s),u=P(t=>{let a=Ln(l.current,t,{itemCount:e.length,maxVisible:i});if(l.current=a.state,c(a.state),a.effect.type===`cancel`)r();else if(a.effect.type===`select`){let t=e[a.effect.index];t!==void 0&&n(t)}},[e,i,r,n]),d=K(),f=Gn({enabled:d&&e.length>0,itemCount:e.length,cancellable:!0,onSelect:t=>{let r=e[t];r!==void 0&&n(r)},onCancel:r});Q(`list-picker`,e=>e.forEach(u),{isActive:!d});let p=Z(`list-picker`,[[[`previous`,`next`],`Navigate`],[`select`,`Select`],[`cancel`,`Cancel`]]);if(e.length===0)return V(k,{});if(d){let n=br(e.length,!0);return H(k,{flexDirection:`column`,children:[e.map((e,n)=>H(k,{children:[V(G,{children:xr(n)}),t(e,!1)]},n)),H(G,{children:[n,f.buffer.length>0?` ${f.buffer}`:``]}),f.invalid&&V(G,{children:n})]})}let m=Rn(s,{itemCount:e.length,maxVisible:i});m!==s&&(l.current=m);let{selectedIndex:h,scrollOffset:g}=m,_=e.slice(g,g+i),v=g+i<e.length;return H(k,{flexDirection:`column`,children:[g>0&&H(G,{dimColor:!0,children:[` ↑ `,g,` more above`]}),_.map((e,n)=>V(k,{marginBottom:1,children:t(e,g+n===h)},g+n)),v&&H(G,{dimColor:!0,children:[` ↓ `,e.length-g-i,` more below`]}),V(Y,{hints:a===yo?p:a})]})}function xo({label:e,index:t,isCursor:n,isChecked:r,screenReader:i}){let a=q(),o=r?`[x] `:`[ ] `;return i?H(G,{children:[xr(t),o,e]}):H(G,{color:n?a.text.accent:void 0,children:[n?`> `:` `,o,e]})}function So(e){let{active:t,itemCount:n,setCursor:r}=e;Q(`multi-select`,t=>{for(let i of t)i===`previous`?r(e=>e<=0?n-1:e-1):i===`next`?r(e=>e>=n-1?0:e+1):i===`toggle`?e.onToggleAtCursor():i===`confirm`?e.onConfirm():i===`cancel`&&e.onCancel()},{isActive:t})}function Co(e){let t=Z(`multi-select`,[[[`previous`,`next`],`Navigate`],[`toggle`,`Toggle`],[`confirm`,e.canConfirm?`Confirm`:`Confirm (min ${e.minSelect})`],[`cancel`,`Cancel`]]);return e.screenReader?V(Sr,{itemCount:e.itemCount,cancellable:!0,buffer:e.numbered.buffer,invalid:e.numbered.invalid}):V(Y,{hints:t})}function wo(e){let t=q(),{title:n,description:r,options:i,cursor:a,selected:o,screenReader:s,numbered:c}=e;return H(k,{flexDirection:`column`,...s?{}:{borderStyle:`round`,borderColor:t.border.attention},paddingX:1,children:[V(G,{color:t.text.warning,bold:!0,children:n}),r!==void 0&&r.length>0&&V(G,{dimColor:!0,children:r}),i.map((e,t)=>V(xo,{label:e.label,index:t,isCursor:t===a,isChecked:o.has(e.value),screenReader:s},e.value)),V(Co,{screenReader:s,itemCount:i.length,numbered:c,canConfirm:e.canConfirm,minSelect:e.minSelect})]})}function To(e){let{options:t,minSelect:n,maxSelect:r,defaultValues:i,onConfirm:a}=e,[o,s]=z(0),[c,l]=z(()=>new Set(i??[]));return{cursor:o,setCursor:s,selected:c,toggleAt:e=>{let n=t[e];n!==void 0&&l(e=>{let t=new Set(e);return t.has(n.value)?t.delete(n.value):t.size<r&&t.add(n.value),t})},confirmIfAllowed:()=>{c.size>=n&&a([...c])}}}function Eo({title:e,description:t,options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o,onCancel:s}){let c=K(),{cursor:l,setCursor:u,selected:d,toggleAt:f,confirmIfAllowed:p}=To({options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o}),m=Gn({enabled:c,itemCount:n.length,cancellable:!0,multi:!0,onSelect:f,onConfirm:p,onCancel:s});So({active:!c,itemCount:n.length,setCursor:u,onToggleAtCursor:()=>f(l),onConfirm:p,onCancel:s});let h=d.size>=r;return V(wo,{title:e,...t===void 0?{}:{description:t},options:n,cursor:l,selected:d,screenReader:c,canConfirm:h,minSelect:r,numbered:m})}function Do(){return{value:``,resolved:!1}}function Oo(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:t.type===`cancel`?{state:{...e,resolved:!0},effect:{type:`cancel`}}:t.type===`delete`?{state:{...e,value:e.value.slice(0,-1),error:void 0},effect:{type:`none`}}:t.type===`insert`?{state:{...e,value:e.value+t.value,error:void 0},effect:{type:`none`}}:ko(e,n)}function ko(e,t){let n=e.value.trim();if(!n&&!t.allowEmpty){let r=t.validate?.(n);return{state:r?{...e,error:r}:e,effect:{type:`none`}}}let r=t.validate?.(n);return r===void 0?{state:{...e,resolved:!0},effect:{type:`submit`,value:n}}:{state:{...e,error:r},effect:{type:`none`}}}function Ao({title:e,description:t,placeholder:n,onSubmit:r,onCancel:i,validate:a,allowEmpty:o=!1,masked:s=!1}){let c=q(),[l,u]=z(()=>Do()),d=R(l),f=P(e=>{let t=Oo(d.current,e,{allowEmpty:o,validate:a});d.current=t.state,u(t.state),t.effect.type===`cancel`?i():t.effect.type===`submit`&&r(t.effect.value)},[o,a,i,r]),p=K();Q(`text-prompt`,(e,t,n,r)=>{for(let t of e)t===`submit`?f({type:`submit`}):t===`cancel`?f({type:`cancel`}):t===`delete-backward`&&f({type:`delete`});e.length===0&&!r&&t&&n.ctrl!==!0&&n.meta!==!0&&f({type:`insert`,value:t})});let m=Z(`text-prompt`,[[`submit`,`Submit`],[`cancel`,`Cancel`]]);return H(k,{flexDirection:`column`,...p?{}:{borderStyle:`round`,borderColor:c.border.attention},paddingX:1,children:[V(G,{color:c.text.warning,bold:!0,children:e}),V(jo,{description:t}),H(k,{marginTop:1,children:[V(G,{color:c.text.accent,children:`> `}),l.value?V(G,{children:s?`*`.repeat(l.value.length):l.value}):n?V(G,{dimColor:!0,children:n}):null,V(G,{color:c.text.accent,children:`█`})]}),l.error&&V(G,{color:c.text.error,children:l.error}),V(Y,{hints:m})]})}function jo({description:e}){return e===void 0||e.length===0?null:V(G,{dimColor:!0,children:e})}const Mo={value:``,label:`Type a custom answer…`};function No({request:e,onAnswer:t}){let n=q(),[r,i]=z(!1),a=e.options??[],o=a.length>0,s=e.maxSelect??1,c=()=>t({type:`cancelled`});if(!o||r)return V(Ao,{title:e.title,description:e.description,placeholder:e.placeholder,allowEmpty:e.allowEmpty,masked:e.masked,onSubmit:e=>t({type:`answer`,values:[],text:e}),onCancel:r?()=>i(!1):c},`text:${e.id}`);if(s>1)return V(Eo,{title:e.title,description:e.description,options:a,minSelect:e.minSelect??1,maxSelect:s,defaultValues:e.default?.values,onConfirm:e=>t({type:`answer`,values:e}),onCancel:c});let l=e.allowFreeText?[...a,Mo]:[...a],u=e.default?.values?.[0],d=u===void 0?0:Math.max(0,l.findIndex(e=>e.value===u));return H(k,{flexDirection:`column`,children:[V(G,{bold:!0,children:e.title}),e.description!==void 0&&e.description.length>0&&V(G,{dimColor:!0,children:e.description}),V(bo,{items:l,initialIndex:d,maxVisible:e.maxVisible,renderItem:(e,t)=>H(G,{color:t?n.text.accent:void 0,children:[t?`> `:` `,e.label]}),onSelect:e=>{e===Mo?i(!0):t({type:`answer`,values:[e.value]})},onCancel:c})]})}const Po=[`Allow [y]`,`Allow always (this session) [s]`,`Allow always (this project) [p]`,`Deny [n]`];function Fo(e,t=!0){return[Po[0],`Allow ${e} always (this session) [s]`,t?`Allow ${e} always (this project) [p]`:`Project-wide approval unavailable`,Po[3]]}function Io(e,t,n=!0){if(e.resolved)return{state:e,effect:{type:`none`}};if(typeof t!=`string`)return t.index===2&&!n?{state:e,effect:{type:`none`}}:Ro(e,t.index);let r=Ln(e,t,{itemCount:Po.length});return r.effect.type!==`select`||r.effect.index===2&&!n?{state:r.state,effect:{type:`none`}}:{state:r.state,effect:{type:`resolve`,decision:Lo(r.effect.index)}}}function Lo(e){return e===0?!0:e===1?`allow-session`:e===2&&`allow-project`}function Ro(e,t){return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`resolve`,decision:Lo(t)}}}function zo(e){let t=Object.entries(e);return t.length===0?`(no arguments)`:t.map(([e,t])=>`${e}: ${typeof t==`string`?t:JSON.stringify(t)}`).join(`, `)}function Bo({request:e,armDelayMs:t=450}){let n=q(),r=e.canPersistProjectPermission!==!1,[i,a]=M.useState(()=>Pn()),o=M.useRef(i),s=M.useRef(e);if(s.current!==e){s.current=e;let t=Pn();o.current=t,a(t)}let[c,l]=M.useState();M.useEffect(()=>{if(t<=0)return;let n=setTimeout(()=>l(e),t);return()=>clearTimeout(n)},[e,t]);let u=t<=0||c===e,d=M.useCallback(t=>{let n=Io(o.current,t,r);o.current=n.state,a(n.state),n.effect.type===`resolve`&&e.resolve(n.effect.decision)},[e,r]),f=K(),p=Fo(w(e.toolName,e.toolArgs),r),m=Gn({enabled:f&&u,itemCount:p.length,onSelect:t=>{let n=Io(o.current,{type:`shortcut`,index:t},r);o.current=n.state,a(n.state),n.effect.type===`resolve`&&e.resolve(n.effect.decision)}}),h=m.clear;M.useEffect(()=>h(),[e,h]),Q(`permission-prompt`,e=>{if(!u)return;let t={"allow-once":0,"allow-session":1,"allow-project":2,deny:3};for(let n of e)n in t?d({type:`shortcut`,index:t[n]}):(n===`previous`||n===`next`||n===`confirm`)&&d(n===`confirm`?`select`:n)},{isActive:!f});let g=Z(`permission-prompt`,[[[`previous`,`next`],`Navigate`],[`confirm`,`Confirm`]]),_=e.requester?.kind===`background-agent`?e.requester.label:void 0;return f?V(Cr,{title:Za.permissionRequired,description:`${_===void 0?``:`Background agent ${_} wants to run `}${e.toolName} — ${zo(e.toolArgs)}${e.requestedByPeer===void 0?``:` (requested by another session: ${e.requestedByPeer})`}`,options:p,buffer:m.buffer,invalid:m.invalid}):H(k,{flexDirection:`column`,borderStyle:`round`,borderColor:u?n.border.attention:n.border.muted,paddingX:1,children:[H(k,{children:[V(G,{color:n.text.warning,bold:!0,children:`[Permission Required]`}),u?null:V(G,{dimColor:!0,children:` keys answer in a moment`})]}),_===void 0?H(G,{children:[`Tool:`,` `,V(G,{color:n.text.accent,bold:!0,children:e.toolName})]}):H(G,{color:n.text.warning,children:[`Background agent `,V(G,{bold:!0,children:_}),` wants to run`,` `,V(G,{color:n.text.accent,bold:!0,children:e.toolName})]}),H(G,{dimColor:!0,children:[` `,zo(e.toolArgs)]}),e.requestedByPeer===void 0?null:H(G,{color:n.text.warning,children:[`Requested by another session: `,e.requestedByPeer]}),V(k,{marginTop:1,flexDirection:`column`,children:p.map((e,t)=>{let r=u&&t===i.selectedIndex;return V(k,{children:H(G,{color:r?n.text.accent:void 0,bold:r,dimColor:!u,children:[r?`> `:` `,e]})},e)})}),V(Y,{hints:g})]})}function Vo(){return{buffer:``,resolved:!1}}const Ho=[`y`,`yes`],Uo=[`n`,`no`];function Wo(e,t,n){if(e.resolved)return{state:e,effect:{type:`none`}};if(n.backspace===!0||n.delete===!0)return{state:{...e,buffer:e.buffer.slice(0,-1)},effect:{type:`none`}};if(n.return===!0){let t=e.buffer.trim().toLowerCase();return Ho.includes(t)?{state:{buffer:``,resolved:!0},effect:{type:`select`,index:0}}:Uo.includes(t)?{state:{buffer:``,resolved:!0},effect:{type:`select`,index:1}}:{state:{...e,buffer:``},effect:{type:`none`}}}return/^[a-zA-Z]+$/.test(t)?{state:{...e,buffer:e.buffer+t},effect:{type:`none`}}:{state:e,effect:{type:`none`}}}function Go(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:typeof t==`string`?Ln(e,t,{itemCount:n}):{state:{...e,selectedIndex:t.index,resolved:!0},effect:{type:`select`,index:t.index}}}function Ko({message:e,options:t=[`Yes`,`No`],onSelect:n}){let r=q(),[i,a]=z(()=>Pn()),o=R(i),s=P(e=>{let r=Go(o.current,e,t.length);o.current=r.state,a(r.state),r.effect.type===`select`&&n(r.effect.index)},[n,t.length]),c=K(),[l,u]=z(Vo),d=R(l);Ee((e,t)=>{let r=Wo(d.current,e,t);d.current=r.state,u(r.state),r.effect.type===`select`&&n(r.effect.index)},{isActive:c}),Q(`confirm-prompt`,e=>{for(let n of e)n===`choose-yes`&&t.length===2?s({type:`shortcut`,index:0}):n===`choose-no`&&t.length===2?s({type:`shortcut`,index:1}):(n===`previous`||n===`next`||n===`confirm`)&&s(n===`confirm`?`select`:n)},{isActive:!c});let f=Z(`confirm-prompt`,[[[`previous`,`next`],`Navigate`],[`confirm`,`Confirm`]]);return c?H(k,{flexDirection:`column`,children:[V(G,{children:e}),H(G,{children:[`Answer y or n and press Enter`,l.buffer.length>0?` ${l.buffer}`:``]})]}):H(k,{flexDirection:`column`,borderStyle:`round`,borderColor:r.border.attention,paddingX:1,children:[V(G,{color:r.text.warning,children:e}),V(k,{marginTop:1,children:t.map((e,t)=>V(k,{marginRight:2,children:H(G,{color:t===i.selectedIndex?r.text.accent:void 0,bold:t===i.selectedIndex,children:[t===i.selectedIndex?`> `:` `,e]})},e))}),V(Y,{hints:f})]})}function qo(e,t,n,r,i){let[a,o]=z([]),[s,c]=z(!1),[l,u]=z();return I(()=>{if(o([]),u(void 0),e===`marketplace-list`)c(!0),n.marketplaceList().then(e=>{let t=[{label:`Add Marketplace`,value:`__add__`}],n=e.map(e=>({label:e.name,value:e.name,hint:e.type}));o([...t,...n]),c(!1)}).catch(e=>{u(e instanceof Error?e.message:String(e)),c(!1)});else if(e===`marketplace-browse`){let e=t??``;c(!0),n.listAvailablePlugins(e).then(e=>{o(e.map(e=>({label:e.name,value:e.name,hint:e.installed?`installed`:e.description}))),c(!1)}).catch(e=>{u(e instanceof Error?e.message:String(e)),c(!1)})}else e===`installed-list`&&(c(!0),n.listInstalled().then(e=>{o(e.map(e=>({label:e.name,value:e.name,hint:e.description}))),c(!1)}).catch(e=>{u(e instanceof Error?e.message:String(e)),c(!1)}))},[i,e,t,n,r]),{items:a,loading:s,error:l}}function Jo({title:e,items:t,onSelect:n,onBack:r,loading:i,error:a}){let o=q(),[s,c]=z(()=>Pn()),l=R(s),u=!i&&!a,d=K(),f=Gn({enabled:d&&u,itemCount:t.length,cancellable:!0,onSelect:e=>{let r=t[e];r!==void 0&&n(r.value)},onCancel:r}),p=P(e=>{let i=Ln(l.current,e,{itemCount:t.length,enabled:u});if(l.current=i.state,c(i.state),i.effect.type===`cancel`)r();else if(i.effect.type===`select`){let e=t[i.effect.index];e!==void 0&&n(e.value)}},[u,t,r,n]);Q(`menu-select`,e=>e.forEach(e=>p(e===`back`?`cancel`:e)),{isActive:!d});let m=Z(`menu-select`,[[[`previous`,`next`],`Navigate`],[`select`,`Select`],[`back`,`Back`]]),h=Z(`menu-select`,[[`back`,`Back`]]),g=Rn(s,{itemCount:t.length});g!==s&&(l.current=g);let _=g.selectedIndex;return d?V(Cr,{title:e,options:i||a?[]:t.map(e=>e.label),description:i?`Loading...`:a,cancellable:!0,buffer:f.buffer,invalid:f.invalid}):H(k,{flexDirection:`column`,borderStyle:`round`,borderColor:o.border.attention,paddingX:1,children:[V(G,{color:o.text.warning,bold:!0,children:e}),i&&V(k,{marginTop:1,children:V(G,{dimColor:!0,children:`Loading...`})}),a&&V(k,{marginTop:1,children:V(G,{color:o.text.error,children:a})}),!i&&!a&&V(k,{flexDirection:`column`,marginTop:1,children:t.map((e,t)=>H(k,{children:[H(G,{color:t===_?o.text.accent:void 0,bold:t===_,children:[t===_?`> `:` `,e.label]}),e.hint&&H(G,{dimColor:!0,children:[` `,e.hint]})]},e.value))}),V(Y,{hints:i?[]:a?h:m})]})}function Yo(e,t){e===`marketplace`?t.push({screen:`marketplace-list`}):e===`installed`&&t.push({screen:`installed-list`})}function Xo(e,t){e===`__add__`?t.push({screen:`marketplace-add`}):t.push({screen:`marketplace-action`,context:{marketplace:e}})}function Zo(e,t,n,r){e===`browse`?r.push({screen:`marketplace-browse`,context:{marketplace:t}}):e===`update`?n.marketplaceUpdate(t).then(()=>{r.notify(`Updated marketplace "${t}".`),r.pop()}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)}):e===`remove`&&r.setConfirm({message:`Remove marketplace "${t}" and all its plugins?`,onConfirm:()=>{r.setConfirm(void 0),n.marketplaceRemove(t).then(()=>{r.notify(`Removed marketplace "${t}".`),r.popN(2)}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})},onCancel:()=>r.setConfirm(void 0)})}function Qo(e,t,n,r){let i=`${e}@${t}`;n.find(t=>t.value===e)?.hint===`installed`?r.push({screen:`installed-action`,context:{pluginId:i}}):r.push({screen:`marketplace-install-scope`,context:{marketplace:t,pluginId:i}})}function $o(e,t,n,r){let i=e;n.install(t,i).then(()=>{r.notify(`Installed plugin "${t}" (${i} scope).`),r.popN(2)}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})}function es(e,t,n){n.setConfirm({message:`Uninstall plugin "${e}"?`,onConfirm:()=>{n.setConfirm(void 0),t.uninstall(e).then(()=>{n.notify(`Uninstalled plugin "${e}".`),n.refresh()}).catch(e=>{n.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})},onCancel:()=>n.setConfirm(void 0)})}function ts(e,t,n,r){e===`uninstall`&&r.setConfirm({message:`Uninstall plugin "${t}"?`,onConfirm:()=>{r.setConfirm(void 0),n.uninstall(t).then(()=>{r.notify(`Uninstalled plugin "${t}".`),r.popN(2)}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})},onCancel:()=>r.setConfirm(void 0)})}function ns({callbacks:e,onClose:t,addMessage:n}){let[r,i]=z([{screen:`main`}]),[a,o]=z(),[s,c]=z(0),l=r[r.length-1]??{screen:`main`},u=P(e=>{i(t=>[...t,e])},[]),d=P(()=>{i(e=>e.length<=1?(t(),e):e.slice(0,-1))},[t]),f=P(e=>{i(n=>{let r=n.slice(0,Math.max(1,n.length-e));return r.length===0?(t(),n):r})},[t]),p=P(e=>{n?.({role:`system`,content:e})},[n]),m=P(()=>{c(e=>e+1)},[]),h=P(e=>o(e),[o]),g={push:P(e=>u({screen:e.screen,context:e.context}),[u]),pop:d,popN:f,notify:p,setConfirm:h,refresh:m},{items:_,loading:v,error:ee}=qo(l.screen,l.context?.marketplace,e,s,r.length),y=P(t=>{let n=l.screen,r=l.context;n===`main`?Yo(t,g):n===`marketplace-list`?Xo(t,g):n===`marketplace-action`?Zo(t,r?.marketplace??``,e,g):n===`marketplace-browse`?Qo(t,r?.marketplace??``,_,g):n===`marketplace-install-scope`?$o(t,r?.pluginId??``,e,g):n===`installed-list`?es(t,e,g):n===`installed-action`&&ts(t,r?.pluginId??``,e,g)},[l,_,e,u,d,f,p,o,m]),te=P(t=>{l.screen===`marketplace-add`&&e.marketplaceAdd(t).then(e=>{p(`Added marketplace "${e}" from ${t}.`),d()}).catch(e=>{p(`Error: ${e instanceof Error?e.message:String(e)}`),d()})},[l.screen,e,p,d]);if(a)return V(Ko,{message:a.message,onSelect:e=>{e===0?a.onConfirm():a.onCancel()}});let b=l.screen;return b===`marketplace-add`?V(Ao,{title:`Add Marketplace Source`,placeholder:`owner/repo or git URL`,onSubmit:te,onCancel:d,validate:e=>e.includes(`/`)?void 0:`Must be owner/repo or a git URL`}):b===`marketplace-action`?V(Jo,{title:`Marketplace: ${l.context?.marketplace??``}`,items:[{label:`Browse plugins`,value:`browse`},{label:`Update`,value:`update`},{label:`Remove`,value:`remove`}],onSelect:y,onBack:d},r.length):b===`marketplace-install-scope`?V(Jo,{title:`Install scope for "${l.context?.pluginId??``}"`,items:[{label:`User scope`,value:`user`},{label:`Project scope`,value:`project`}],onSelect:y,onBack:d},r.length):b===`installed-action`?V(Jo,{title:`Plugin: ${l.context?.pluginId??``}`,items:[{label:`Uninstall`,value:`uninstall`}],onSelect:y,onBack:d},r.length):V(Jo,{title:{main:`Plugin Management`,"marketplace-list":`Marketplace`,"marketplace-browse":`Browse: ${l.context?.marketplace??``}`,"installed-list":`Installed Plugins`}[b]??`Plugin Management`,items:{main:[{label:`Marketplace`,value:`marketplace`},{label:`Installed Plugins`,value:`installed`}]}[b]??_,onSelect:y,onBack:d,loading:v,error:ee},`${b}-${r.length}-${s}`)}function rs({notices:e}){let t=q();return e.length===0?null:V(k,{flexDirection:`column`,paddingX:1,children:e.map(e=>V(G,{color:t.text.muted,children:e.message},e.id))})}function is(e){let t=e.startsWith(`session_`)?e.slice(8):e;return t===``?e:t.slice(0,8)}function as(e){let t=[];return e.live===!0&&t.push(`● live`),e.clients!==void 0&&e.clients>0&&t.push(`${e.clients} ${e.clients===1?`client`:`clients`}`),t.length>0?t.join(` · `):null}function os({sessions:e,onSelect:t,onCancel:n}){let r=q();return H(k,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[V(G,{bold:!0,color:r.text.accent,children:`Select a session to resume:`}),V(bo,{items:[...e],renderItem:(e,t)=>{let n=as(e),i=e.preview?e.preview.slice(0,60)+(e.preview.length>60?`...`:``):``;return H(G,{children:[t?`> `:` `,V(G,{bold:!0,children:e.name??is(e.id)}),` `,V(G,{dimColor:!0,children:new Date(e.updatedAt).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}),` `,H(G,{dimColor:!0,children:[`msgs: `,e.messageCount]}),n===null?null:H(B,{children:[` `,V(G,{color:r.text.success,children:n})]}),i?H(B,{children:[`
|
|
37
|
-
`,V(G,{dimColor:!0,children:i})]}):null]})},onSelect:e=>t(e.id),onCancel:n})]})}function ss(e){let t=cs(e),n=e.hasPendingPrompt&&t.kind!==`queued`?[`queued`]:[],r=[t.label,...n].join(` · `);return{...t,segments:n,text:r}}function cs(e){return e.activeToolCount>0?{kind:`tools`,label:`Tools (${e.activeToolCount})`,tone:`accent`}:e.isThinking?{kind:`thinking`,label:`Thinking`,tone:`warning`}:e.activeBackgroundTaskCount>0?{kind:`background`,label:`Background (${e.activeBackgroundTaskCount})`,tone:`accent`}:e.hasPendingPrompt?{kind:`queued`,label:`Queued`,tone:`warning`}:{kind:`idle`,label:`Idle`,tone:`muted`}}const ls=` | `;function us(e,t){return e>=90?t.text.error:e>=70?t.text.warning:t.text.success}function ds({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r}){let i=q(),a=ss({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r});return V(G,{color:i.text[a.tone],bold:a.kind!==`idle`,children:a.text})}function fs({percentage:e,usedTokens:n,maxTokens:r}){return H(G,{color:us(e,q()),children:[`Context: `,Math.round(e),`% (`,t(n),`/`,t(r),` tokens)`]})}function ps(){return V(G,{color:q().text.warning,bold:!0,children:`Observing — read only`})}function ms({permissionMode:e}){return H(B,{children:[V(G,{color:q().text.accent,bold:!0,children:`Mode:`}),` `,V(G,{children:e})]})}function hs(e,t){return t||e!=="default"}function gs({activePresetId:e}){return H(B,{children:[V(G,{color:q().text.accent,bold:!0,children:`Preset:`}),` `,V(G,{children:e})]})}function _s(e){return e!==void 0&&e!=="default"}function vs({modelName:e,providerDisplayName:t,effort:n}){return H(G,{dimColor:!0,children:[t===void 0?e:`${t} ${e}`,n===void 0?``:` Effort: ${n}`]})}function ys(e){let t=q(),n=e.showGitBranch&&e.gitBranch!==void 0&&e.gitBranch.length>0,r=K(),i=hs(e.permissionMode,r),a=e.activePresetId,o=_s(a);return H(G,{children:[e.readOnly&&H(B,{children:[V(ps,{}),!r&&ls]}),!r&&V(ds,{isThinking:e.isThinking,activeToolCount:e.activeToolCount,activeBackgroundTaskCount:e.activeBackgroundTaskCount,hasPendingPrompt:e.hasPendingPrompt}),i&&H(B,{children:[ls,V(ms,{permissionMode:e.permissionMode})]}),o&&H(B,{children:[ls,V(gs,{activePresetId:a})]}),e.sessionName&&H(B,{children:[ls,V(G,{color:t.text.session,children:e.sessionName})]}),n&&H(B,{children:[ls,H(G,{dimColor:!0,children:[`git: `,e.gitBranch]})]}),ls,V(vs,{modelName:e.modelName,providerDisplayName:e.providerDisplayName,effort:e.effort}),!r&&H(B,{children:[ls,V(fs,{percentage:e.contextPercentage,usedTokens:e.contextUsedTokens,maxTokens:e.contextMaxTokens})]})]})}function bs({permissionMode:e,modelName:t,providerDisplayName:n,sessionId:r,isThinking:i,activeToolCount:a=0,activeBackgroundTaskCount:o=0,hasPendingPrompt:s=!1,contextPercentage:c,contextUsedTokens:l,contextMaxTokens:u,sessionName:d,gitBranch:f,showGitBranch:p=!0,activeAgentLabel:m,activePresetId:h,effort:g,readOnly:_=!1}){let v=q();return H(k,{paddingLeft:1,paddingRight:1,justifyContent:`space-between`,children:[V(ys,{permissionMode:e,modelName:t,providerDisplayName:n,isThinking:i,activeToolCount:a,activeBackgroundTaskCount:o,hasPendingPrompt:s,contextPercentage:c,contextUsedTokens:l,contextMaxTokens:u,sessionName:d,gitBranch:f,showGitBranch:p,activePresetId:h,effort:g,readOnly:_}),m!==void 0&&H(G,{color:v.text.warning,bold:!0,children:[`[`,m,`]`]})]})}const xs=N(null),Ss=xs.Provider;function Cs(){let e=F(xs);if(!e)throw Error(`TuiCliAdapterContext not provided`);return e}function ws({cwd:e,permissionMode:t,modelId:n,providerType:r,sessionId:i,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextState:l,sessionName:u,settings:d,activeAgentLabel:f,activePresetId:p,effort:m,gitRefreshToken:h,readOnly:g=!1}){let _=Cs(),v=L(()=>_.getGitBranch(e),[_,e,h]),ee=L(()=>r===void 0?void 0:_.getProviderDisplayName(r),[_,r]);return d.enabled?V(bs,{permissionMode:t,modelName:n??``,providerDisplayName:ee,sessionId:i,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextPercentage:l.percentage,contextUsedTokens:l.usedTokens,contextMaxTokens:l.maxTokens,sessionName:u,gitBranch:v,showGitBranch:d.gitBranch,activeAgentLabel:f,activePresetId:p,effort:m,readOnly:g}):g?V(ps,{}):null}function Ts(e,t){let n=un(e);return{color:ln(t,n),icon:cn[n],strikethrough:n===`error`||n===`denied`}}function Es({isThinking:e}){let t=q();return e?V(k,{marginBottom:1,children:V(G,{color:t.text.warning,children:`Thinking...`})}):V(B,{})}function Ds({activeTools:e}){let t=q(),n=Xa();return H(k,{flexDirection:`column`,marginBottom:1,children:[V(G,{color:t.text.emphasis,bold:!0,children:`Tools:`}),V(G,{children:` `}),e.map((e,r)=>{let{color:i,icon:a,strikethrough:o}=Ts(e,t);return H(k,{flexDirection:`column`,children:[H(G,{color:i,strikethrough:o,children:[` `,a,` `,Wa(e.toolName,n),`(`,Ga(e.firstArg),`)`]}),e.diffLines&&e.diffLines.length>0&&V(co,{file:e.diffFile,lines:e.diffLines})]},`${e.toolName}-${r}`)})]})}function Os(e,t,n,r){let i=t.map(e=>Wa(e.toolName,r)).join(`, `),a=[i.length>0?`${Za.tool} ${i}`:void 0,e.length>0?e:n?Za.thinking:void 0].filter(e=>e!==void 0);return a.length===0?V(B,{}):V(G,{children:a.join(` — `)})}function ks({text:e,activeTools:t,isThinking:n=!1}){let r=q(),i=Ha(),a=t.length>0,o=e.length>0,s=K(),c=Ya(),l=Xa();return s?Os(e,t,n,l):!a&&!o?V(Es,{isThinking:n}):H(k,{flexDirection:`column`,children:[a&&V(Ds,{activeTools:t}),o&&H(k,{flexDirection:`column`,marginBottom:1,children:[H(G,{color:r.text.accent,bold:!0,children:[c,`:`]}),V(G,{children:` `}),V(k,{marginLeft:2,children:V(nt,{wrap:`wrap`,children:i(e)})})]})]})}function As(e,t){let n=t?` (current)`:``;return`${e.name} — ${e.appearance}, ${e.source}${n}`}function js({theme:e,isFocused:t,isActive:n,rowNumber:r}){let i=q(),a=r===void 0?t?`> `:` `:xr(r);return H(G,{...t&&r===void 0?{color:i.text.accent,bold:!0}:{},children:[a,As(e,n)]})}function Ms({itemCount:e,buffer:t,invalid:n}){let r=br(e,!0);return H(k,{flexDirection:`column`,children:[H(G,{children:[r,t.length>0?` ${t}`:``]}),n&&V(G,{children:r})]})}function Ns(e,t){let n=e.findIndex(e=>e.id===t);return n<0?0:n}function Ps(e){let[t,n]=M.useState(()=>({syntaxHighlighting:e.syntaxHighlighting,reducedMotion:e.reducedMotion}));return{toggles:t,setToggles:n}}function Fs(e){let{themes:t,activeThemeId:n,preview:r}=e,[i,a]=M.useState(()=>Ns(t,n));return{focusedIndex:i,move:M.useCallback(e=>{t.length!==0&&a(n=>{let i=(n+e+t.length)%t.length,a=t[i];return a&&r(a.id),i})},[r,t])}}function Is(e,t){let{themes:n,select:r,cancel:i}=e,{focusedIndex:a,move:o}=Fs(e),{toggles:s,setToggles:c}=Ps(e),l=M.useRef(s);l.current=s;let u=M.useCallback(e=>{let t=n[e];t&&r(t.id,l.current)},[r,n]),d=Gn({enabled:t&&n.length>0,itemCount:n.length,cancellable:!0,onSelect:u,onCancel:i}),f=M.useCallback(e=>{c(t=>({...t,[e]:!t[e]}))},[c]);return Q(`theme-picker`,e=>{for(let t of e)t===`previous`?o(-1):t===`next`?o(1):t===`select`?u(a):t===`toggle-syntax`?f(`syntaxHighlighting`):t===`toggle-motion`?f(`reducedMotion`):t===`cancel`&&i()},{isActive:!t}),{focusedIndex:a,toggles:s,numbered:d}}function Ls({themes:e,activeThemeId:t,focusedIndex:n,screenReader:r}){return e.length===0?V(G,{dimColor:!0,children:`No themes installed`}):V(B,{children:e.map((e,i)=>V(js,{theme:e,isFocused:i===n,isActive:e.id===t,...r?{rowNumber:i}:{}},e.id))})}function Rs(){return ut()?V(B,{}):V(G,{dimColor:!0,children:`Colour is off for this terminal — themes apply, previews cannot show.`})}function zs({skipped:e}){return e.length===0?V(B,{}):V(k,{flexDirection:`column`,marginTop:1,children:e.map((e,t)=>V(G,{dimColor:!0,children:` Skipped "${e.fileName}" — ${e.reason}`},t))})}function Bs({toggles:e,reducedMotionPin:t,screenReader:n}){let r=e=>e?`on`:`off`,i=t===void 0?``:` (this run: motion ${r(!t.reducedMotion)}, pinned by ${t.tier})`;return H(k,{flexDirection:`column`,children:[V(G,{dimColor:!0,children:`syntax ${r(e.syntaxHighlighting)} · motion ${r(!e.reducedMotion)}${i}`}),n&&V(G,{dimColor:!0,children:`Change with /theme syntax on|off or /theme motion on|off`})]})}function Vs({screenReader:e,itemCount:t,numbered:n}){let r=Z(`theme-picker`,[[[`previous`,`next`],`Preview`],[`select`,`Apply`],[`toggle-syntax`,`Syntax`],[`toggle-motion`,`Motion`],[`cancel`,`Cancel`]]);return e?V(Ms,{itemCount:t,buffer:n.buffer,invalid:n.invalid}):V(Y,{hints:r})}function Hs({picker:e}){let t=q(),n=K(),{themes:r,activeThemeId:i}=e,{focusedIndex:a,toggles:o,numbered:s}=Is(e,n);return H(k,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.focused},paddingX:1,children:[V(G,{color:t.text.accent,bold:!0,children:`Theme`}),V(Rs,{}),V(Bs,{toggles:o,reducedMotionPin:e.reducedMotionPin,screenReader:n}),V(k,{flexDirection:`column`,marginTop:1,children:V(Ls,{themes:r,activeThemeId:i,focusedIndex:a,screenReader:n})}),V(zs,{skipped:e.skipped}),V(Vs,{screenReader:n,itemCount:r.length,numbered:s})]})}function Us({entry:e,selected:t}){let n=q(),r=e.config.enabled,i=r?`●`:`○`,a=r?`[on] `:`[off]`,o=e.config.options?.port,s=typeof o==`number`?`port: ${o}`:``;return V(k,{children:V(G,{color:t?n.text.accent:void 0,bold:t,children:`${i} ${e.transport.name.padEnd(18)} ${a} ${s}`})})}function Ws(e,t,n,r,i,a,o,s,c){Q(`transport-settings`,P(l=>{if(!n){if(l.includes(`previous`)){i(e=>Math.max(0,e-1));return}if(l.includes(`next`)){i(t=>Math.min(e.length-1,t+1));return}if(l.includes(`close`)){s();return}if(l.includes(`toggle`)){let n=e[t];if(!n)return;a(!0),o(void 0),r.setEnabled(n.transport.name,!n.config.enabled).then(()=>{c(),a(!1)}).catch(e=>{o(e instanceof Error?e.message:`could not save the setting`),a(!1)})}}},[n,e,t,r,s,c,i,a,o]))}function Gs({registry:e,onClose:t}){let n=q(),r=Ya(),[i,a]=z(()=>e.getAll()),[o,s]=z(0),[c,l]=z(!1),[u,d]=z(void 0),f=P(()=>{a(e.getAll())},[e]),p=Z(`transport-settings`,[[[`previous`,`next`],`Select`],[`toggle`,`Toggle`],[`close`,`Close`]]);return Ws(i,o,c,e,s,l,d,t,f),H(k,{flexDirection:`column`,paddingX:2,paddingY:1,children:[V(G,{bold:!0,children:`Settings › Transports`}),V(k,{marginTop:1,flexDirection:`column`,children:i.map((e,t)=>V(Us,{entry:e,selected:t===o},e.transport.name))}),H(k,{marginTop:1,flexDirection:`column`,children:[V(Y,{hints:p}),H(G,{dimColor:!0,children:[`A toggle is saved now and applies the next time `,r,` starts.`]})]}),c&&V(k,{marginTop:1,children:V(G,{color:n.text.warning,children:`Saving…`})}),u!==void 0&&V(k,{marginTop:1,children:V(G,{color:n.text.error,children:`Not saved — ${u}`})})]})}function Ks({message:e}){return V(k,{paddingX:1,marginBottom:1,children:V(G,{color:q().text.warning,children:e})})}function qs({model:e}){return V(Se,{items:e.staticItems,children:e=>e.kind===`banner`?V(an,{version:e.version},`logo`):V(vo,{entry:e.entry},e.entry.id)},e.transcriptKey)}function Js({model:e}){let t=q(),{background:n,stream:r}=e;return H(k,{flexDirection:`column`,paddingX:1,flexGrow:1,children:[n.selectedEntry&&n.selectedEntry.kind!==`main_thread`&&V(Mn,{entry:n.selectedEntry,page:n.detail.page,loading:n.detail.loading,error:n.detail.error}),e.isShuttingDown&&V(G,{color:t.text.warning,children:`Shutting down...`}),(r.isThinking||r.activeTools.length>0)&&H(k,{flexDirection:`column`,marginBottom:1,children:[V(ks,{text:r.text,activeTools:r.activeTools,isThinking:r.isThinking}),r.isStalled&&V(G,{color:t.text.warning,children:`⚠ Still waiting on the provider — the network may be stalled. Esc to interrupt.`})]}),!r.isThinking&&r.lastErrorMessage&&V(G,{color:t.text.error,children:`✖ Last turn failed — the session is alive; type your next prompt when ready.`}),V(An,{entries:n.entries,focusedIndex:n.focusedIndex})]})}function Ys({model:e}){if(e.coordinationError!==void 0||e.coordinationPending)return V(B,{});let{background:t,plugin:n,sessionPicker:r,transport:i}=e,a=e.pendingUserAction;return H(B,{children:[t.switcherVisible&&V(Tr,{snapshot:t.snapshot,selectedEntryId:t.selectedEntryId,onSelect:t.select,onClose:t.closeSwitcher,onAttach:t.attachToFork}),e.permissionRequest&&V(Bo,{request:e.permissionRequest}),a&&V(No,{request:a,onAnswer:t=>e.resolveUserAction(a,t)}),n.visible&&V(ns,{callbacks:n.callbacks,onClose:n.close,addMessage:e=>n.addMessage(e.content)}),i.visible&&i.registry&&V(Gs,{registry:i.registry,onClose:i.close}),r.visible&&V(os,{sessions:r.sessions,onSelect:r.select,onCancel:r.cancel}),e.theme.picker.visible&&V(Hs,{picker:e.theme.picker})]})}function Xs({model:e}){let{input:t}=e;return H(B,{children:[V(jn,{percentage:e.contextPercentage}),V(_a,{onSubmit:t.submit,onCancelQueue:t.cancelQueue,isDisabled:t.disabled,isQueueCancellationDisabled:t.queueCancellationDisabled,isAborting:t.isAborting,pendingPrompt:t.pendingPrompt,pendingCount:t.pendingCount,commandQueryPort:t.commandQueryPort,sessionName:t.sessionName,history:t.history,onRequestFocusBackgroundList:t.focusBackgroundList,historySearch:t.historySearch,initialValue:t.initialValue,consumeInitialValue:t.consumeInitialValue,externalPromptOrigin:t.externalPromptOrigin}),V(ws,{...e.status})]})}function Zs({viewModel:e}){let t=q(),n=yr();return H(k,{flexDirection:`column`,children:[V(qs,{model:e}),!e.handoffSuspended&&H(B,{children:[e.updateNotice&&V(Ks,{message:e.updateNotice}),e.coordinationError&&H(G,{color:t.text.error,children:[e.coordinationError,` Press Enter to retry.`]}),n.diagnostic&&V(G,{color:t.text.error,children:`Keybindings ${n.diagnostic.file} ${n.diagnostic.path}: ${n.diagnostic.message} Last valid bindings remain active.`}),n.warnings.map(e=>V(G,{color:t.text.warning,children:`Keybindings ${e.path}: ${e.message}`},`${e.path}:${e.code}`)),e.theme.unknownThemeNotice!==void 0&&V(G,{color:t.text.warning,children:e.theme.unknownThemeNotice}),V(rs,{notices:e.sessionEventNotices}),V(Js,{model:e}),V(Ys,{model:e}),V(Xs,{model:e})]})]})}function Qs(e){return[...e.screenReader?[]:[{kind:`banner`,version:e.version??`0.0.0`}],...e.history.map(e=>({kind:`entry`,entry:e}))]}function $s(e){let t=e.forceExit??(e=>process.exit(e));if(e.isShuttingDown){t(130);return}e.graceful()}function ec(e){let t=e.write??(e=>{process.stdout.write(e)}),n=e.now??(()=>Date.now()),r=e.longToolBellMs??5e3,i=new Map,a=()=>{e.enabled&&t(`\x07`)};return{replyCompleted:a,promptMounted:a,toolStarted(t){e.enabled&&i.set(t,n())},toolCompleted(e){let t=i.get(e);i.delete(e),t!==void 0&&(n()-t<=r||a())}}}const tc={promptStart:`A`,promptEnd:`B`,turnStart:`C`,turnEnd:`D`};function nc(e){return`\x1b]133;${tc[e]}\x07`}function rc(e){let t=e.write??(e=>{process.stdout.write(e)});return{emit(n){!e.enabled||!e.supported()||t(nc(n))}}}function ic(e,t){return e.executionId??`${e.toolName}#${t}`}function ac(e){let t=new Set;return e.forEach((e,n)=>{e.isRunning&&t.add(ic(e,n))}),t}function oc(e){let{enabled:t,isThinking:n,activeTools:r,awaitingAnswer:i}=e,a=L(()=>ec({enabled:t}),[t]),o=oi(),s=li(),c=L(()=>rc({enabled:t,supported:()=>ft({override:s.turnMarks}),write:e=>o.write(e)}),[t,o,s.turnMarks]),l=R(!1),u=R(new Set);I(()=>{n&&!l.current?(c.emit(`promptEnd`),c.emit(`turnStart`)):!n&&l.current&&(c.emit(`turnEnd`),c.emit(`promptStart`),a.replyCompleted()),l.current=n},[n,a,c]),I(()=>{c.emit(`promptStart`)},[c]),I(()=>{i&&a.promptMounted()},[i,a]),I(()=>{let e=ac(r);for(let t of e)u.current.has(t)||a.toolStarted(t);for(let t of u.current)e.has(t)||a.toolCompleted(t);u.current=e},[r,a])}function sc(e){return!!(e.permissionRequest||e.pendingUserAction||e.pluginVisible||e.transportVisible||e.sessionPickerVisible||e.workspaceSwitcherVisible||e.historySearchOpen||e.themePickerVisible||e.coordinationBlocked)}function cc(e){Q(e.isThinking?`thinking`:`background-detail`,t=>{if(sc(e))return;if(t.includes(`abort`)&&e.isThinking){e.readOnly||e.abort();return}let n=e.selectedEntry;if(t.includes(`return-to-main`)&&n&&n.kind!==`main_thread`&&e.mainThreadEntryId){e.selectWorkspaceEntry(e.mainThreadEntryId);return}t.includes(`return-to-main`)&&!e.backgroundListFocused&&!e.readOnly&&e.stopWaitingLoop()})}function lc(e){Q(`app`,t=>{t.includes(`open-workspace-switcher`)&&(e.permissionRequest||e.pendingUserAction||e.pluginVisible||e.sessionPickerVisible||e.historySearchOpen||e.themePickerVisible||e.coordinationBlocked||e.isShuttingDown||e.toggleWorkspaceSwitcher())})}function uc(e){Q(`recovery`,t=>{e.recoveryError!==void 0&&!e.recoveryPending&&t.includes(`retry`)&&e.retryRecovery()})}function dc(e,t){return e===``||t&&e===`]`}function fc(e){let{exit:t}=we(),n=n=>{$s({isShuttingDown:e.isShuttingDown,graceful:()=>void e.shutdown(n).finally(()=>t())})};Ee((t,r)=>{(r.ctrl&&t===`c`||e.attached&&dc(t,r.ctrl))&&n(`prompt_input_exit`)}),I(()=>{let e=()=>n(`other`);return process.on(`SIGINT`,e),process.on(`SIGTERM`,e),()=>{process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}})}function pc(e){cc(e),uc(e),lc(e),fc(e);let t=K();return oc({enabled:t,isThinking:e.isThinking,activeTools:e.activeTools,awaitingAnswer:e.permissionRequest!==null||e.pendingUserAction!==null}),t}function mc(){return Promise.reject(Error(`Plugin management is unavailable in this host.`))}function hc(){return{listInstalled:mc,listAvailablePlugins:mc,install:mc,uninstall:mc,enable:mc,disable:mc,marketplaceAdd:mc,marketplaceRemove:mc,marketplaceUpdate:mc,marketplaceList:mc,reloadPlugins:mc}}function gc(e){return e??hc()}function _c(e){return L(()=>gc(e),[e])}function vc(e){let t=_c(e.pluginAdapter),n=P(t=>e.addEntry(a(i(t))),[e.addEntry]),r=P(t=>{e.setSessionPickerVisible(!1),e.onSessionSwitch(t)},[e.onSessionSwitch,e.setSessionPickerVisible]),o=P(()=>{e.setSessionPickerVisible(!1),e.addEntry(a(i(`Session resume cancelled.`)))},[e.addEntry,e.setSessionPickerVisible]),s=e.hostSessions??u(e.sessionStore,e.cwd),c=e.sessionPickerVisible&&s.length===0;return I(()=>{c&&(e.setSessionPickerVisible(!1),e.addEntry(a(i(`No saved sessions to resume in this workspace.`))))},[c,e.addEntry,e.setSessionPickerVisible]),{plugin:{visible:e.pluginVisible,callbacks:t,close:()=>e.setPluginVisible(!1),addMessage:n},transport:{visible:e.transportVisible,registry:e.transportRegistry,close:()=>e.setTransportVisible(!1)},sessionPicker:{visible:e.sessionPickerVisible&&!c,sessions:s,select:r,cancel:o}}}function yc(e){let[t,n]=z(0),r=P(async t=>{let n=e.selectedEntry;if(n&&n.kind!==`main_thread`&&n.controls.includes(`send`)){await e.sendAgentJob(n.sourceId,t);return}await e.submit(t)},[e.selectedEntry,e.sendAgentJob,e.submit]),i=P(async e=>{n(e=>e+1),await r(e)},[r]),a=R(!1);return I(()=>{a.current&&!e.isThinking&&n(e=>e+1),a.current=e.isThinking},[e.isThinking]),{submit:i,gitRefreshToken:t}}function bc(e){let{screens:t,workspace:n}=e.shell,r=yc({selectedEntry:n.background.selectedEntry,submit:t.handleSubmit,sendAgentJob:e.state.sendAgentJob,isThinking:e.state.isThinking}),i=pc({isThinking:e.state.isThinking,isShuttingDown:e.state.isShuttingDown,readOnly:e.state.readOnly,attached:e.state.attached,permissionRequest:e.state.permissionRequest,pendingUserAction:e.state.pendingUserAction,pluginVisible:t.showPluginTUI,transportVisible:t.showTransportTUI,sessionPickerVisible:t.showSessionPicker,workspaceSwitcherVisible:n.background.switcherVisible,historySearchOpen:e.shell.historySearchOpen,themePickerVisible:t.showThemePicker,selectedEntry:n.background.selectedEntry,backgroundListFocused:n.isBackgroundListFocused,mainThreadEntryId:n.mainThreadEntryId,activeTools:e.state.activeTools,abort:e.state.handleAbort,stopWaitingLoop:e.state.handleStopWaitingLoop,toggleWorkspaceSwitcher:n.toggleSwitcher,selectWorkspaceEntry:e.state.selectExecutionWorkspaceEntry,shutdown:e.state.handleShutdown,recoveryError:e.recoveryError,recoveryPending:e.recoveryPending,coordinationBlocked:e.coordinationBlocked,retryRecovery:e.retryRecovery});return{submission:r,overlays:vc({cwd:e.cwd,pluginAdapter:e.pluginAdapter,pluginVisible:t.showPluginTUI,setPluginVisible:t.setShowPluginTUI,transportRegistry:e.transportRegistry,transportVisible:t.showTransportTUI,setTransportVisible:t.setShowTransportTUI,sessionStore:e.sessionStore,hostSessions:e.state.hostSessions,sessionPickerVisible:t.showSessionPicker,setSessionPickerVisible:t.setShowSessionPicker,onSessionSwitch:e.onSessionSwitch,addEntry:e.state.addEntry}),screenReader:i}}function xc(e){let t=Ya();I(()=>{let n=W(e??``),r=W(t),i=n?`${r} — ${n}`:r;process.stdout.write(`\x1b]0;${i}\x07`)},[e,t])}function Sc(e){let[t,n]=z(!1);return I(()=>{if(e)return e.registerSuspendHooks({suspend:async()=>{n(!0),await new Promise(e=>setTimeout(e,50))},resume:()=>n(!1)})},[e]),t}function Cc(e){let[t,n]=z(),[r,i]=z(!0),a=P(()=>{i(!0),e.start().then(()=>n(void 0)).catch(e=>{let t=e instanceof Error?e.message:String(e);n(`TUI start failed: ${t}`)}).finally(()=>i(!1))},[e]);return I(()=>{a()},[e,a]),{startError:t,startPending:r,retryStart:a}}function wc(e){let[t,n]=z();return I(()=>{let t=!0;return e?.then(e=>{t&&e!==void 0&&n(e)}).catch(()=>{}),()=>{t=!1}},[e]),t}function Tc(e,t){let n=Cc(e),[r,i]=z(e.sessionName);return I(()=>{e.sessionName!==void 0&&e.sessionName!==r&&i(e.sessionName)},[e,e.sessionName,r]),xc(r),{sessionName:r,setSessionName:i,handoffSuspended:Sc(e.terminalHandoffController),updateNotice:wc(t),...n}}function Ec(e){return ce(e.readSettings(e.getUserSettingsPath()))}function Dc(){let e=Cs(),[t,n]=z(()=>Ec(e));return[t,P(()=>{n(Ec(e))},[e])]}function Oc(e){let[t,n]=z(null),[r,i]=z(),[a,o]=z(!1),{entry:s,snapshot:c,read:l}=e;return I(()=>{if(!s||s.kind===`main_thread`){n(null),i(void 0),o(!1);return}let e=!0;return o(!0),i(void 0),l(s.id).then(t=>{e&&(n(t),o(!1))}).catch(t=>{e&&(i(t.message),o(!1))}),()=>{e=!1}},[c,l,s]),{page:t,error:r,loading:a}}function kc(e,t){let n=m(e,{hasSessionRecord:t.hasSessionRecord});if(n.type===`refused`){let e=n.resumeSessionId&&t.formatResumeCommand?.(n.resumeSessionId);t.notify(e?`${n.reason} Open it with: ${e}`:n.reason);return}return t.switchSession(n.sessionId),{sessionId:n.sessionId}}function Ac({sessionStore:e,onSessionSwitch:t,addEntry:n}){let r=Cs();return P(o=>{let s=e=>n(a(i(e)));if(e===void 0){s(`This surface has no session store, so it cannot attach to a forked session.`);return}kc(o,{hasSessionRecord:t=>e.load(t).status===`valid`,switchSession:t,notify:s,...r.formatResumeCommand===void 0?{}:{formatResumeCommand:r.formatResumeCommand}})},[n,r,t,e])}function jc(e){let{snapshot:t,selectedEntryId:n}=e,r=L(()=>t?.entries.find(e=>e.id===n),[t,n]);return{entry:r,detail:Oc({entry:r,snapshot:t,read:e.read}),attachToFork:Ac({sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.addEntry})}}function Mc(e,t,n){return t<=0?{type:`exit`}:n.upArrow?{type:`move`,index:e>0?e-1:null}:n.downArrow?{type:`move`,index:e<t-1?e+1:e}:n.return?{type:`open`,index:Math.min(Math.max(e,0),t-1)}:n.escape?{type:`exit`}:{type:`none`}}function Nc(e,t,n,r,i){Q(`background-list`,i=>{if(e===null)return;let a=Mc(e,t.length,{upArrow:i.includes(`previous`),downArrow:i.includes(`next`),return:i.includes(`open`),escape:i.includes(`close`)});if(a.type===`move`&&n(a.index),a.type===`open`){let e=t[a.index];e&&r(e),n(null)}a.type===`exit`&&n(null)},{isActive:e!==null&&i})}function Pc(e,t,n){let[r,i]=z(null);return I(()=>{i(t=>t===null||e.length===0?null:Math.min(t,e.length-1))},[e.length]),Nc(r,e,i,t,n),{focusedIndex:r,focusList:P(()=>{e.length>0&&i(0)},[e.length])}}function Fc(e){return{open:P(()=>e(!0),[e]),toggle:P(()=>e(e=>!e),[e]),close:P(()=>e(!1),[e])}}function Ic(e){let t=L(()=>hn(e.snapshot),[e.snapshot]),{focusedIndex:n,focusList:r}=Pc(t.map(e=>e.id),e.select,e.navigationEnabled),i=jc({selectedEntryId:e.selectedEntryId,snapshot:e.snapshot,read:e.read,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.addEntry}),a=Fc(e.setSwitcherVisible),o=i.entry;return{background:{entries:t,focusedIndex:n,selectedEntry:o,detail:i.detail,switcherVisible:e.switcherVisible,snapshot:e.snapshot,selectedEntryId:e.selectedEntryId,select:e.select,closeSwitcher:a.close,attachToFork:i.attachToFork},activeBackgroundTaskCount:gn(e.snapshot),activeAgentLabel:o?.kind===`main_thread`?void 0:o?.title,mainThreadEntryId:e.snapshot?.entries.find(e=>e.kind===`main_thread`)?.id,isSelectedEntryInteractive:!o||o.kind===`main_thread`||o.controls.includes(`send`),isBackgroundListFocused:n!==null,openSwitcher:a.open,toggleSwitcher:a.toggle,focusBackgroundList:r}}function Lc(e,t,n){let r=e=>{if(e.requesterDriverId===T)switch(e.intent.type){case`show-plugin-manager`:t.setShowPluginTUI(!0);return;case`show-settings`:t.setShowTransportTUI(!0);return;case`show-session-picker`:t.setShowSessionPicker(!0);return;case`show-agent-switcher`:n.current.openAgentSwitcher?.();return;case`show-theme-picker`:t.setShowThemePicker(!0);return}},i=e=>{n.current.setSessionName(e.name)};return e.on(`ui_intent`,r),e.on(`session_renamed`,i),()=>{e.off(`ui_intent`,r),e.off(`session_renamed`,i)}}function Rc(e){let t=R(e);return t.current=e,t}function zc({uiEventPort:e,baseHandleSubmit:t,setSessionName:n,refreshStatusLineSettings:r,refreshAppearanceSettings:i,showSessionPickerOnStart:a,openAgentSwitcher:o}){let[s,c]=z(!1),[l,u]=z(a??!1),[d,f]=z(!1),[p,m]=z(!1),h=Rc({setSessionName:n,refreshStatusLineSettings:r,refreshAppearanceSettings:i,openAgentSwitcher:o});return Ae(()=>Lc(e,{setShowPluginTUI:c,setShowTransportTUI:f,setShowSessionPicker:u,setShowThemePicker:m},h),[e]),{handleSubmit:P(async e=>{await t(e),e.trimStart().startsWith(`/`)&&(h.current.refreshStatusLineSettings(),h.current.refreshAppearanceSettings())},[t]),showPluginTUI:s,showSessionPicker:l,showTransportTUI:d,showThemePicker:p,setShowPluginTUI:c,setShowSessionPicker:u,setShowTransportTUI:f,setShowThemePicker:m}}function Bc(e){let t={..._},n=e.statusline;return Vc(n)?{enabled:typeof n.enabled==`boolean`?n.enabled:t.enabled,gitBranch:typeof n.gitBranch==`boolean`?n.gitBranch:t.gitBranch}:t}function Vc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Hc(e){return Bc(e.readSettings(e.getUserSettingsPath()))}function Uc(){let e=Cs(),[t,n]=z(()=>Hc(e));return[t,P(()=>{n(Hc(e))},[e])]}function Wc(e){let[t,n]=z(!1),[r,i]=z(!1),[a,o]=Uc(),[s,c]=Dc(),l=zc({uiEventPort:e.state.uiEventPort,baseHandleSubmit:e.state.handleSubmit,setSessionName:e.setSessionName,refreshStatusLineSettings:o,refreshAppearanceSettings:c,showSessionPickerOnStart:e.showSessionPickerOnStart,openAgentSwitcher:()=>n(!0)}),u=e.state.permissionRequest===null&&e.state.pendingUserAction===null&&!l.showPluginTUI&&!l.showTransportTUI&&!l.showSessionPicker&&!l.showThemePicker&&!t&&!r&&!e.coordinationBlocked;return{screens:l,workspace:Ic({snapshot:e.state.executionWorkspaceSnapshot,selectedEntryId:e.state.selectedExecutionEntryId,select:e.state.selectExecutionWorkspaceEntry,read:e.state.readExecutionWorkspaceDetail,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.state.addEntry,navigationEnabled:u,switcherVisible:t,setSwitcherVisible:n}),statusSettings:a,appearance:s,historySearchOpen:r,setHistorySearchOpen:i}}function Gc(e=ot(),t=[]){let n=new Map(e.map(e=>[e.id,e]));return{list:()=>e,skipped:()=>t,get:e=>n.get(e),resolve:e=>{if(e===void 0||e===at)return{theme:st(n.get(at))};let t=n.get(e);return t?{theme:t}:{theme:st(n.get(at)),unknownId:e}}}}function Kc(e){return`Theme "${e}" is not installed — using "${at}".`}function qc(e){return{id:e.id,name:e.name,appearance:e.appearance,source:e.source}}function Jc(e){return{listThemes:()=>e.registry.list().map(qc),getTheme:t=>{let n=e.registry.get(t);return n?qc(n):void 0},getAppearance:()=>({settings:e.readAppearance(),...e.reducedMotionPin===void 0?{}:{reducedMotionPin:e.reducedMotionPin}})}}function Yc(e){let t=L(()=>e.registry??Gc(),[e.registry]),[n,r]=z(void 0),i=L(()=>t.resolve(n??e.appearance.theme),[t,n,e.appearance.theme]),{setVisible:a,submit:o}=e,s=P(()=>{r(void 0),a(!1)},[a]),{syntaxHighlighting:c,reducedMotion:l}=e.appearance,u=P((e,t)=>{r(void 0),a(!1);let n=[`/theme ${e}`];t.syntaxHighlighting!==c&&n.push(`syntax ${t.syntaxHighlighting?`on`:`off`}`),t.reducedMotion!==l&&n.push(`motion ${t.reducedMotion?`off`:`on`}`),o(n.join(` `))},[l,a,o,c]),d=n===void 0?i.unknownId:void 0,f=e.reducedMotion??e.appearance.reducedMotion;return{resolved:i.theme,reducedMotion:f,syntaxHighlighting:e.appearance.syntaxHighlighting,...d===void 0?{}:{unknownThemeNotice:Kc(d)},picker:{visible:e.visible,themes:t.list(),skipped:t.skipped(),activeThemeId:e.appearance.theme,syntaxHighlighting:e.appearance.syntaxHighlighting,reducedMotion:e.appearance.reducedMotion,...e.reducedMotionOverride===void 0||e.reducedMotion===void 0?{}:{reducedMotionPin:{tier:e.reducedMotionOverride,reducedMotion:e.reducedMotion}},preview:r,select:u,cancel:s}}}function Xc(e){let[,t]=z(0);I(()=>e.subscribe(()=>t(e=>e+1)),[e]);let n=e.getSnapshot(),r=P(t=>e.selectExecutionWorkspaceEntry(t),[e]),i=P(t=>e.readExecutionWorkspaceDetail(t),[e]);return{uiEventPort:e.getSessionUiEventPort(),commandQueryPort:e.getCommandQueryPort(),history:n.history,addEntry:t=>e.addEntry(t),streamingText:n.streamingText,activeTools:n.activeTools,isThinking:n.isThinking,isAborting:n.isAborting,lastErrorMessage:n.lastErrorMessage,isStalled:n.isStalled,sessionEventNotices:n.sessionEventNotices,isShuttingDown:n.isShuttingDown,pendingPrompt:n.pendingPrompt,pendingCount:n.pendingCount,executionWorkspaceSnapshot:n.executionWorkspaceSnapshot,selectedExecutionEntryId:n.selectedExecutionEntryId,permissionRequest:n.permissionRequest,pendingUserAction:n.pendingUserAction,contextState:n.contextState,hostSessions:n.hostSessions,transcriptGeneration:n.transcriptGeneration??0,readOnly:n.readOnly===!0,attached:n.attached===!0,handleSubmit:t=>e.handleInput(t),handleAbort:()=>e.abort(),handleCancelQueue:()=>e.cancelQueue(),handleStopWaitingLoop:()=>e.stopWaitingSelfPacedLoop(),handleShutdown:t=>e.shutdown({reason:t}),sendAgentJob:(t,n)=>e.sendAgentJob(t,n),resolveUserAction:(t,n)=>e.resolveUserAction(t,n),getRuntimeStatusSnapshot:t=>e.getRuntimeStatusSnapshot(t),selectExecutionWorkspaceEntry:r,readExecutionWorkspaceDetail:i}}function Zc(e,t){let n=e.sessionSwitchError??t.startError,r=!!(e.sessionSwitchPending||t.startPending);return{error:n,pending:r,blocked:n!==void 0||r}}function Qc(e){let{promptHistorySource:t,promptHistoryProject:n}=e.props;if(t!==void 0&&n!==void 0)return{source:t,project:n,sessionId:e.runtime.sessionId,onOpenChange:e.shell.setHistorySearchOpen}}function $c(e){let{screens:t,workspace:n}=e.shell,r=e.state,i=!!(r.permissionRequest||r.pendingUserAction||t.showPluginTUI||t.showTransportTUI||t.showSessionPicker||t.showThemePicker||n.background.switcherVisible),a=e.coordination.blocked||i||r.isShuttingDown||!n.isSelectedEntryInteractive||n.isBackgroundListFocused;return{submit:e.interaction.submission.submit,cancelQueue:r.handleCancelQueue,disabled:a||r.isThinking&&r.pendingPrompt!==null,queueCancellationDisabled:a||r.readOnly,isAborting:r.isAborting,pendingPrompt:r.pendingPrompt,pendingCount:r.pendingCount,commandQueryPort:r.commandQueryPort,sessionName:e.lifecycle.sessionName,history:r.history,focusBackgroundList:n.focusBackgroundList,historySearch:Qc(e)}}function el(e){let{props:t,runtime:n,state:r}=e,i=e.shell.workspace;return{cwd:t.cwd,permissionMode:n.permissionMode,modelId:n.modelId??t.modelId,providerType:t.providerType,sessionId:n.sessionId,isThinking:r.isThinking,activeToolCount:r.activeTools.length,activeBackgroundTaskCount:i.activeBackgroundTaskCount,hasPendingPrompt:r.pendingPrompt!==null,contextState:r.contextState,sessionName:e.lifecycle.sessionName,settings:e.shell.statusSettings,activeAgentLabel:i.activeAgentLabel,activePresetId:n.activePresetId,effort:n.effort,gitRefreshToken:e.interaction.submission.gitRefreshToken,readOnly:r.readOnly}}function tl(e){let{interaction:t,lifecycle:n,shell:r,state:i}=e;return{staticItems:e.staticItems,transcriptKey:i.transcriptGeneration,handoffSuspended:n.handoffSuspended,updateNotice:n.updateNotice,coordinationError:e.coordination.error,coordinationPending:e.coordination.pending,sessionEventNotices:i.sessionEventNotices,isShuttingDown:i.isShuttingDown,stream:{text:i.streamingText,activeTools:i.activeTools,isThinking:i.isThinking,isStalled:i.isStalled,lastErrorMessage:i.lastErrorMessage},background:r.workspace.background,permissionRequest:i.permissionRequest,pendingUserAction:i.pendingUserAction,resolveUserAction:i.resolveUserAction,...t.overlays,theme:e.theme,contextPercentage:i.contextState.percentage,input:$c(e),status:el(e)}}function nl(e,t){return Yc({appearance:t.appearance,registry:e.themeRegistry,reducedMotion:e.reducedMotion,reducedMotionOverride:e.reducedMotionOverride,visible:t.screens.showThemePicker,setVisible:t.screens.setShowThemePicker,submit:e=>void t.screens.handleSubmit(e)})}function rl(e,t){let[n,r]=z(e);return{initialValue:n,consumeInitialValue:P(()=>r(void 0),[]),externalPromptOrigin:t===`external-link`}}function il(e,t,n){return L(()=>Qs({history:e,version:t,screenReader:n}),[e,n,t])}function al(e){let t=rl(e.initialInput,e.initialInputOrigin),n=Xc(e.channel),r=Tc(e.channel,e.startupUpdateNotice),i=Zc(e,r),a=Wc({state:n,setSessionName:r.setSessionName,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,showSessionPickerOnStart:e.showSessionPickerOnStart,coordinationBlocked:i.blocked}),o=bc({cwd:e.cwd,state:n,shell:a,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,pluginAdapter:e.pluginAdapter,transportRegistry:e.transportRegistry,recoveryError:i.error,recoveryPending:i.pending,coordinationBlocked:i.blocked,retryRecovery:e.sessionSwitchError===void 0?r.retryStart:e.onRetrySessionSwitch}),s=tl({props:e,state:n,lifecycle:r,shell:a,interaction:o,staticItems:il(n.history,e.version,o.screenReader),runtime:n.getRuntimeStatusSnapshot(e.permissionMode??`default`),coordination:i,theme:nl(e,a)});return{...s,input:{...s.input,...t}}}function ol(e){let t=al(e);return V(_t,{theme:t.theme.resolved,reducedMotion:t.theme.reducedMotion,syntaxHighlighting:t.theme.syntaxHighlighting,children:V(Zs,{viewModel:t})})}function sl(e){let[t,n]=z(()=>({channel:e.createChannel(e.resumeSessionId),sessionId:e.resumeSessionId})),[r,i]=z(e.showSessionPickerOnStart??!1),[a,o]=z(),[s,c]=z(!1),[l,u]=z(),d=R(!1),f=R(!0);I(()=>()=>{f.current=!1},[]);let p=P(async r=>{if(!d.current){d.current=!0,c(!0);try{if(i(!1),e.requestSessionSwitch)await e.requestSessionSwitch(r);else{if(await t.channel.stop(),!f.current)return;n({channel:e.createChannel(r),sessionId:r})}if(!f.current)return;u(void 0),o(void 0)}catch(e){let t=e instanceof Error?e.message:String(e);o(`Session switch failed: ${t}`),u(r)}finally{d.current=!1,c(!1)}}},[e.createChannel,e.requestSessionSwitch,t.channel]);return{state:t,showPicker:r,error:a,switching:s,switchSession:p,retrySwitch:P(()=>{l!==void 0&&p(l)},[l,p])}}function cl(e){let t=sl(e);return V(Ss,{value:e.cliAdapter,children:V(ol,{cwd:e.cwd,channel:t.state.channel,onSessionSwitch:t.switchSession,onRetrySessionSwitch:t.retrySwitch,sessionSwitchError:t.error,sessionSwitchPending:t.switching,showSessionPickerOnStart:t.showPicker,...e.initialInput===void 0?{}:{initialInput:e.initialInput},...e.initialInputOrigin===void 0?{}:{initialInputOrigin:e.initialInputOrigin},...e.providerType===void 0?{}:{providerType:e.providerType},...e.modelId===void 0?{}:{modelId:e.modelId},...e.permissionMode===void 0?{}:{permissionMode:e.permissionMode},...e.version===void 0?{}:{version:e.version},...e.sessionStore===void 0?{}:{sessionStore:e.sessionStore},...e.startupUpdateNotice===void 0?{}:{startupUpdateNotice:e.startupUpdateNotice},...e.transportRegistry===void 0?{}:{transportRegistry:e.transportRegistry},...e.pluginAdapter===void 0?{}:{pluginAdapter:e.pluginAdapter},...e.promptHistorySource===void 0?{}:{promptHistorySource:e.promptHistorySource},...e.promptHistoryProject===void 0?{}:{promptHistoryProject:e.promptHistoryProject},...e.themeRegistry===void 0?{}:{themeRegistry:e.themeRegistry},...e.reducedMotion===void 0?{}:{reducedMotion:e.reducedMotion},...e.reducedMotionOverride===void 0?{}:{reducedMotionOverride:e.reducedMotionOverride}},t.state.sessionId??`__new__`)})}var ll=class{options;attendedState=!0;focusObserved=!1;listeners=new Set;idleTimer;idleThresholdMs;constructor(e){this.options=e,this.idleThresholdMs=e.idleThresholdMs??3e5}get attended(){return this.attendedState}get source(){return this.focusObserved?`focus`:`idle`}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}start(){this.focusObserved||this.armIdleTimer()}focusIn(){this.observeFocus(),this.transition(!0)}focusOut(){this.observeFocus(),this.transition(!1)}keystroke(){this.focusObserved||(this.transition(!0),this.armIdleTimer())}observeFocus(){if(!this.options.focusReporting)throw Error(`AttentionTracker: a focus event arrived although focus reporting is off.`);this.focusObserved||(this.focusObserved=!0,this.idleTimer!==void 0&&clearTimeout(this.idleTimer),this.idleTimer=void 0)}dispose(){this.idleTimer!==void 0&&clearTimeout(this.idleTimer),this.idleTimer=void 0,this.listeners.clear()}armIdleTimer(){this.idleTimer!==void 0&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.transition(!1)},this.idleThresholdMs),typeof this.idleTimer==`object`&&`unref`in this.idleTimer&&this.idleTimer.unref()}transition(e){if(this.attendedState===e)return;this.attendedState=e;let t={kind:e?`returned`:`lost`,at:new Date(this.options.now()).toISOString()};for(let e of this.listeners)e(t)}};function ul(e,t){if(!t||!e.includes(27))return{forwarded:e,focusIn:0,focusOut:0};let n=e.toString(`latin1`),r=0,i=0,a=``,o=0;for(;o<n.length;)n.startsWith(`\x1B[I`,o)?(r+=1,o+=3):n.startsWith(`\x1B[O`,o)?(i+=1,o+=3):(a+=n[o],o+=1);return{forwarded:Buffer.from(a,`latin1`),focusIn:r,focusOut:i}}var dl=class extends ye{source;hooks;onData=e=>{let t=ul(typeof e==`string`?Buffer.from(e):e,this.hooks.negotiated());for(let e=0;e<t.focusOut;e+=1)this.hooks.onFocusOut();for(let e=0;e<t.focusIn;e+=1)this.hooks.onFocusIn();t.forwarded.length!==0&&(this.hooks.onKeystroke(),this.push(t.forwarded))};constructor(e,t){super({read(){}}),this.source=e,this.hooks=t,e.on(`data`,this.onData)}get isTTY(){return this.source.isTTY===!0}setRawMode(e){return this.source.setRawMode?.(e),this}ref(){return this.source.ref?.(),this}unref(){return this.source.unref?.(),this}asInkStdin(){return this}detach(){this.source.off(`data`,this.onData)}};function fl(e){if(e.enabled)return`[Screen reader mode: on via ${e.channel??`settings`}]`;if(e.hint===!0)return`[Screen reader mode: off — run with --screen-reader]`}function pl(e,t=e=>{process.stdout.write(e)}){let n=fl(e);n!==void 0&&t(`${n}\n`)}function ml(e){return e??(e=>{process.stderr.write(`${e}\n`)})}function hl(e,t,n,r,i){if(e===void 0||e.trim()===``)return n;let a=Number(e.trim());return!Number.isFinite(a)||!Number.isInteger(a)||a<0?(i(`${t}: ignoring "${e}" — expected a whole number of milliseconds. Using ${n}.`),n):a>r?(i(`${t}: clamping ${a} to the ${r} ms sanity bound.`),r):a}function gl(e){if(!e.enabled)return{startupQuietMs:0,preparkMs:0};let t=ml(e.warn);return{startupQuietMs:hl(e.overrides?.startupQuiet?.raw,e.overrides?.startupQuiet?.label??`startup quiet period`,900,6e5,t),preparkMs:hl(e.overrides?.prepark?.raw,e.overrides?.prepark?.label??`pre-write park`,50,5e3,t)}}function _l(e){return e?.isTTY!==!0||typeof e.setRawMode!=`function`?()=>{}:(e.setRawMode(!0),()=>{e.setRawMode?.(!1)})}async function vl(e,t){if(e<=0)return`elapsed`;let n=_l(t);return new Promise(r=>{let i=e=>{n(),t?.pause?.(),r(e)},a=()=>{clearTimeout(o),i(`keypress`)},o=setTimeout(()=>{t!==void 0&&t.off(`data`,a),i(`elapsed`)},e);o.unref?.(),t!==void 0&&(t.once(`data`,a),t.resume?.())})}function yl(e){return typeof e==`string`?e:Buffer.from(e).toString(`utf8`)}function bl(e){return W(e).trim().length>0}var xl=class{source;preparkMs;now;open;queue=[];timer;lastPrintableReleaseAt;echoArmed=!1;echoExpiryScheduled=!1;flushing=!1;drainWaiters=[];constructor(e){this.source=e.stdout,this.preparkMs=e.preparkMs,this.now=e.now??Date.now,this.on=((...e)=>this.source.on(...e)),this.off=((...e)=>this.source.off(...e))}get columns(){return this.source.columns??80}get rows(){return this.source.rows??24}get isTTY(){return this.source.isTTY??!1}get destroyed(){return this.source.destroyed??!1}get writable(){return this.source.writable??!0}get writableEnded(){return this.source.writableEnded??!1}get writableLength(){return this.source.writableLength??0}get writableNeedDrain(){return this.source.writableNeedDrain??!1}on;off;write(e,t,n){let r=typeof t==`function`?t:n,i=yl(e),a=this.open;if(a===void 0){let e={chunks:[],echo:this.echoArmed,printable:!1,barrier:!1};a=e,this.open=e,process.nextTick(()=>this.close(e))}return a.chunks.push({text:i,callback:r}),i.length===0?a.barrier=!0:!a.printable&&bl(i)&&(a.printable=!0),!this.writableNeedDrain}asInkStdout(){return this}armEchoRelease(){this.echoArmed=!0,!this.echoExpiryScheduled&&(this.echoExpiryScheduled=!0,setImmediate(()=>{this.echoArmed=!1,this.echoExpiryScheduled=!1}))}drain(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0);for(let e of this.queue.splice(0))this.release(e);return this.settled()}flush(){return this.flushing=!0,this.drain()}settled(){return this.open===void 0&&this.queue.length===0?Promise.resolve():new Promise(e=>{this.drainWaiters.push(e)})}close(e){if(this.open===e){if(this.open=void 0,this.isParked(e)){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0);for(let e of this.queue.splice(0))this.release(e)}this.queue.push(e),this.pump()}}isParked(e){return this.preparkMs>0&&this.lastPrintableReleaseAt!==void 0&&e.printable&&!e.echo&&!this.flushing}pump(){for(this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0);this.queue.length>0;){let e=this.queue[0];if(this.isParked(e)){let e=(this.lastPrintableReleaseAt??0)+this.preparkMs-this.now();if(e>0){this.timer=setTimeout(()=>{this.timer=void 0,this.pump()},e);return}}this.queue.shift(),this.release(e)}if(this.open===void 0){let e=this.drainWaiters;this.drainWaiters=[];for(let t of e)t()}}release(e){for(let t of e.chunks)this.source.write(t.text,t.callback);e.printable&&(this.lastPrintableReleaseAt=this.now())}};function Sl(e){return new xl(e)}function Cl(e){return{armEchoRelease:()=>e.armEchoRelease(),write:t=>{e.write(t)}}}function wl(e){let t=e.write??(e=>{process.stdout.write(e)}),n=!1;return{get negotiated(){return n},enable(){n||!e.supported()||(n=!0,t(`\x1B[?1004h`))},disable(){n&&(n=!1,t(`\x1B[?1004l`))}}}var Tl=class{hooks;instance;modeHooks;registerSuspendHooks(e){return this.hooks=e,()=>{this.hooks===e&&(this.hooks=void 0)}}setTerminalModeHooks(e){this.modeHooks=e}setInkInstance(e){this.instance=e}get canHandoffTerminal(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&this.hooks!==void 0}async runWithTerminal(e){let t=this.hooks;if(!this.canHandoffTerminal||t===void 0)throw Error(`TUI terminal handoff unavailable: no interactive TTY, or the App is not mounted.`);await t.suspend(),await this.modeHooks?.preSuspend(),this.instance?.clear();let n=process.stdin;n.isTTY&&typeof n.setRawMode==`function`&&n.setRawMode(!1),n.pause();try{return await e()}finally{n.isTTY&&typeof n.setRawMode==`function`&&n.setRawMode(!0),n.resume(),t.resume(),this.modeHooks?.postResume()}}};const El=new Set([`completed`,`failed`,`stopped`]);var Dl=class{lostAt;lastTurnSource=`user`;turnsFinished=0;wakeTurnsFinished=0;needsInputCount=0;errorCount=0;currentStates=new Map;reachedTerminal=new Map;baseline=new Map;baselinePending=!1;get away(){return this.lostAt!==void 0}onLost(e){this.lostAt=Date.parse(e),this.reset(),this.baseline=new Map(this.currentStates),this.baselinePending=this.currentStates.size===0}onReturned(e){if(this.lostAt===void 0)return;let t=Math.max(0,Date.parse(e)-this.lostAt);this.lostAt=void 0;let n=this.parts();if(this.reset(),n.length!==0)return Al(`While away ${kl(t)}: ${n.join(` · `)}`)}turnSource(e){this.lastTurnSource=e}turnCompleted(){this.away&&(this.turnsFinished+=1,this.lastTurnSource===`agent-wakeup`&&(this.wakeTurnsFinished+=1))}needsInput(){this.away&&(this.needsInputCount+=1)}error(){this.away&&(this.errorCount+=1)}entryState(e,t){if(this.currentStates.set(e,t),!this.away)return;if(this.baselinePending){this.baseline.set(e,t);return}let n=this.baseline.get(e),r=n!==void 0&&El.has(n);if(!El.has(t)||r){this.reachedTerminal.delete(e);return}this.reachedTerminal.set(e,t)}snapshotComplete(){this.baselinePending=!1}parts(){let e=[];if(this.turnsFinished>0){let t=this.wakeTurnsFinished>0?` (${this.wakeTurnsFinished} wake)`:``;e.push(`${this.turnsFinished} ${Ol(this.turnsFinished,`turn`)} finished${t}`)}this.needsInputCount>0&&e.push(`${this.needsInputCount} needs input`);let t={completed:0,failed:0,stopped:0};for(let e of this.reachedTerminal.values())e in t&&(t[e]+=1);for(let n of[`completed`,`failed`,`stopped`])t[n]>0&&e.push(`${t[n]} ${n}`);return this.errorCount>0&&e.push(`${this.errorCount} ${Ol(this.errorCount,`error`)}`),e}reset(){this.turnsFinished=0,this.wakeTurnsFinished=0,this.needsInputCount=0,this.errorCount=0,this.reachedTerminal.clear()}};function Ol(e,t){return e===1?t:`${t}s`}function kl(e){let t=Math.floor(e/6e4);if(t<1)return`<1m`;let n=Math.floor(t/60),r=t%60;return n===0?`${r}m`:r===0?`${n}h`:`${n}h ${r}m`}function Al(e){return e.length<=120?e:`${e.slice(0,119)}…`}var jl=class{options;recap=new Dl;unsubscribe;now;constructor(e){this.options=e,this.now=e.now??Date.now}wire(){this.unsubscribe===void 0&&(this.options.source.attended||this.recap.onLost(new Date(this.now()).toISOString()),this.unsubscribe=this.options.source.subscribe(e=>{if(e.kind===`lost`){this.recap.onLost(e.at);return}let t=this.recap.onReturned(e.at);t!==void 0&&this.options.onRecap(t)}))}unwire(){this.unsubscribe?.(),this.unsubscribe=void 0}onTurnSource=e=>{this.recap.turnSource(e)};onComplete=()=>{this.recap.turnCompleted()};onError=()=>{this.recap.error()};onNeedsInput=()=>{this.recap.needsInput()};onWorkspaceSnapshot=e=>{for(let t of e.entries)t.kind!==`main_thread`&&this.recap.entryState(t.id,t.state);this.recap.snapshotComplete()}};function Ml(e){return/not initialized/i.test(e.message)}function Nl(e){let t=e.isBenignError??Ml,n=null,r=0,i;function a(){n!==null&&(clearInterval(n),n=null)}function o(){r+=e.intervalMs;try{e.check()}catch(n){let o=n instanceof Error?n:Error(String(n));if(!t(o)){a(),e.onFailure({kind:`error`,error:o});return}i=o,r>=e.timeoutMs&&(a(),e.onFailure({kind:`timeout`,lastError:i}));return}a(),e.onReady()}return{start(){n===null&&(r=0,n=setInterval(o,e.intervalMs))},stop:a}}function Pl(e,t,n,r,o){if(e.data?.pluginRegistryReloaded===!0&&o?.(n),r.addEntry(a(i(e.message))),t.isInitialized){let e=t.getContextState();r.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})}}function Fl(e){let t=e.slice(1).split(/\s+/);return{name:t[0]?.toLowerCase()??``,args:t.slice(1).join(` `)}}var Il=class extends AggregateError{},Ll=class{operations;defaultShutdownTimeoutMs;started=!1;startPromise;teardownBegun=!1;stopped=!1;shuttingDown=!1;shutdownPromise;stopPromise;constructor(e,t){this.operations=e,this.defaultShutdownTimeoutMs=t}get isShuttingDown(){return this.shuttingDown}get isActiveForPeerStatus(){return this.started&&!this.teardownBegun&&!this.shuttingDown}async start(){if(this.teardownBegun)throw Error(`Cannot start a channel after teardown has begun.`);if(this.started)return;let e=this.startPromise??=this.operations.start();try{await e,this.started=!0}catch(e){throw e instanceof Il&&(this.teardownBegun=!0),e}finally{this.startPromise===e&&(this.startPromise=void 0)}}async stop(){if(this.teardownBegun=!0,!this.stopped){this.stopPromise??=this.performStop();try{await this.stopPromise}catch(e){throw this.stopPromise=void 0,e}}}async performStop(){let e=this.startPromise,t;if(e!==void 0)try{await e}catch(e){t=e instanceof Error?e:Error(String(e))}let n;try{await this.operations.stop()}catch(e){n=e instanceof Error?e:Error(String(e))}if(this.shutdownPromise??=this.shutdownSessionBounded({reason:`other`,message:`channel stopped`},this.defaultShutdownTimeoutMs),await this.shutdownPromise,n!==void 0&&t!==void 0)throw AggregateError([t,n],`TUI channel start and teardown both failed.`);if(n!==void 0)throw n;if(this.started=!1,this.stopped=!0,t!==void 0)throw t}async shutdown(e){this.teardownBegun=!0,this.shuttingDown||(this.shuttingDown=!0,this.operations.beginShutdown());let t=this.stopPromise;if(t!==void 0){await t.catch(()=>void 0);return}this.shutdownPromise??=this.performShutdown(e),await this.shutdownPromise}async performShutdown(e){let t=this.startPromise;t!==void 0&&await t.catch(()=>void 0),await this.shutdownSessionBounded({reason:e?.reason??`prompt_input_exit`,message:`CLI shutdown`},e?.timeoutMs??this.defaultShutdownTimeoutMs)}async shutdownSessionBounded(e,t){let n,r=new Promise(e=>{n=setTimeout(e,t),n.unref?.()});await Promise.race([this.operations.shutdownSession(e).catch(()=>void 0),r]),n&&clearTimeout(n)}},Rl=class{onChange;entries=[];processing=!1;constructor(e){this.onChange=e}get current(){return this.processing?this.entries[0]?.presentedRequest??null:null}enqueue(e,t){return new Promise(n=>{this.entries.push({presentedRequest:{...e},resolve:n,...t===void 0?{}:{id:t}}),this.processNext()})}resolveCurrent(e,t){if(this.entries[0]?.presentedRequest!==e)return;let n=this.entries.shift();n&&(this.processing=!1,this.onChange(),n.resolve(t),this.processNext())}dismissById(e){let t=this.entries.filter(t=>t.id===e);if(t.length===0)return!1;this.entries=this.entries.filter(t=>t.id!==e),this.processing=!1;for(let e of t)e.resolve({type:`cancelled`});return this.processNext(),!0}cancelAll(){let e=this.entries;this.entries=[],this.processing=!1;for(let t of e)t.resolve({type:`cancelled`});this.onChange()}processNext(){if(!this.processing){if(!this.entries[0]){this.onChange();return}this.processing=!0,this.onChange()}}},zl=class{onChange;entries=[];processing=!1;currentRequest=null;constructor(e){this.onChange=e}get current(){return this.currentRequest}enqueue(e,t,n,r,i,a){return new Promise(o=>{this.entries.push({toolName:e,toolArgs:t,resolve:o,...n===void 0?{}:{id:n},...r===void 0?{}:{canPersistProjectPermission:r},...i===void 0?{}:{requestedByPeer:i},...a===void 0?{}:{requester:a}}),this.processNext()})}dismissById(e){let t=this.entries.filter(t=>t.id===e);if(t.length===0)return!1;let n=this.entries[0]?.id===e;this.entries=this.entries.filter(t=>t.id!==e);for(let e of t)e.resolve(!1);return n&&(this.processing=!1,this.currentRequest=null,this.processNext()),!0}cancelAll(){let e=this.entries;this.entries=[],this.processing=!1,this.currentRequest=null;for(let t of e)t.resolve(!1);this.onChange()}processNext(){if(this.processing)return;let e=this.entries[0];if(!e){this.currentRequest=null,this.onChange();return}this.processing=!0,this.currentRequest={toolName:e.toolName,toolArgs:e.toolArgs,...e.canPersistProjectPermission===void 0?{}:{canPersistProjectPermission:e.canPersistProjectPermission},...e.requestedByPeer===void 0?{}:{requestedByPeer:e.requestedByPeer},...e.requester===void 0?{}:{requester:e.requester},resolve:t=>{this.entries[0]===e&&(this.entries.shift(),this.processing=!1,this.currentRequest=null,e.resolve(t),setTimeout(()=>this.processNext(),0))}},this.onChange()}};function Bl(e,t){let n=null;try{n=t.getActiveDriverId?.()??null}catch{n=null}return a(s(e,n?{metadata:{driverId:n}}:{}))}function Vl(e,t){e(`plan_event`,e=>t.addSessionEventNotice({event:`plan_event`,payload:e})),e(`context_file_refreshed`,e=>t.addSessionEventNotice({event:`context_file_refreshed`,payload:e})),e(`branch_event`,e=>t.addSessionEventNotice({event:`branch_event`,payload:e}))}function Hl(e,t,n,r,i){let a=((...e)=>{try{n(...e)}catch(e){let n=e instanceof Error?e:Error(String(e));try{r(n,t)}catch{}}});e.on(t,a),i.push({event:t,handler:a})}var Ul=class{options;bindings=[];constructor(e){this.options=e}wire(){if(this.bindings.length>0)return;let{session:e,manager:t,attention:r}=this.options,i=n=>{t.addUserEcho(Bl(n,e))},a=()=>t.syncHistory(e.getFullHistory());this.bind(`user_message`,i),this.bind(`text_delta`,t.onTextDelta),this.bind(`tool_start`,t.onToolStart),this.bind(`tool_end`,t.onToolEnd),this.bind(`thinking`,t.onThinking),this.bind(`complete`,e=>{t.onComplete(e),r?.onComplete(),a()}),this.bind(`interrupted`,t.onInterrupted),this.bind(`error`,e=>{t.onError(e),r?.onError(),a()}),this.bind(`context_update`,t.onContextUpdate),this.bind(`compact`,a),this.bind(`skill_activation`,a),this.bind(`memory_event`,a),this.bind(`execution_workspace_event`,e=>{t.syncExecutionWorkspaceSnapshot(e.snapshot),r?.onWorkspaceSnapshot(e.snapshot)}),this.bind(`history_cleared`,()=>t.clearHistory()),this.bind(`turn_source`,e=>r?.onTurnSource(e)),Vl(this.bind.bind(this),t),this.bind(`permission_request`,({id:t,toolName:i,toolArgs:a,canPersistProjectPermission:o,requesterDriverId:s,requester:c})=>{r?.onNeedsInput();let l=s?.startsWith(`peer:`)?n(s):void 0;this.options.requestPermission(i,a,t,o,l,c).then(n=>e.resolvePermission(t,n)).catch(()=>e.resolvePermission(t,!1))}),this.bind(`ask_request`,({id:t,request:n})=>{r?.onNeedsInput(),this.options.askUser(n,t).then(n=>e.resolveAsk(t,n)).catch(()=>e.resolveAsk(t,{type:`cancelled`}))}),this.bind(`prompt_resolved`,({id:e})=>this.options.dismissPrompt(e)),r?.wire()}unwire(){let{session:e}=this.options;this.options.attention?.unwire();for(let{event:t,handler:n}of this.bindings)e.off(t,n);this.bindings.length=0}bind(e,t){Hl(this.options.session,e,t,t=>{let n=this.options.onDeliveryError;n?n(t,e):this.options.manager.addSessionEventDeliveryError(t,e)},this.bindings)}};function Wl(e){return{cwd:e.cwd,...e.livePromptTrace?{livePromptTrace:e.livePromptTrace}:{},provider:e.provider,...e.providerErrorGuidance===void 0?{}:{providerErrorGuidance:e.providerErrorGuidance},...e.promptFileReferenceTag===void 0?{}:{promptFileReferenceTag:e.promptFileReferenceTag},...e.modelCommandToolPrefix===void 0?{}:{modelCommandToolPrefix:e.modelCommandToolPrefix},...e.subagentHookEnvironmentNames===void 0?{}:{subagentHookEnvironmentNames:e.subagentHookEnvironmentNames},...e.observerFailureWarningCode===void 0?{}:{observerFailureWarningCode:e.observerFailureWarningCode},...e.commandHookShell===void 0?{}:{commandHookShell:e.commandHookShell},...e.bare===!0?{bare:!0}:{},...e.skipConfiguredHooks===!0?{skipConfiguredHooks:!0}:{},...e.orgPolicy===void 0?{}:{orgPolicy:e.orgPolicy},...e.projectAccess===void 0?{}:{projectAccess:e.projectAccess},...e.projectSettingsPaths===void 0?{}:{projectSettingsPaths:e.projectSettingsPaths},...e.baselinePermissionAllow===void 0?{}:{baselinePermissionAllow:e.baselinePermissionAllow},...e.taskContext===void 0?{}:{taskContext:e.taskContext},...e.contributionSources===void 0?{}:{contributionSources:e.contributionSources},...e.skillRoots===void 0?{}:{skillRoots:e.skillRoots},...e.userSettingsSources===void 0?{}:{userSettingsSources:e.userSettingsSources},...e.environment===void 0?{}:{environment:e.environment},...e.resolveProviderCredential===void 0?{}:{resolveProviderCredential:e.resolveProviderCredential},...e.editCheckpointStore===void 0?{}:{editCheckpointStore:e.editCheckpointStore},...e.externalEventVerifierFactory===void 0?{}:{externalEventVerifierFactory:e.externalEventVerifierFactory},...e.externalEventGrantHistory===void 0?{}:{externalEventGrantHistory:e.externalEventGrantHistory},...e.model===void 0?{}:{model:e.model},...e.effort===void 0?{}:{effort:e.effort},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt},...e.responseFormat===void 0?{}:{responseFormat:e.responseFormat},...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},permissionMode:e.permissionMode,maxTurns:e.maxTurns,sessionStore:e.sessionStore,disableSessionLoops:e.disableSessionLoops,resolveDefaultLoopPrompt:e.resolveDefaultLoopPrompt,resumeSessionId:e.resumeSessionId,forkSession:e.forkSession,...e.workspaceMovedFrom===void 0?{}:{workspaceMovedFrom:e.workspaceMovedFrom},sessionName:e.sessionName,autoName:!0,backgroundTaskRunners:e.backgroundTaskRunners,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.agentDefinitions===void 0?{}:{agentDefinitions:e.agentDefinitions},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.pluginDirectories===void 0?{}:{pluginDirectories:e.pluginDirectories},...e.additionalTools===void 0?{}:{additionalTools:e.additionalTools},...e.defaultTools===void 0?{}:{defaultTools:e.defaultTools},...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},...e.sandboxClient===void 0?{}:{sandboxClient:e.sandboxClient},commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,...e.remoteCommandPolicy?{remoteCommandPolicy:e.remoteCommandPolicy}:{},language:e.language,agentName:e.agentName,activePresetId:e.activePresetId,persona:e.persona,systemPrompt:e.systemPrompt,appendSystemPrompt:e.appendSystemPrompt,allowedTools:e.allowedTools,deniedTools:e.deniedTools,enableParallelSubagents:e.enableParallelSubagents,selfVerification:e.selfVerification,terminalHandoff:e.terminalHandoff,...e.providerDefinitions?{providerDefinitions:e.providerDefinitions}:{},...e.memoryStore?{memoryStore:e.memoryStore}:{},...e.automaticMemory?{automaticMemory:e.automaticMemory}:{},...e.recallMemory?{recallMemory:e.recallMemory}:{},...e.promptHistory?{promptHistory:e.promptHistory}:{}}}function Gl(e,t){switch(t.event){case`plan_event`:return{id:e,event:t.event,message:`Plan ${t.payload.type.replaceAll(`_`,` `)}`};case`context_file_refreshed`:return{id:e,event:t.event,message:`Context refreshed: ${t.payload.filePath}`};case`branch_event`:return{id:e,event:t.event,message:`Branch ${t.payload.kind.replaceAll(`_`,` `)}: ${t.payload.branchId} @ ${t.payload.checkpointId}`}}}var Kl=class{sequence=0;notices=[];add(e){this.append(Gl(this.nextId(),e))}addDeliveryError(e,t){this.append({id:this.nextId(),event:`delivery-error`,message:`Session event delivery failed (${t}): ${e.message}`})}addAttentionRecap(e){this.append({id:this.nextId(),event:`attention-recap`,message:e})}nextId(){return this.sequence+=1,`session-event-${this.sequence}`}append(e){this.notices.push(e);let t=this.notices.length-50;t>0&&this.notices.splice(0,t)}};function ql(e,t){let n=null;return{schedule(){n||=setTimeout(()=>{n=null,e()},t)},flush(){n&&=(clearTimeout(n),null)}}}var Jl=class{history=[];localNotices=[];streamingText=``;activeTools=[];isThinking=!1;isAborting=!1;pendingPrompt=null;contextState={percentage:0,usedTokens:0,maxTokens:0};executionWorkspaceSnapshot=null;selectedExecutionEntryId;lastErrorMessage=null;isStalled=!1;sessionNoticeStore=new Kl;sessionEventNotices=this.sessionNoticeStore.notices;onChange=null;streamBuf=``;debouncedStreamNotify=ql(()=>this.notify(),300);stallTimer=null;armStallTimer(){this.clearStallTimer(),this.stallTimer=setTimeout(()=>{this.stallTimer=null,this.isStalled=!0,this.notify()},15e3)}clearStallTimer(){this.stallTimer&&=(clearTimeout(this.stallTimer),null),this.isStalled&&=!1}notify(){this.onChange?.()}onTextDelta=e=>{this.isThinking&&this.armStallTimer(),this.streamBuf+=e,this.streamingText=this.streamBuf,this.debouncedStreamNotify.schedule()};onToolStart=e=>{this.clearStallTimer(),this.activeTools=[...this.activeTools,e],this.notify()};onToolEnd=e=>{let t=e.executionId===void 0?this.activeTools.findLastIndex(t=>t.toolName===e.toolName&&t.isRunning):this.activeTools.findIndex(t=>t.executionId===e.executionId&&t.isRunning);if(t!==-1){let n=[...this.activeTools];n[t]=e,this.activeTools=n}this.isThinking&&!this.activeTools.some(e=>e.isRunning)&&this.armStallTimer(),this.notify()};onThinking=e=>{this.isThinking=e,e?(this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.lastErrorMessage=null,this.armStallTimer()):(this.isAborting=!1,this.activeTools=[],this.clearStallTimer()),this.notify()};onComplete=e=>{this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.contextState={percentage:e.contextState.usedPercentage,usedTokens:e.contextState.usedTokens,maxTokens:e.contextState.maxTokens},this.notify()};onInterrupted=()=>{this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onError=e=>{this.clearStallTimer(),this.lastErrorMessage=e?.message??`Unknown error`,this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onContextUpdate=e=>{this.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})};syncHistory(e){e.length!==0&&(this.history=this.withLocalNotices(e),this.notify())}syncHostHistory(e,t){this.history=[...this.withLocalNotices(e),...t],this.notify()}withLocalNotices(e){let t=[],n=0;for(let r of this.localNotices){let i=Math.min(r.afterSessionEntries,e.length);for(;n<i;)t.push(e[n++]);t.push(r.entry)}for(;n<e.length;)t.push(e[n++]);return t}addEntry(e){this.localNotices.push({entry:e,afterSessionEntries:this.history.length-this.localNotices.length}),this.history=[...this.history,e],this.notify()}addUserEcho(e){this.history=[...this.history,e],this.notify()}clearHistory(){this.history=[],this.localNotices=[],this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()}setPendingPrompt(e){this.pendingPrompt=e,this.notify()}setAborting(e){this.isAborting=e,this.notify()}setContextState(e){this.contextState=e,this.notify()}addSessionEventNotice(e){this.sessionNoticeStore.add(e),this.notify()}addAttentionRecap(e){this.sessionNoticeStore.addAttentionRecap(e),this.notify()}addSessionEventDeliveryError(e,t){this.sessionNoticeStore.addDeliveryError(e,t),this.notify()}syncExecutionWorkspaceSnapshot(e){let t=this.selectedExecutionEntryId,n=t!==void 0&&e.entries.some(e=>e.id===t)?t:e.selectedEntryId??e.entries[0]?.id;this.executionWorkspaceSnapshot={...e,...n?{selectedEntryId:n}:{}},this.selectedExecutionEntryId=n,this.notify()}selectExecutionWorkspaceEntry(e){this.executionWorkspaceSnapshot?.entries.some(t=>t.id===e)&&(this.selectedExecutionEntryId=e,this.executionWorkspaceSnapshot={...this.executionWorkspaceSnapshot,selectedEntryId:e},this.notify())}dispose(){this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.onChange=null}};function Yl(e){switch(e.kind){case`none`:return;case`several`:return e.message;case`stopped`:return`Loop ${e.loopId} stopped by Esc.`;case`failed`:return e.message}}const Xl=15e3;var Zl=class{stateManager;interactiveSession;registry;opts;submitHandler=null;userActions;permissions;eventProjector;attention;lifecycle;availableCommands=[];sessionName;initPoller=null;get terminalHandoffController(){return this.opts.terminalHandoff}onChange=null;constructor(e){this.opts=e,this.sessionName=e.sessionName,this.stateManager=new Jl,this.stateManager.onChange=()=>this.onChange?.(),this.userActions=new Rl(()=>this.onChange?.()),this.permissions=new zl(()=>this.onChange?.()),this.interactiveSession=this.createSession(),this.registry=this.createRegistry(),this.attention=this.createAttention(e.attention),this.eventProjector=new Ul({session:this.interactiveSession,manager:this.stateManager,...this.attention?{attention:this.attention}:{},requestPermission:(e,t,n,r,i,a)=>this.permissions.enqueue(e,t,n,r,i,a),askUser:(e,t)=>this.askUser(e,t),dismissPrompt:e=>this.dismissPromptById(e),...e.onSessionEventDeliveryError?{onDeliveryError:e.onSessionEventDeliveryError}:{}}),this.lifecycle=new Ll({start:()=>this.startRuntime(),stop:async()=>{this.eventProjector.unwire(),this.cancelAllPermissions(),this.cancelAllUserActions(),this.stopInitCheck(),this.onChange=null,this.stateManager.dispose(),await this.stopTransports()},beginShutdown:()=>{this.cancelAllUserActions(),this.cancelAllPermissions(),this.stateManager.addEntry(a(i(`Shutting down...`))),this.onChange?.()},shutdownSession:async({reason:e,message:t})=>{await this.interactiveSession.shutdown({reason:e,message:t})}},5e3)}async startRuntime(){let e=!1;try{this.eventProjector.wire(),this.syncRestoredHistory(),this.startInitCheck(),this.opts.transportRegistry&&(e=!0,await this.opts.bindTransports?.(this.interactiveSession),await this.opts.transportRegistry.startAll())}catch(t){if(this.eventProjector.unwire(),this.stopInitCheck(),e&&this.opts.transportRegistry)try{await this.stopTransports()}catch(e){throw new Il([t,...e instanceof AggregateError?e.errors:[e]],`TUI channel start failed and transport rollback also failed.`)}throw t}}async stopTransports(){if(!this.opts.transportRegistry)return;let e=await this.opts.transportRegistry.stopAll();if(e.errors.length>0)throw AggregateError(e.errors,`TUI transport teardown failed.`)}get permissionRequest(){return this.permissions.current}get pendingUserAction(){return this.userActions.current}get isShuttingDown(){return this.lifecycle.isShuttingDown}get isActiveForPeerStatus(){return this.lifecycle.isActiveForPeerStatus}createSession(){return se(Wl(this.opts))}createRegistry(){let e=new te;for(let t of this.opts.commandModules??[])e.addModule(t);return this.opts.reloadPluginCommandSource?.(e),e}onSubmit(e){this.submitHandler=e}setAvailableCommands(e){this.availableCommands=e,this.onChange?.()}setBusy(e){this.stateManager.onThinking(e)}async start(){await this.lifecycle.start()}async stop(){await this.lifecycle.stop()}getSession(){return this.interactiveSession}getRegistry(){return this.registry}subscribe(e){return this.onChange=e,()=>{this.onChange===e&&(this.onChange=null)}}getSnapshot(){let e=this.stateManager;return{history:e.history,streamingText:e.streamingText,activeTools:e.activeTools,isThinking:e.isThinking,isAborting:e.isAborting,lastErrorMessage:e.lastErrorMessage,isStalled:e.isStalled,sessionEventNotices:e.sessionEventNotices,isShuttingDown:this.isShuttingDown,pendingPrompt:e.pendingPrompt,pendingCount:this.interactiveSession.getPendingCount(),executionWorkspaceSnapshot:e.executionWorkspaceSnapshot,...e.selectedExecutionEntryId===void 0?{}:{selectedExecutionEntryId:e.selectedExecutionEntryId},permissionRequest:this.permissionRequest,pendingUserAction:this.pendingUserAction,contextState:e.contextState}}getCommandQueryPort(){return this.registry}getSessionUiEventPort(){return this.interactiveSession}getRuntimeStatusSnapshot(e){try{let e=this.interactiveSession.getSession(),t=e.getActivePresetId?.(),n=e.getModelEffort();return{permissionMode:e.getPermissionMode(),sessionId:e.getSessionId(),...t===void 0?{}:{activePresetId:t},...n===void 0?{}:{effort:n}}}catch{return{permissionMode:e,sessionId:``}}}addEntry(e){this.stateManager.addEntry(e)}abort(){this.stateManager.setAborting(!0),this.cancelAllUserActions(),this.cancelAllPermissions(),this.interactiveSession.abort()}cancelQueue(){this.interactiveSession.cancelQueue(),this.cancelAllUserActions(),this.cancelAllPermissions(),this.stateManager.setPendingPrompt(null)}async stopWaitingSelfPacedLoop(){let e=Yl(await this.interactiveSession.stopWaitingSelfPacedLoop(`Loop stopped by Esc`));e!==void 0&&this.addEntry(a(i(e)))}async shutdown(e){await this.lifecycle.shutdown(e)}selectExecutionWorkspaceEntry(e){this.stateManager.selectExecutionWorkspaceEntry(e)}async readExecutionWorkspaceDetail(e){return this.interactiveSession.readExecutionWorkspaceDetail(e)}async sendAgentJob(e,t){await this.interactiveSession.sendAgentJob(e,t)}setSessionName(e){this.sessionName=e,this.interactiveSession.setName(e),this.onChange?.()}async askUser(e,t){return this.userActions.enqueue(e,t)}resolveUserAction(e,t){this.userActions.resolveCurrent(e,t)}cancelAllUserActions(){this.userActions.cancelAll()}async handleInput(e){if(!e.startsWith(`/`)){await this.interactiveSession.submit(e),this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}await this.handleSlashCommand(e)}async handleSlashCommand(e){let{name:t,args:n}=Fl(e),r=await this.interactiveSession.executeCommand(t,n);if(r){if(r.data?.sessionExecution===!0){this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}Pl(r,this.interactiveSession,this.registry,this.stateManager,this.opts.reloadPluginCommandSource);return}this.stateManager.addEntry(a(i(`Unknown command "/${t}". Type /help for help.`)))}handlePermissionRequest(e,t,n){return this.permissions.enqueue(e,t,n)}dismissPromptById(e){this.userActions.dismissById(e),this.permissions.dismissById(e)}cancelAllPermissions(){this.permissions.cancelAll()}syncRestoredHistory(){if(this.stateManager.history.length===0){let e=this.interactiveSession.getFullHistory();e.length>0&&this.stateManager.syncHistory(e)}}startInitCheck(){this.stopInitCheck(),this.initPoller=Nl({check:()=>this.runInitCheck(),intervalMs:200,timeoutMs:Xl,onReady:()=>void 0,onFailure:e=>this.onInitFailure(e)}),this.initPoller.start()}runInitCheck(){let e=this.interactiveSession.getContextState(),t=this.interactiveSession.getName();t&&t!==this.sessionName&&(this.sessionName=t,this.onChange?.()),this.stateManager.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens});let n=this.interactiveSession.getFullHistory();n.length>0&&this.stateManager.syncHistory(n),this.syncExecutionWorkspace()}createAttention(e){if(e)return new jl({source:e,onRecap:e=>this.stateManager.addAttentionRecap(e)})}onInitFailure(e){let t=e.kind===`timeout`?`Session initialization timed out after ${Xl/on}s${e.lastError?` (last error: ${e.lastError.message})`:``}`:`Session initialization failed: ${e.error.message}`;this.stateManager.onError(),this.stateManager.addEntry({id:`session-init-error-${Date.now()}`,timestamp:new Date,category:`event`,type:`session-init-error`,data:{message:t}})}stopInitCheck(){this.initPoller?.stop(),this.initPoller=null}syncExecutionWorkspace(){try{this.stateManager.syncExecutionWorkspaceSnapshot(this.interactiveSession.getExecutionWorkspaceSnapshot({selectedEntryId:this.stateManager.selectedExecutionEntryId}))}catch{}}};function Ql(e,t){if(e.category!==`chat`||e.type!==`user`)return!1;let n=e.data;return typeof n==`object`&&!!n&&`content`in n&&n.content===t}var $l=class{options;known=[];read;followUp;echoes=[];constructor(e){this.options=e}get behind(){return this.read!==void 0||this.followUp!==void 0}readTail(){if(this.read!==void 0){this.followUp??=`tail`;return}this.start(!1)}reload(){if(this.read!==void 0){this.followUp=`reload`;return}this.start(!0)}restart(){this.read=void 0,this.followUp=void 0,this.start(!0)}reset(){this.known=[],this.read=void 0,this.followUp=void 0,this.echoes=[]}onPage(e){let t=this.read;if(t===void 0)return;if(e.startIndex!==t.next){e.total<t.next&&this.restart();return}if(t.entries.push(...this.options.revive(e.entries)),t.next+=e.entries.length,t.next<e.total&&e.entries.length>0){this.options.request(t.next)||(this.read=void 0);return}this.read=void 0,this.known=t.reload?t.entries:[...this.known,...t.entries];let n=this.followUp;this.followUp=void 0,n!==void 0&&this.start(n===`reload`),this.show()}echo(e,t){this.echoes.push({entry:e,content:t,after:this.known.length,shown:!1}),this.show()}start(e){let t=e?0:this.known.length;this.read={reload:e,entries:[],next:t},this.options.request(t)||(this.read=void 0)}show(){if(this.echoes=this.unrecordedEchoes(),!this.behind)for(let e of this.echoes)e.shown=!0;this.options.show(this.known,this.echoes.filter(e=>e.shown).map(e=>e.entry))}unrecordedEchoes(){let e=0;return this.echoes.filter(t=>{let n=Math.max(e,t.after),r=this.known.findIndex((e,r)=>r>=n&&Ql(e,t.content));return r===-1?!0:(e=r+1,!1)})}};const eu=`appearance-settings-patch`;function tu(e){return e instanceof Error?e.message:String(e)}function nu(e){return{result:{success:!1,message:e},uiIntents:[]}}function ru(e,t){return e?.commands.find(e=>e.name===t)}async function iu(e,t,n,r){let i=await e.execute(n,t);if(!i.success)return{result:i,uiIntents:[]};let a=[];for(let e of i.hostActions??[]){if(e.type!==eu)return nu(`Cannot apply '${e.type}' on this terminal.`);if(!v(e.patch))return nu(`Failed to apply '${eu}': invalid appearance settings patch`);a.push(e.patch)}for(let e of a)try{await r.writeAppearanceSettings(e)}catch(e){return nu(`Failed to apply '${eu}': ${tu(e)}`)}return{result:{message:i.message,success:i.success,...i.data===void 0?{}:{data:i.data}},uiIntents:i.uiIntents??[]}}function au(e){let t=new h(e.terminalHandoff),{cwd:n}=e;return{canHandoffTerminal:()=>t.canHandoffTerminal(),runWithTerminal:e=>t.runWithTerminal(e),getCwd:()=>n,getCommandInvocationSource:()=>`user`}}function ou(e,t){return e!==void 0&&e===t?T:e}function su(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cu(e,t){if(!su(e))return e;let n=e;typeof e.timestamp==`string`&&(n={...n,timestamp:new Date(e.timestamp)});let r=e.metadata;return t!==void 0&&su(r)&&r.driverId===t&&(n={...n,metadata:{...r,driverId:T}}),n}function lu(e,t){return e.map(e=>{let n=new Date(e.timestamp);if(e.category!==`chat`||e.data===void 0)return{...e,timestamp:n};let r=t!==void 0&&n.getTime()>=t.since?t.driverId:void 0;return{...e,timestamp:n,data:cu(e.data,r)}})}function uu(e){return{name:e.name,description:e.description,source:`builtin`,...e.displayName===void 0?{}:{displayName:e.displayName},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint}}}function du(e,t){return[...e.map(e=>({name:e.name,description:e.description,source:`builtin`,modelInvocable:e.modelInvocable,...e.displayName===void 0?{}:{displayName:e.displayName},...e.example===void 0?{}:{example:e.example},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.subcommands!==void 0&&e.subcommands.length>0?{subcommands:e.subcommands.map(uu)}:{}})),...t.filter(e=>e.userInvocable).map(e=>({name:e.name,description:e.description,source:e.source,modelInvocable:e.modelInvocable,userInvocable:e.userInvocable,...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.context===void 0?{}:{context:e.context},...e.agent===void 0?{}:{agent:e.agent}}))]}function fu(e,t){let n=t.toLowerCase();return e.find(e=>e.name.toLowerCase()===n&&e.subcommands!==void 0)?.subcommands??[]}function pu(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>e.name.toLowerCase().startsWith(n))}const mu=[`get-context`,`get-commands`,`get-status`,`get-executing`,`get-pending`,`get-execution-workspace`],hu=[...mu,`get-prompts`],gu=[`get-context`,`get-status`,`get-commands`],_u=new Set([`exit`,`quit`]),vu=new Set([`show-plugin-manager`,`show-settings`]);function yu(e){return e instanceof Error?e.message:String(e)}var bu=class{handlers={ui_intent:new Set,session_renamed:new Set};on(e,t){this.handlers[e].add(t)}off(e,t){this.handlers[e].delete(t)}emitUiIntent(e){for(let t of[...this.handlers.ui_intent])t(e)}emitSessionRenamed(e){for(let t of[...this.handlers.session_renamed])t(e)}},xu=class{options;sessionName;manager;userActions;permissions;attention;lifecycle;uiEvents=new bu;clientCommands;commandQueryPort={getCommands:e=>pu(this.commandCatalog,e),getSubcommands:e=>fu(this.commandCatalog,e)};readOnly;commandCatalog=[];status;pendingCount=0;hostSessions;sessionListSequence=0;sessionListRequestId;pendingPicker;hostHistory;own;pendingCommands=new Map;commandSequence=0;pendingDetails=new Map;detailSequence=0;pendingLoopStops=new Map;loopStopSequence=0;pendingTaskSends=new Map;pendingSessionChange;sessionChangeSequence=0;promptGeneration=0;shownPromptIds=new Set;settledPromptIds=new Set;transcriptGeneration=0;unsubscribers=[];detached=!1;ended=!1;onChange=null;constructor(e){this.options=e,this.sessionName=e.sessionName,this.readOnly=e.role===`observe`,this.manager=this.createManager(),this.clientCommands=e.clientCommands===void 0?void 0:{set:e.clientCommands,host:au({terminalHandoff:e.terminalHandoff,cwd:e.cwd})},this.hostHistory=new $l({request:e=>this.send(e===0?{type:`get-history`}:{type:`get-history`,fromIndex:e}),show:(e,t)=>this.manager.syncHostHistory(e,t),revive:e=>lu(e,this.own)}),this.userActions=new Rl(()=>this.notify()),this.permissions=new zl(()=>this.notify()),this.attention=e.attention?new jl({source:e.attention,onRecap:e=>this.manager.addAttentionRecap(e)}):void 0,this.lifecycle=new Ll({start:async()=>this.attach(),stop:async()=>{this.detach(),this.attention?.unwire(),this.onChange=null,this.manager.dispose()},beginShutdown:()=>{this.detach(),this.notice(`Detached. The session keeps running.`)},shutdownSession:async()=>void 0},0)}get terminalHandoffController(){return this.options.terminalHandoff}async start(){await this.lifecycle.start()}async stop(){await this.lifecycle.stop()}async shutdown(e){await this.lifecycle.shutdown(e)}subscribe(e){return this.onChange=e,()=>{this.onChange===e&&(this.onChange=null)}}getSnapshot(){let e=this.manager;return{history:e.history,streamingText:e.streamingText,activeTools:e.activeTools,isThinking:e.isThinking,isAborting:e.isAborting,lastErrorMessage:e.lastErrorMessage,isStalled:e.isStalled,sessionEventNotices:e.sessionEventNotices,isShuttingDown:this.lifecycle.isShuttingDown,pendingPrompt:e.pendingPrompt,pendingCount:e.pendingPrompt===null?0:Math.max(this.pendingCount,1),executionWorkspaceSnapshot:e.executionWorkspaceSnapshot,...e.selectedExecutionEntryId===void 0?{}:{selectedExecutionEntryId:e.selectedExecutionEntryId},permissionRequest:this.permissions.current,pendingUserAction:this.userActions.current,contextState:e.contextState,...this.hostSessions===void 0?{}:{hostSessions:this.hostSessions},transcriptGeneration:this.transcriptGeneration,...this.readOnly?{readOnly:!0}:{},attached:!0}}getCommandQueryPort(){return this.commandQueryPort}getSessionUiEventPort(){return this.uiEvents}getRuntimeStatusSnapshot(e){let t=this.status;return t===void 0?{permissionMode:e,sessionId:``}:{permissionMode:t.permissionMode,sessionId:t.sessionId,effort:t.effort,modelId:t.model}}addEntry(e){this.manager.addEntry(e)}async handleInput(e){if(!e.startsWith(`/`)){if(this.refuseReadOnly())return;this.send({type:`submit`,prompt:e});return}let{name:t,args:n}=Fl(e);if(_u.has(t)){this.end(`user`);return}let r=ru(this.clientCommands?.set,t);if(r!==void 0){await this.runClientCommand(r,n);return}if(this.refuseReadOnly())return;this.commandSequence+=1;let i=`wire-tui-command-${this.commandSequence}`;await new Promise(e=>{this.pendingCommands.set(i,e),this.send({type:`command`,name:t,args:n,requestId:i})||this.settleCommand(i)})}async runClientCommand(e,t){let n=this.clientCommands;if(n!==void 0)try{let{result:r,uiIntents:i}=await iu(e,t,n.host,n.set);for(let e of i)this.uiEvents.emitUiIntent({intent:e,requesterDriverId:T});this.notice(r.message)}catch(t){this.notice(`/${e.name} failed: ${yu(t)}`)}}abort(){this.refuseReadOnly()||(this.manager.setAborting(!0),this.userActions.cancelAll(),this.permissions.cancelAll(),this.send({type:`abort`}))}cancelQueue(){this.refuseReadOnly()||(this.send({type:`cancel-queue`}),this.userActions.cancelAll(),this.permissions.cancelAll(),this.pendingCount=0,this.manager.setPendingPrompt(null))}async stopWaitingSelfPacedLoop(){if(this.refuseReadOnly())return;this.loopStopSequence+=1;let e=`wire-tui-loop-stop-${this.loopStopSequence}`,t=await new Promise(t=>{this.pendingLoopStops.set(e,t),this.send({type:`stop-waiting-loop`,requestId:e})||this.settleLoopStop(e)}),n=t===void 0?void 0:Yl(t);n!==void 0&&this.notice(n)}selectExecutionWorkspaceEntry(e){this.manager.selectExecutionWorkspaceEntry(e)}async readExecutionWorkspaceDetail(e){this.detailSequence+=1;let t=`wire-tui-detail-${this.detailSequence}`;return new Promise((n,r)=>{this.pendingDetails.set(t,{resolve:n,reject:r}),this.send({type:`read-execution-detail`,requestId:t,entryId:e})||this.rejectDetail(t,`Could not reach the session.`)})}async sendAgentJob(e,t){if(this.refuseReadOnly())return;let n=await new Promise(n=>{let r=this.pendingTaskSends.get(e)??[];r.push(n),this.pendingTaskSends.set(e,r),this.send({type:`send-background-task`,taskId:e,input:{prompt:t}})||this.settleTaskSend(e)});n!==void 0&&this.notice(`Could not send to background task ${e}: ${n}`)}resolveUserAction(e,t){this.userActions.resolveCurrent(e,t)}async requestSessionSwitch(e){if(this.refuseReadOnly()||e===this.status?.sessionId)return;this.settleSessionChange(),this.sessionChangeSequence+=1;let t=`wire-tui-session-change-${this.sessionChangeSequence}`;await new Promise(n=>{this.pendingSessionChange={requestId:t,settle:n},this.send({type:`switch-session`,sessionId:e,requestId:t})||this.settleSessionChange()})}attach(){let{connection:e}=this.options;this.options.driverId!==void 0&&(this.own={driverId:this.options.driverId,since:Date.now()}),this.unsubscribers.push(e.subscribe(e=>this.onFrame(e)),e.onClose(()=>this.end(`closed`))),this.attention?.wire(),this.requestSnapshot()}onFrame(e){if(!this.detached)try{this.project(e)}catch(t){this.notice(`Could not show the session's ${e.type} update: ${yu(t)}`)}}project(e){let t=this.manager;switch(e.type){case`user_message`:{let t=ou(e.driverId,this.options.driverId)??null;this.hostHistory.echo(Bl(e.content,{getActiveDriverId:()=>t}),e.content);return}case`text_delta`:t.onTextDelta(e.delta);return;case`tool_start`:t.onToolStart(e.state);return;case`tool_end`:t.onToolEnd(e.state);return;case`thinking`:t.onThinking(e.isThinking),this.send({type:`get-pending`});return;case`executing`:e.executing!==t.isThinking&&t.onThinking(e.executing);return;case`complete`:t.onComplete(e.result),this.attention?.onComplete(),this.hostHistory.readTail();return;case`interrupted`:t.onInterrupted(),this.hostHistory.readTail();return;case`error`:t.onError(Error(e.message)),this.attention?.onError(),this.hostHistory.readTail();return;case`history`:this.hostHistory.onPage(e);return;case`history_changed`:this.hostHistory.reload();return;case`history_cleared`:t.clearHistory(),this.hostHistory.reset(),this.hostHistory.reload();return;case`context`:t.onContextUpdate(e.state);return;case`turn_source`:this.attention?.onTurnSource(e.source);return;case`pending`:this.pendingCount=e.pendingCount??(e.pending===null?0:1),t.setPendingPrompt(e.pending);return;case`execution_workspace_event`:t.syncExecutionWorkspaceSnapshot(e.snapshot),this.attention?.onWorkspaceSnapshot(e.snapshot);return;case`plan_event`:t.addSessionEventNotice({event:`plan_event`,payload:e.event});return;case`context_file_refreshed`:t.addSessionEventNotice({event:`context_file_refreshed`,payload:e.event});return;case`branch_event`:t.addSessionEventNotice({event:`branch_event`,payload:e.event});return;default:this.projectSessionFrame(e)}}projectSessionFrame(e){switch(e.type){case`permission_request`:this.askPermission(e.event);return;case`ask_request`:this.askUser(e.event);return;case`prompt_resolved`:this.dismissPrompt(e.event.id);return;case`ui_intent`:this.showUiIntent(e.event);return;case`session_renamed`:this.rename(e.event.name);return;case`session_status`:this.applyStatus(e.status);return;case`commands`:this.commandCatalog=du(e.commands,e.skills),this.notify();return;case`command_result`:this.showCommandResult(e);return;case`sessions`:if(e.requestId!==this.sessionListRequestId)return;this.hostSessions=e.listing.sessions,this.notify(),this.openPendingPicker();return;case`sessions_error`:if(e.requestId!==this.sessionListRequestId)return;this.pendingPicker!==void 0&&(this.pendingPicker=void 0,this.notice(e.message));return;case`session_switched`:this.settleSessionChange(),this.followSessionSwitch(e.event.sessionId);return;case`session_change_failed`:(e.requestId===void 0||e.requestId===this.pendingSessionChange?.requestId)&&this.settleSessionChange(),this.notice(e.message);return;case`protocol_error`:e.requestId===void 0?this.settleSessionChange():this.settleCommand(e.requestId),this.notice(e.message);return;case`resume_gap`:this.hostHistory.restart(),this.requestState();return;default:this.projectReply(e)}}projectReply(e){switch(e.type){case`execution_detail`:{let t=this.pendingDetails.get(e.requestId);this.pendingDetails.delete(e.requestId),t?.resolve(e.page);return}case`execution_detail_error`:this.rejectDetail(e.requestId,e.message);return;case`waiting_loop_stop`:this.settleLoopStop(e.requestId,e.outcome);return;case`background_task_control_result`:if(e.action!==`send`)return;this.settleTaskSend(e.taskId,e.success?void 0:e.message??`refused`);return;default:return}}showsPrompt(e){return this.shownPromptIds.has(e)?!0:(this.shownPromptIds.add(e),!1)}askPermission(e){if(this.showsPrompt(e.id))return;this.attention?.onNeedsInput();let t=e.requesterDriverId?.startsWith(`peer:`)?n(e.requesterDriverId):void 0,r=this.promptGeneration;this.permissions.enqueue(e.toolName,e.toolArgs,e.id,e.canPersistProjectPermission,t,e.requester).then(t=>this.answer(r,e.id,{type:`permission-response`,id:e.id,result:t}))}askUser(e){if(this.showsPrompt(e.id))return;this.attention?.onNeedsInput();let t=this.promptGeneration;this.userActions.enqueue(e.request,e.id).then(n=>this.answer(t,e.id,{type:`ask-response`,id:e.id,response:n}))}answer(e,t,n){e===this.promptGeneration&&(this.shownPromptIds.delete(t),!this.settledPromptIds.delete(t)&&this.send(n))}dismissPrompt(e){this.settledPromptIds.add(e);let t=this.userActions.dismissById(e),n=this.permissions.dismissById(e);!t&&!n&&this.settledPromptIds.delete(e)}showUiIntent(e){if(e.requesterDriverId===void 0){this.uiEvents.emitUiIntent(e);return}if(vu.has(e.intent.type)){this.notice(`That screen is not available while attached to a daemon.`);return}let t={...e,requesterDriverId:T};if(e.intent.type===`show-session-picker`){this.pendingPicker=t,this.requestSessionList()||(this.pendingPicker=void 0);return}this.uiEvents.emitUiIntent(t)}openPendingPicker(){let e=this.pendingPicker;e!==void 0&&(this.pendingPicker=void 0,this.uiEvents.emitUiIntent(e))}rename(e){this.sessionName=e,this.uiEvents.emitSessionRenamed({name:e}),this.notify()}applyStatus(e){this.status=e,this.manager.onContextUpdate(e.context);let t=e.sessionName??(e.sessionId===``?void 0:is(e.sessionId));t!==void 0&&t!==this.sessionName&&this.rename(t)}showCommandResult(e){for(let e of gu)this.send({type:e});e.data?.sessionExecution===!0?this.send({type:`get-pending`}):this.notice(e.message),e.requestId!==void 0&&this.settleCommand(e.requestId)}settleCommand(e){let t=this.pendingCommands.get(e);this.pendingCommands.delete(e),t?.()}rejectDetail(e,t){let n=this.pendingDetails.get(e);this.pendingDetails.delete(e),n?.reject(Error(t))}settleLoopStop(e,t){let n=this.pendingLoopStops.get(e);this.pendingLoopStops.delete(e),n?.(t)}settleTaskSend(e,t){let n=this.pendingTaskSends.get(e),r=n?.shift();n!==void 0&&n.length===0&&this.pendingTaskSends.delete(e),r?.(t)}refuseReadOnly(){return this.readOnly&&this.notice(`Read only: this terminal observes the session and cannot change it. /exit detaches.`),this.readOnly}settleSessionChange(){let e=this.pendingSessionChange;this.pendingSessionChange=void 0,e?.settle()}followSessionSwitch(e){this.promptGeneration+=1,this.userActions.cancelAll(),this.permissions.cancelAll(),this.shownPromptIds.clear(),this.settledPromptIds.clear(),this.status=void 0,this.pendingCount=0,this.hostHistory.reset(),this.manager.dispose(),this.manager=this.createManager(),this.transcriptGeneration+=1,this.notice(`Switched to session ${e}.`),this.rename(is(e)),this.requestSnapshot()}requestSnapshot(){this.hostHistory.reload(),this.requestState()}requestState(){for(let e of this.readOnly?mu:hu)this.send({type:e});this.requestSessionList()}requestSessionList(){this.sessionListSequence+=1;let e=`wire-tui-sessions-${this.sessionListSequence}`;return this.sessionListRequestId=e,this.send({type:`list-sessions`,requestId:e})}send(e){if(this.detached||this.readOnly&&!Ze(e.type))return!1;try{return this.options.connection.send(e),!0}catch(e){return this.notice(`Could not reach the session: ${yu(e)}`),!1}}end(e){this.ended||(this.ended=!0,this.detach(),this.notice(e===`closed`?`The connection to the session closed.`:`Detached. The session keeps running.`),this.options.onEnd?.(e))}detach(){if(this.detached)return;this.detached=!0,this.pendingPicker=void 0;for(let e of this.unsubscribers.splice(0))e();this.userActions.cancelAll(),this.permissions.cancelAll();let e=[...this.pendingCommands.values()];this.pendingCommands.clear();for(let t of e)t();this.settleSessionChange();for(let e of[...this.pendingDetails.keys()])this.rejectDetail(e,`Detached from the session.`);for(let e of[...this.pendingLoopStops.keys()])this.settleLoopStop(e);let t=[...this.pendingTaskSends.values()].flat();this.pendingTaskSends.clear();for(let e of t)e()}createManager(){let e=new Jl;return e.onChange=()=>this.notify(),e}notice(e){this.manager.addEntry(a(i(e)))}notify(){this.onChange?.()}};function Su(e,t){return{cwd:e.cwd,...e.livePromptTrace?{livePromptTrace:e.livePromptTrace}:{},provider:e.provider,...e.providerErrorGuidance===void 0?{}:{providerErrorGuidance:e.providerErrorGuidance},...e.promptFileReferenceTag===void 0?{}:{promptFileReferenceTag:e.promptFileReferenceTag},...e.modelCommandToolPrefix===void 0?{}:{modelCommandToolPrefix:e.modelCommandToolPrefix},...e.subagentHookEnvironmentNames===void 0?{}:{subagentHookEnvironmentNames:e.subagentHookEnvironmentNames},...e.observerFailureWarningCode===void 0?{}:{observerFailureWarningCode:e.observerFailureWarningCode},...e.commandHookShell===void 0?{}:{commandHookShell:e.commandHookShell},...e.bare===!0?{bare:!0}:{},...e.skipConfiguredHooks===!0?{skipConfiguredHooks:!0}:{},...e.projectAccess===void 0?{}:{projectAccess:e.projectAccess},...e.projectSettingsPaths===void 0?{}:{projectSettingsPaths:e.projectSettingsPaths},...e.baselinePermissionAllow===void 0?{}:{baselinePermissionAllow:e.baselinePermissionAllow},...e.taskContext===void 0?{}:{taskContext:e.taskContext},...e.contributionSources===void 0?{}:{contributionSources:e.contributionSources},...e.skillRoots===void 0?{}:{skillRoots:e.skillRoots},...e.userSettingsSources===void 0?{}:{userSettingsSources:e.userSettingsSources},...e.environment===void 0?{}:{environment:e.environment},...e.resolveProviderCredential===void 0?{}:{resolveProviderCredential:e.resolveProviderCredential},...e.orgPolicy===void 0?{}:{orgPolicy:e.orgPolicy},...e.externalEventVerifierFactory===void 0?{}:{externalEventVerifierFactory:e.externalEventVerifierFactory},...e.externalEventGrantHistory===void 0?{}:{externalEventGrantHistory:e.externalEventGrantHistory},...e.providerDefinitions?{providerDefinitions:e.providerDefinitions}:{},...e.modelId===void 0?{}:{model:e.modelId},...e.effort===void 0?{}:{effort:e.effort},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt},...e.appendSystemPrompt===void 0?{}:{appendSystemPrompt:e.appendSystemPrompt},...e.responseFormat===void 0?{}:{responseFormat:e.responseFormat},...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},permissionMode:e.permissionMode,maxTurns:e.maxTurns,allowedTools:e.allowedTools,deniedTools:e.deniedTools,sessionStore:e.sessionStore,disableSessionLoops:e.disableSessionLoops,resolveDefaultLoopPrompt:e.resolveDefaultLoopPrompt,resumeSessionId:t,forkSession:e.forkSession,sessionName:e.sessionName,backgroundTaskRunners:e.backgroundTaskRunners,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.agentDefinitions===void 0?{}:{agentDefinitions:e.agentDefinitions},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.pluginDirectories===void 0?{}:{pluginDirectories:e.pluginDirectories},...e.additionalTools===void 0?{}:{additionalTools:e.additionalTools},...e.defaultTools===void 0?{}:{defaultTools:e.defaultTools},...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},...e.sandboxClient===void 0?{}:{sandboxClient:e.sandboxClient},commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,remoteCommandPolicy:e.remoteCommandPolicy,transportRegistry:e.transportRegistry,bindTransports:e.bindTransports,language:e.language,reloadPluginCommandSource:e.reloadPluginCommandSource,agentName:e.agentName,activePresetId:e.activePresetId,persona:e.persona,enableParallelSubagents:e.enableParallelSubagents,selfVerification:e.selfVerification,...e.memoryStore?{memoryStore:e.memoryStore}:{},...e.automaticMemory?{automaticMemory:e.automaticMemory}:{},...e.recallMemory?{recallMemory:e.recallMemory}:{},...e.screenReader===void 0?{}:{screenReader:e.screenReader},promptHistory:e.promptHistory}}async function Cu(e,t){let n;try{await e()}catch(e){n=e instanceof Error?e:Error(String(e))}let r;try{await t()?.stop()}catch(e){r=e instanceof Error?e:Error(String(e))}if(n!==void 0&&r!==void 0)throw AggregateError([n,r],`TUI render and teardown both failed.`);if(n!==void 0)throw n;if(r!==void 0)throw r}async function wu(e){try{await e.keybindingsSource?.start(),await Du(e,t=>({createChannel:Eu(e,t)}))}finally{e.keybindingsSource?.dispose()}}async function Tu(e){let t=`user`,n=()=>void 0,r=new Promise(e=>{n=e});try{await e.keybindingsSource?.start(),await Du(e,i=>{let a;return{createChannel:()=>a??=new xu({connection:e.connection,driverId:e.driverId,sessionName:e.sessionLabel,role:e.mode??`drive`,terminalHandoff:i.terminalHandoff,attention:i.attention,...e.clientCommands===void 0?{clientCommands:void 0}:{clientCommands:e.clientCommands,cwd:e.cwd},onEnd:e=>{t=e,n()}}),requestSessionSwitch:async e=>a?.requestSessionSwitch(e),ended:r}})}finally{e.keybindingsSource?.dispose()}return t}function Eu(e,t){let n=e.workspaceMovedFrom;return r=>{let i=n;n=void 0;let a=new Zl({...Su(e,r),...e.createEditCheckpointStore===void 0?{}:{editCheckpointStore:e.createEditCheckpointStore()},...i===void 0?{}:{workspaceMovedFrom:i},terminalHandoff:t.terminalHandoff,attention:t.attention});return e.onChannelReady?.(a),a}}async function Du(e,t){let n=e.screenReader===!0;e.announce!==!1&&pl({enabled:n,channel:e.screenReaderChannel,hint:e.screenReaderHint});let r=gl({enabled:n,overrides:e.screenReaderPacing}),i=n&&r.preparkMs>0?Sl({stdout:process.stdout,preparkMs:r.preparkMs}):void 0;ut()||(D.level=0);let a=new Tl,o=pt({override:e.focusReporting}),s=wl({supported:()=>o}),c=new ll({focusReporting:o,now:Date.now});a.setTerminalModeHooks({preSuspend:async()=>{s.disable(),await i?.drain()},postResume:()=>s.enable()});let l=t({terminalHandoff:a,attention:c}),u,d=e=>(u=l.createChannel(e),u);await vl(r.startupQuietMs,process.stdin);let f=new dl(process.stdin,{negotiated:()=>s.negotiated,onFocusIn:()=>c.focusIn(),onFocusOut:()=>c.focusOut(),onKeystroke:()=>c.keystroke()});process.stdin.resume(),s.enable(),c.start();let p=i===void 0?void 0:Cl(i),m=V(Ja,{name:e.productDisplayName,modelCommandToolPrefix:e.modelCommandToolPrefix,children:V(vr,{source:e.keybindingsSource,children:V(lt,{enabled:n,children:V(ci,{overrides:e.terminalCapabilities,children:V(cl,{cwd:e.cwd,createChannel:d,...l.requestSessionSwitch===void 0?{}:{requestSessionSwitch:l.requestSessionSwitch},providerOverride:e.providerOverride,providerType:e.providerType,modelId:e.modelId,permissionMode:e.permissionMode,version:e.version,sessionStore:e.sessionStore,resumeSessionId:e.resumeSessionId,showSessionPickerOnStart:e.showSessionPickerOnStart,initialInput:e.initialInput,initialInputOrigin:e.initialInputOrigin,startupUpdateNotice:e.startupUpdateNotice,transportRegistry:e.transportRegistry,pluginAdapter:e.commandHostAdapters?.plugin,cliAdapter:e.cliAdapter,promptHistorySource:e.promptHistorySource,promptHistoryProject:e.promptHistoryProject,themeRegistry:e.themeRegistry,reducedMotion:e.reducedMotion,reducedMotionOverride:e.reducedMotionOverride})})})})}),h=Ce(p===void 0?m:V(ai,{port:p,children:m}),{exitOnCtrlC:!1,isScreenReaderEnabled:n,stdin:f.asInkStdin(),...i===void 0?{}:{stdout:i.asInkStdout()}});a.setInkInstance(h),l.ended?.then(()=>h.unmount());try{await Cu(()=>h.waitUntilExit(),()=>u)}finally{await i?.flush(),a.setTerminalModeHooks(void 0),s.disable(),c.dispose(),f.detach(),process.stdin.pause()}}const Ou={drive:`drive (send prompts, answer its questions)`,observe:`observe (read only)`},ku=[`needs-input`,`working`,`idle`,`unknown`,`unverified`,`dead`];function Au(e,t,n){if(e.length<=t)return e;let r=Math.max(1,t-1),i=n===void 0?`check workspace trust in the terminal`:`see ${n}`;return[...e.slice(0,r),`… ${e.length-r} more — ${i}`]}function $(e){return e?.liveness===`alive`&&e.control===`available`&&e.generation!==void 0}function ju(e){return e.liveness===`dead`?`dead`:$(e)?e.activity:`unverified`}function Mu(e){return[...e].sort((e,t)=>ku.indexOf(ju(e))-ku.indexOf(ju(t))||e.id.localeCompare(t.id))}function Nu(e){return[...e].sort((e,t)=>(e.cwd===void 0)-+(t.cwd===void 0)||(e.cwd??``).localeCompare(t.cwd??``)||ku.indexOf(ju(e))-ku.indexOf(ju(t))||e.id.localeCompare(t.id))}function Pu(e,t,n){if(e===`/`)return e;let r=0;for(let n of t){if(n===e)continue;let t=0;for(;t<e.length&&t<n.length&&e[e.length-t-1]===n[n.length-t-1];)t++;r=Math.max(r,t)}let i=e.split(/[\\/]/u).filter(Boolean).at(-1)?.length??e.length,a=Math.min(e.length,Math.max(i,r+3)),o=e.length-a,s=Math.max(e.lastIndexOf(`/`,o-1),e.lastIndexOf(`\\`,o-1)),c=e.slice(s+1);return je(Iu(c))<=n?c:e.slice(o)}function Fu(e){return Array.from(e,e=>/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(e)?`\\u{${e.codePointAt(0).toString(16)}}`:e)}function Iu(e){return Fu(e).join(``)}function Lu(e,t){let n=Fu(e);if(je(n.join(``))<=t)return n.join(``);let r=Math.ceil((t-1)/2),i=t-r-1,a=``;for(let e of n){if(je(a)+je(e)>r)break;a+=e}let o=``;for(let e of[...n].reverse()){if(je(o)+je(e)>i)break;o=e+o}return`${a}…${o}`}function Ru(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r!==void 0&&e.id===r.id&&e.liveness===r.liveness&&e.control===r.control&&e.activity===r.activity&&e.problem===r.problem&&e.nextLoopAt===r.nextLoopAt&&e.name===r.name&&e.cwd===r.cwd&&e.pr?.url===r.pr?.url&&e.generation===r.generation})}function zu(e,t){let n=Date.parse(e)-t;return Number.isFinite(n)?n<=0?`loop eligible now`:n<6e4?`loop eligible in <1m`:`loop eligible in ${Math.ceil(n/6e4)}m`:``}function Bu({loadRows:e,onStop:t,onStart:n,startTrustQuestion:r,trustStatusCommand:i,onOpenPr:a,onAttach:o,filteredByCwd:s=!1,filteredByName:c=!1,filteredByPr:l=!1,stateFilter:u,refreshMs:d=2e3,initialSelectedId:f,initialGroupByDirectory:p=!1}){let{exit:m}=we(),{stdout:h}=Oe(),g=Math.max(12,h.columns??80),_=K(),[v,ee]=z([]),[y,te]=z(Date.now),[b,ne]=z(`loading`),[re,ie]=z(f),[ae,oe]=z(!1),[se,ce]=z(p),[x,le]=z(),S=x?.id,[ue,de]=z(`idle`),[C,w]=z(`idle`),[fe,T]=z(),pe=R(!1),[me,he]=z(`idle`),[ge,_e]=z(),[E,ve]=z(),ye=R(!1),[D,be]=z(`idle`),xe=R(!1),O=R(!0),Se=e=>{n!==void 0&&(ye.current=!0,he(`starting`),Promise.resolve().then(()=>n(e)).then(e=>{O.current&&(_e(e),he(`started`))}).catch(()=>{O.current&&he(`failed`)}).finally(()=>{ye.current=!1}))},A=L(()=>{let e=v.filter(e=>u===void 0||ju(e)===u);return se?Nu(e):Mu(e)},[v,u,se]),Ce=L(()=>{let e=[],t=[...new Set(A.map(e=>e.cwd).filter(e=>e!==void 0))],n,r=0;return A.forEach((i,a)=>{let o=se?i.cwd??`unverified`:ju(i);if(o!==n){let n=se?i.cwd===void 0?`Directory: unverified`:(()=>{let e=`Dir ${++r}: `,n=Math.max(4,g-e.length),a=Lu(Pu(i.cwd,t,n),n),o=`${e}${a} — ${Iu(i.cwd)}`;return _||je(o)<=g?o:`${e}${a}`})():`${o}:`;e.push({kind:`group`,label:n})}e.push({kind:`row`,row:i,index:a}),n=o}),e},[A,se,g,_]);I(()=>{let t=new AbortController,n=!0,r,i=async()=>{try{let r=Mu(await e(t.signal));if(!n||t.signal.aborted)return;let i=Date.now();ee(e=>Ru(e,r)?e:r),te(e=>r.some(t=>t.nextLoopAt!==void 0&&zu(t.nextLoopAt,e)!==zu(t.nextLoopAt,i))?i:e),ne(`ready`)}catch{n&&!t.signal.aborted&&ne(`unavailable`)}finally{n&&!t.signal.aborted&&(r=setTimeout(()=>{i()},d))}};return i(),()=>{n=!1,r!==void 0&&clearTimeout(r),t.abort()}},[e,d]),I(()=>(O.current=!0,()=>{O.current=!1}),[]);let j=re!==void 0&&A.some(e=>e.id===re)?re:A[0]?.id;I(()=>{ie(e=>A.length===0||e!==void 0&&A.some(t=>t.id===e)?e:A[0]?.id)},[A]),Ee((e,i)=>{if(!pe.current&&!(xe.current&&e!==`q`&&!(!_&&i.escape)&&!(i.ctrl&&e===`c`))&&!(ye.current&&e!==`q`&&!(!_&&i.escape)&&!(i.ctrl&&e===`c`))){if(E!==void 0){e===`y`||e===`r`?(ve(void 0),Se(e===`y`?`trust`:`restricted`)):(e===`n`||i.escape)&&ve(void 0);return}if(S!==void 0){if(e===`n`||i.escape){le(void 0);return}if(e===`y`&&x?.action===`attach`){let e=x,t=A.find(t=>t.id===e.id);if(le(void 0),b!==`ready`||!$(t)||t.generation!==e.generation||e.mode===void 0||o===void 0){de(`unavailable`);return}o({id:e.id,generation:e.generation,mode:e.mode,groupByDirectory:se}),m();return}if(e===`y`){let e=x,n=A.find(t=>t.id===e?.id);if(le(void 0),b!==`ready`||e===void 0||!$(n)||n.generation!==e.generation||t===void 0){w(`unavailable`);return}pe.current=!0,w(`stopping`),t(e.id,e.generation).then(()=>{O.current&&(T(e.id),w(`stopped`))}).catch(()=>{O.current&&w(`failed`)}).finally(()=>{pe.current=!1})}return}if(e===`q`||!_&&i.escape||i.ctrl&&e===`c`){m();return}if(e===`?`){oe(e=>!e);return}if(e===`g`){Te.clear(),ce(e=>!e);return}if(e===`n`&&n!==void 0){if(r===void 0){Se();return}ye.current=!0,r().then(e=>{ye.current=!1,O.current&&(e===void 0?Se():ve(e))}).catch(()=>{ye.current=!1,O.current&&he(`failed`)});return}if((e===`a`||e===`p`)&&o!==void 0){let t=A.find(e=>e.id===j);b!==`ready`||!$(t)?de(`unavailable`):(de(`idle`),w(`idle`),le({id:t.id,generation:t.generation,action:`attach`,mode:e===`a`?`drive`:`observe`}));return}if(e===`o`&&a!==void 0){let e=A.find(e=>e.id===j);if(b!==`ready`||!$(e)||!e.pr){be(`unavailable`);return}xe.current=!0,be(`opening`),a(e.id,e.pr.url,e.generation).then(()=>{O.current&&be(`opened`)}).catch(()=>{O.current&&be(`failed`)}).finally(()=>{xe.current=!1});return}if(e===`s`&&t!==void 0){let e=A.find(e=>e.id===j);b!==`ready`||!$(e)?w(`unavailable`):(w(`idle`),de(`idle`),le({id:e.id,generation:e.generation,action:`stop`}));return}if(!(_||A.length===0)&&(i.upArrow||i.downArrow)){let e=Math.max(0,A.findIndex(e=>e.id===j)),t=Math.max(0,Math.min(A.length-1,e+(i.downArrow?1:-1)));ie(A[t]?.id)}}});let Te=Gn({enabled:_&&S===void 0&&E===void 0&&C!==`stopping`,itemCount:A.length,cancellable:!0,repeatable:!0,onSelect:e=>{ie(A[e]?.id),w(`idle`)},onCancel:()=>{pe.current||m()}}),De=A.find(e=>e.id===j),ke=b===`ready`&&$(De)?De.name:void 0,M=b===`ready`&&$(De)&&De.activity===`idle`&&De.nextLoopAt?zu(De.nextLoopAt,y):``,N=b===`ready`&&$(De)?De.pr:void 0,P=Math.max(8,h.rows??24),F=[`Keys:`,_?`Number+Enter Select`:`↑/↓ Select`,`s Request stop`,`g Group state/dir`,...n===void 0?[]:[`n New session`],...o===void 0?[]:[`a Attach (drive)`,`p Peek (read only)`],...a===void 0?[]:[`o Open linked PR`],`y Confirm`,`n/Esc Cancel`,`q/Esc/Ctrl+C Close`,`? Toggle help`,`Activity ≠ liveness`,`Idle ≠ attach-ready`,`Close keeps sessions`],Ae=ae&&S===void 0&&C!==`stopping`,Me=2+(u===void 0?0:1)+ +(b===`loading`||b===`unavailable`||b===`ready`&&A.length===0)+(j===void 0?0:1)+(ke===void 0?0:1)+(N===void 0?0:2)+ +!!M+(D===`idle`?0:1)+(me===`idle`?0:1)+(E===void 0?0:1)+(S===void 0?C===`idle`?0:1:_?1:2)+ +(S===void 0&&ue!==`idle`)+1+(Ae?F.length:0)+2,Ne=Math.max(1,P-Me),Pe=Math.max(0,Ce.findIndex(e=>e.kind===`row`&&e.row.id===j)),Fe=Math.min(Math.max(0,Pe-Math.floor(Ne/2)),Math.max(0,Ce.length-Ne)),Ie=_?Ce:Ce.slice(Fe,Fe+Ne),Le=E===void 0?[]:Au([`Not trusted: ${E.folder}`,`Trusting it loads the project's own settings, hooks, plugins, skills and MCP servers:`,...E.loads],_?1/0:Ne,i),U=_?{}:{wrap:`truncate-end`},Re=o!==void 0&&b===`ready`&&$(De),ze=C===`stopping`?`Stop in progress; wait for result.`:E===void 0?S===void 0?_?`Type a number and Enter to select; s Stop;${Re?` a Attach; p Peek;`:``}${n?` n New;`:``}${a?` o Open PR;`:``} g Group; Escape to close; ? Help.`:`↑↓ Navigate s Stop${Re?` a Attach p Peek`:``}${n?` n New`:``}${a?` o Open PR`:``} g Group ? Help q/Esc Close`:`Confirm ${x?.action===`attach`?`attach`:`stop`} or cancel before closing.`:`Answer the trust question or cancel before closing.`,Be=e=>x?.action===`attach`&&x.mode!==void 0?`${x.mode===`drive`?`Attach to`:`Peek at`} ${e} to ${Ou[x.mode]}?`:`Stop ${e}?`;return H(k,{flexDirection:`column`,..._?{}:{height:P},children:[H(G,{...U,children:[s?`Background sessions in selected directory`:`Background sessions across projects`,c?` · name filter active`:``,l?` · PR filter active`:``]}),H(G,{...U,children:[A.length,` supervised session(s). Foreground peers and saved records are separate.`]}),u!==void 0&&H(G,{...U,children:[`State: `,u]}),b===`loading`&&V(G,{...U,children:`Loading supervised sessions...`}),b===`unavailable`&&V(G,{...U,children:`Supervised session discovery unavailable; last verified rows remain below.`}),b===`ready`&&A.length===0&&V(G,{...U,children:`No supervised sessions.`}),Le.map((e,t)=>V(G,{...U,children:e},`trust-${t}`)),E===void 0&&Fe>0&&!_&&H(G,{children:[Fe,` more above`]}),(E===void 0?Ie:[]).map(e=>e.kind===`group`?V(G,{...U,children:e.label},`group-${e.label}`):H(G,{..._?{}:{wrap:`truncate-end`},children:[_?xr(e.index):e.row.id===j?`> `:` `,e.row.name&&$(e.row)?_?`${e.row.name} (${e.row.id})`:`${Array.from(e.row.name).slice(0,24).join(``)}${Array.from(e.row.name).length>24?`…`:``} [${e.row.id.slice(-8)}]`:e.row.id,` `,`activity `,e.row.activity,` liveness `,e.row.liveness,` control `,e.row.control,b===`ready`&&$(e.row)&&e.row.activity===`idle`&&e.row.nextLoopAt?` ${zu(e.row.nextLoopAt,y)}`:``,e.row.problem?` ${e.row.problem}`:``,b===`ready`&&$(e.row)&&e.row.pr?` ${e.row.pr.host} ${e.row.pr.kind===`pull`?`#`:`!`}${e.row.pr.number}`:``]},`row-${e.row.id}`)),E===void 0&&!_&&Fe+Ie.length<Ce.length&&H(G,{children:[Ce.length-Fe-Ie.length,` more below`]}),j!==void 0&&H(G,{...U,children:[`Selected `,j]}),ke!==void 0&&H(G,{...U,children:[`Name: `,ke]}),N!==void 0&&H(G,{...U,children:[`PR: `,N.host,` `,N.kind===`pull`?`#`:`!`,N.number]}),N!==void 0&&H(G,{...U,children:[`URL: `,N.url]}),M&&V(G,{...U,children:M}),D===`opening`&&V(G,{...U,children:`Opening linked PR...`}),D===`opened`&&V(G,{...U,children:`Opened linked PR.`}),D===`failed`&&V(G,{...U,children:`PR link changed or could not be opened.`}),D===`unavailable`&&V(G,{...U,children:`No verified PR link is available.`}),me===`starting`&&V(G,{...U,children:`Starting a background session...`}),me===`started`&&H(G,{...U,children:[`Started `,ge,c||u!==void 0?` (may be hidden by filter)`:``]}),me===`failed`&&V(G,{...U,children:`Start failed; check workspace trust or run session start --background for details.`}),E!==void 0&&V(G,{...U,children:`y Trust and start / r Start Restricted / n Cancel`}),S!==void 0&&(_?H(G,{children:[Be(S),` y Yes / n No`]}):H(B,{children:[V(G,{...U,children:Be(`…${S.slice(-8)}`)}),V(G,{...U,children:`y Yes / n No`})]})),S===void 0&&C===`unavailable`&&V(G,{...U,children:`This session cannot be stopped from the view.`}),S===void 0&&ue===`unavailable`&&V(G,{...U,children:`This session cannot be attached to from the view.`}),C===`stopping`&&V(G,{...U,children:`Stopping selected session; wait for confirmation.`}),C===`stopped`&&H(G,{...U,children:[`Stopped `,fe]}),C===`failed`&&V(G,{...U,children:`Stop failed; session remains listed until verified otherwise.`}),_&&A.length>0&&S===void 0&&C!==`stopping`&&H(G,{children:[br(A.length,!0),Te.buffer?` ${Te.buffer}`:``]}),_&&Te.invalid&&V(G,{children:`Selection out of range.`}),V(G,{...U,children:ze}),Ae&&F.map(e=>V(G,{...U,children:e},e))]})}async function Vu(e){e.announce!==!1&&pl({enabled:e.screenReader,channel:e.screenReaderChannel,hint:e.screenReaderHint});let t;process.stdin.resume();let n=Ce(V(lt,{enabled:e.screenReader,children:V(Bu,{loadRows:e.loadRows,onStop:e.onStop,onStart:e.onStart,startTrustQuestion:e.startTrustQuestion,onOpenPr:e.onOpenPr,onAttach:e=>{t=e},filteredByCwd:e.filteredByCwd,filteredByName:e.filteredByName,filteredByPr:e.filteredByPr,stateFilter:e.stateFilter,refreshMs:e.refreshMs,...e.initialSelectedId===void 0?{}:{initialSelectedId:e.initialSelectedId},...e.initialGroupByDirectory===void 0?{}:{initialGroupByDirectory:e.initialGroupByDirectory}})}),{isScreenReaderEnabled:e.screenReader,exitOnCtrlC:!1});try{await n.waitUntilExit()}finally{n.unmount()}return t===void 0?{kind:`closed`}:{kind:`attach`,...t}}function Hu({providerDefinitions:t,reloadPluginCommandSource:n,userSettingsPath:r,settingsSources:i,formatResumeCommand:a}){return{getUserSettingsPath:()=>r,readSettings:e=>d(e),reloadPluginCommandSource:e=>{n(e)},applyActiveModelChange:(e,t,n)=>(c(i,[f(`user`,r)],t,n),{applied:!0}),getGitBranch:e=>C(e),getProviderDisplayName:n=>e(t,n)?.displayName??n,...a===void 0?{}:{formatResumeCommand:a}}}function Uu(e){return{...e===void 0?{}:{$schema:e},version:1,bindings:{}}}function Wu(e,t){let n=ur(JSON.stringify(Uu(t)),e);if(!n.ok)throw Error(n.diagnostic.message);return n.snapshot}var Gu=class{filePath;#e;#t;#n=new Set;#r;#i;#a;#o;#s=!1;constructor(e){if(e.filePath.trim()===``)throw Error(`Keybindings file path must not be empty.`);if(e.schemaUrl?.trim()===``)throw Error(`Keybindings schema URL must not be empty.`);this.filePath=e.filePath,this.#e=e.schemaUrl,this.#t=e.onDiagnostic,this.#r=Wu(this.filePath,this.#e)}start(){return this.#s?Promise.reject(Error(`Keybindings source is disposed.`)):(this.#o===void 0&&(this.#o=this.#c().catch(e=>{throw this.#i?.close(),this.#i=void 0,this.#o=void 0,e})),this.#o)}async#c(){let e=he(this.filePath);if(await _e(e,{recursive:!0}),await this.#u(),this.#s)throw Error(`Keybindings source is disposed.`);this.#i=pe(e,{persistent:!1},(e,t)=>{(t===null||t.toString()===me(this.filePath))&&this.#l()})}isStarted(){return this.#i!==void 0&&!this.#s}getSnapshot(){return this.#r}subscribe(e){return this.#n.add(e),()=>this.#n.delete(e)}async ensureFile(){await _e(he(this.filePath),{recursive:!0});try{await ve(this.filePath,`${JSON.stringify(Uu(this.#e),null,2)}\n`,{encoding:`utf8`,flag:`wx`,mode:384})}catch(e){if(!qu(e))throw e}return this.filePath}dispose(){this.#s=!0,this.#a!==void 0&&clearTimeout(this.#a),this.#a=void 0,this.#i?.close(),this.#i=void 0,this.#n.clear()}#l(){this.#s||(this.#a!==void 0&&clearTimeout(this.#a),this.#a=setTimeout(()=>{this.#a=void 0,this.#u()},10))}async#u(){let e;try{e=await E(this.filePath,`utf8`)}catch(e){if(Ku(e))return;this.#d({file:this.filePath,path:`$`,message:Yu(e)});return}let t=ur(e,this.filePath);if(!t.ok){this.#d(t.diagnostic);return}this.#f(Object.freeze({...t.snapshot,generation:this.#r.generation+1}))}#d(e){this.#t?.(e),this.#f(Object.freeze({...this.#r,generation:this.#r.generation+1,diagnostic:e}))}#f(e){if(!this.#s){this.#r=e;for(let t of this.#n)t(e)}}};function Ku(e){return Ju(e)&&e.code===`ENOENT`}function qu(e){return Ju(e)&&e.code===`EEXIST`}function Ju(e){return e instanceof Error&&`code`in e}function Yu(e){return e instanceof Error?e.message:String(e)}function Xu(e){return new Gu(e)}function Zu(e){if(e===`1`)return!0;if(e===`0`)return!1}function Qu(e){if(e.flag!==void 0)return{reducedMotion:e.flag,override:`flag`};let t=Zu(e.env);return t===void 0?{reducedMotion:e.settings}:{reducedMotion:t,override:`environment`}}function $u(e,t,n){let r=ce(e??{}),i=Qu({settings:r.reducedMotion,flag:t,env:n.PRODUCT_REDUCED_MOTION});return{appearance:r,reducedMotion:i.reducedMotion,...i.override===void 0?{}:{reducedMotionOverride:i.override}}}const ed=RegExp(`^[A-Za-z0-9._-]{1,24}$`,`u`);function td(e,t,n){return e.listDirectory(t,n).filter(e=>e.kind===`file`&&e.name.endsWith(`.json`)).map(r=>({fileName:r.name,text:e.readText(ge(t,r.name),n)}))}function nd(e,t){let n=`load ${t.source} themes`,r=l(t.root);for(let i of td(r,t.directory,n)){let n=i.fileName.slice(0,-5);if(!ed.test(n)){let n=Ut(i.fileName);e.skipped.push({id:`${t.idPrefix}${n}`,fileName:Wt(i.fileName),reason:`$: the file name ${n} cannot be a theme id — use at most 24 characters from letters, digits, dot, dash and underscore`});continue}let r=`${t.idPrefix}${n}`;if(e.claimed.has(r)){e.skipped.push({id:r,fileName:i.fileName,reason:`$: the id "${r}" is already taken by a theme loaded earlier`});continue}if(i.text===void 0){e.skipped.push({id:r,fileName:i.fileName,reason:`$: the file could not be read`});continue}let a=rn({id:r,fileName:i.fileName,source:t.source,text:i.text});a.ok?(e.claimed.add(r),e.themes.push(a.theme)):e.skipped.push({id:r,fileName:i.fileName,reason:a.error})}}function rd(e,t,n,r){let i=oe(e,t,r);try{return ee(i,{settingsPath:ae(t)}).map(e=>({name:e.manifest.name,pluginDir:e.pluginDir}))}catch(e){let t=Gt(i.join(`, `)),r=Gt(e instanceof Error?e.message:String(e));return n.skipped.push({id:`custom:<plugins>`,fileName:t,reason:`$: the plugin scopes could not be read — ${r}`}),[]}}function id(e){let t={themes:[],skipped:[],claimed:new Set};nd(t,{root:e.productRuntime.layout.userRoot,directory:`themes`,source:`user`,idPrefix:`custom:`});let n=e.plugins??rd(e.cwd,e.productRuntime,t,e.projectAccess);for(let e of n){if(!ed.test(e.name)){let n=Ut(e.name);t.skipped.push({id:`custom:${n}`,fileName:Wt(e.name),reason:`$: the plugin name ${n} cannot be part of a theme id — its themes are not loaded`});continue}nd(t,{root:e.pluginDir,directory:`themes`,source:`plugin`,idPrefix:`custom:${e.name}:`})}return{themes:t.themes,skipped:t.skipped}}function ad(e){let t=$u(e.settings,e.reducedMotionFlag,e.env),n={reducedMotion:t.reducedMotion,...t.reducedMotionOverride===void 0?{}:{reducedMotionOverride:t.reducedMotionOverride}};if(!e.enabled)return{registry:void 0,cataloguePort:void 0,skipped:[],...n};let r=id({cwd:e.cwd,productRuntime:e.productRuntime,userHome:e.userHome,...e.projectAccess===void 0?{}:{projectAccess:e.projectAccess}}),i=Gc([...ot(),...r.themes],r.skipped);return{registry:i,cataloguePort:Jc({registry:i,readAppearance:()=>$u(d(ae(e.productRuntime)),void 0,{}).appearance,...t.reducedMotionOverride===void 0?{}:{reducedMotionPin:{tier:t.reducedMotionOverride,reducedMotion:t.reducedMotion}}}),skipped:r.skipped,...n}}async function od(e={}){let t=x(e);ne(t);let n={...e,productRuntime:t};return fe(ie(process.argv))?(le(t.environment),re(ue(t)),new Promise(()=>void 0)):S(n,p,{renderApp:wu,renderSupervisedSessionView:Vu,renderAttachedApp:Tu,createDefaultTuiCliAdapter:Hu,createNodeKeybindingsSource:Xu,createThemeSurface:ad,installTuiProcessGuards:Ve,setLiveChannel:ze})}async function sd(e={}){try{let t=x(e);de(t.config.identity.cliName),Ge(t.config.identity.cliName),await od({...e,productRuntime:t})}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),fe(ie(process.argv))?process.exitCode=1:process.exit(1)}}sd();export{};
|
|
36
|
+
`)??[];return i&&i.length>0?H(k,{flexDirection:`column`,marginBottom:1,children:[V(k,{children:V(fo,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),V(G,{children:` `}),i.map((e,r)=>{let i=to(e,ya(e)?.status===`error`);return H(k,{flexDirection:`column`,children:[H(G,{color:ln(t,i),children:[` `,no(e,i,n)]}),V(ro,{tool:e}),e.diffLines&&e.diffLines.length>0&&V(co,{file:e.diffFile,lines:e.diffLines})]},r)})]}):H(k,{flexDirection:`column`,marginBottom:1,children:[V(k,{children:V(fo,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),V(G,{children:` `}),a.map((e,n)=>H(G,{color:t.text.success,children:[` `,W(e)]},n))]})}function _o({entry:e}){let t=q(),n=e.data,r=typeof n?.message==`string`?n.message:typeof n?.content==`string`?n.content:void 0;if(r===void 0)return V(B,{});let i=W(r);return H(k,{flexDirection:`column`,marginBottom:1,children:[V(k,{children:V(fo,{kind:`warning`,text:`System: `,color:t.text.warning})}),V(G,{children:` `}),V(k,{marginLeft:2,children:V(G,{wrap:`wrap`,children:i})})]})}function vo({entry:e}){if(e.category===`chat`){let t=e.data;return V(ho,{message:t})}return e.type===`tool-summary`?V(go,{entry:e}):e.type===`usage-summary`?V(lo,{entry:e}):e.type===`tool-start`||e.type===`tool-end`?V(B,{}):V(_o,{entry:e})}const yo=[{keys:`↑↓`,label:`Navigate`},{keys:`Enter`,label:`Select`},{keys:`Esc`,label:`Cancel`}];function bo({items:e,renderItem:t,onSelect:n,onCancel:r,maxVisible:i=3,footerHints:a=yo,initialIndex:o=0}){let[s,c]=z(()=>{let t=o>=0&&o<e.length?o:0;return{...Pn(t),scrollOffset:Math.max(0,t-i+1)}}),l=R(s),u=P(t=>{let a=Ln(l.current,t,{itemCount:e.length,maxVisible:i});if(l.current=a.state,c(a.state),a.effect.type===`cancel`)r();else if(a.effect.type===`select`){let t=e[a.effect.index];t!==void 0&&n(t)}},[e,i,r,n]),d=K(),f=Gn({enabled:d&&e.length>0,itemCount:e.length,cancellable:!0,onSelect:t=>{let r=e[t];r!==void 0&&n(r)},onCancel:r});Q(`list-picker`,e=>e.forEach(u),{isActive:!d});let p=Z(`list-picker`,[[[`previous`,`next`],`Navigate`],[`select`,`Select`],[`cancel`,`Cancel`]]);if(e.length===0)return V(k,{});if(d){let n=br(e.length,!0);return H(k,{flexDirection:`column`,children:[e.map((e,n)=>H(k,{children:[V(G,{children:xr(n)}),t(e,!1)]},n)),H(G,{children:[n,f.buffer.length>0?` ${f.buffer}`:``]}),f.invalid&&V(G,{children:n})]})}let m=Rn(s,{itemCount:e.length,maxVisible:i});m!==s&&(l.current=m);let{selectedIndex:h,scrollOffset:g}=m,_=e.slice(g,g+i),v=g+i<e.length;return H(k,{flexDirection:`column`,children:[g>0&&H(G,{dimColor:!0,children:[` ↑ `,g,` more above`]}),_.map((e,n)=>V(k,{marginBottom:1,children:t(e,g+n===h)},g+n)),v&&H(G,{dimColor:!0,children:[` ↓ `,e.length-g-i,` more below`]}),V(Y,{hints:a===yo?p:a})]})}function xo({label:e,index:t,isCursor:n,isChecked:r,screenReader:i}){let a=q(),o=r?`[x] `:`[ ] `;return i?H(G,{children:[xr(t),o,e]}):H(G,{color:n?a.text.accent:void 0,children:[n?`> `:` `,o,e]})}function So(e){let{active:t,itemCount:n,setCursor:r}=e;Q(`multi-select`,t=>{for(let i of t)i===`previous`?r(e=>e<=0?n-1:e-1):i===`next`?r(e=>e>=n-1?0:e+1):i===`toggle`?e.onToggleAtCursor():i===`confirm`?e.onConfirm():i===`cancel`&&e.onCancel()},{isActive:t})}function Co(e){let t=Z(`multi-select`,[[[`previous`,`next`],`Navigate`],[`toggle`,`Toggle`],[`confirm`,e.canConfirm?`Confirm`:`Confirm (min ${e.minSelect})`],[`cancel`,`Cancel`]]);return e.screenReader?V(Sr,{itemCount:e.itemCount,cancellable:!0,buffer:e.numbered.buffer,invalid:e.numbered.invalid}):V(Y,{hints:t})}function wo(e){let t=q(),{title:n,description:r,options:i,cursor:a,selected:o,screenReader:s,numbered:c}=e;return H(k,{flexDirection:`column`,...s?{}:{borderStyle:`round`,borderColor:t.border.attention},paddingX:1,children:[V(G,{color:t.text.warning,bold:!0,children:n}),r!==void 0&&r.length>0&&V(G,{dimColor:!0,children:r}),i.map((e,t)=>V(xo,{label:e.label,index:t,isCursor:t===a,isChecked:o.has(e.value),screenReader:s},e.value)),V(Co,{screenReader:s,itemCount:i.length,numbered:c,canConfirm:e.canConfirm,minSelect:e.minSelect})]})}function To(e){let{options:t,minSelect:n,maxSelect:r,defaultValues:i,onConfirm:a}=e,[o,s]=z(0),[c,l]=z(()=>new Set(i??[]));return{cursor:o,setCursor:s,selected:c,toggleAt:e=>{let n=t[e];n!==void 0&&l(e=>{let t=new Set(e);return t.has(n.value)?t.delete(n.value):t.size<r&&t.add(n.value),t})},confirmIfAllowed:()=>{c.size>=n&&a([...c])}}}function Eo({title:e,description:t,options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o,onCancel:s}){let c=K(),{cursor:l,setCursor:u,selected:d,toggleAt:f,confirmIfAllowed:p}=To({options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o}),m=Gn({enabled:c,itemCount:n.length,cancellable:!0,multi:!0,onSelect:f,onConfirm:p,onCancel:s});So({active:!c,itemCount:n.length,setCursor:u,onToggleAtCursor:()=>f(l),onConfirm:p,onCancel:s});let h=d.size>=r;return V(wo,{title:e,...t===void 0?{}:{description:t},options:n,cursor:l,selected:d,screenReader:c,canConfirm:h,minSelect:r,numbered:m})}function Do(){return{value:``,resolved:!1}}function Oo(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:t.type===`cancel`?{state:{...e,resolved:!0},effect:{type:`cancel`}}:t.type===`delete`?{state:{...e,value:e.value.slice(0,-1),error:void 0},effect:{type:`none`}}:t.type===`insert`?{state:{...e,value:e.value+t.value,error:void 0},effect:{type:`none`}}:ko(e,n)}function ko(e,t){let n=e.value.trim();if(!n&&!t.allowEmpty){let r=t.validate?.(n);return{state:r?{...e,error:r}:e,effect:{type:`none`}}}let r=t.validate?.(n);return r===void 0?{state:{...e,resolved:!0},effect:{type:`submit`,value:n}}:{state:{...e,error:r},effect:{type:`none`}}}function Ao({title:e,description:t,placeholder:n,onSubmit:r,onCancel:i,validate:a,allowEmpty:o=!1,masked:s=!1}){let c=q(),[l,u]=z(()=>Do()),d=R(l),f=P(e=>{let t=Oo(d.current,e,{allowEmpty:o,validate:a});d.current=t.state,u(t.state),t.effect.type===`cancel`?i():t.effect.type===`submit`&&r(t.effect.value)},[o,a,i,r]),p=K();Q(`text-prompt`,(e,t,n,r)=>{for(let t of e)t===`submit`?f({type:`submit`}):t===`cancel`?f({type:`cancel`}):t===`delete-backward`&&f({type:`delete`});e.length===0&&!r&&t&&n.ctrl!==!0&&n.meta!==!0&&f({type:`insert`,value:t})});let m=Z(`text-prompt`,[[`submit`,`Submit`],[`cancel`,`Cancel`]]);return H(k,{flexDirection:`column`,...p?{}:{borderStyle:`round`,borderColor:c.border.attention},paddingX:1,children:[V(G,{color:c.text.warning,bold:!0,children:e}),V(jo,{description:t}),H(k,{marginTop:1,children:[V(G,{color:c.text.accent,children:`> `}),l.value?V(G,{children:s?`*`.repeat(l.value.length):l.value}):n?V(G,{dimColor:!0,children:n}):null,V(G,{color:c.text.accent,children:`█`})]}),l.error&&V(G,{color:c.text.error,children:l.error}),V(Y,{hints:m})]})}function jo({description:e}){return e===void 0||e.length===0?null:V(G,{dimColor:!0,children:e})}const Mo={value:``,label:`Type a custom answer…`};function No({request:e,onAnswer:t}){let n=q(),[r,i]=z(!1),a=e.options??[],o=a.length>0,s=e.maxSelect??1,c=()=>t({type:`cancelled`});if(!o||r)return V(Ao,{title:e.title,description:e.description,placeholder:e.placeholder,allowEmpty:e.allowEmpty,masked:e.masked,onSubmit:e=>t({type:`answer`,values:[],text:e}),onCancel:r?()=>i(!1):c},`text:${e.id}`);if(s>1)return V(Eo,{title:e.title,description:e.description,options:a,minSelect:e.minSelect??1,maxSelect:s,defaultValues:e.default?.values,onConfirm:e=>t({type:`answer`,values:e}),onCancel:c});let l=e.allowFreeText?[...a,Mo]:[...a],u=e.default?.values?.[0],d=u===void 0?0:Math.max(0,l.findIndex(e=>e.value===u));return H(k,{flexDirection:`column`,children:[V(G,{bold:!0,children:e.title}),e.description!==void 0&&e.description.length>0&&V(G,{dimColor:!0,children:e.description}),V(bo,{items:l,initialIndex:d,maxVisible:e.maxVisible,renderItem:(e,t)=>H(G,{color:t?n.text.accent:void 0,children:[t?`> `:` `,e.label]}),onSelect:e=>{e===Mo?i(!0):t({type:`answer`,values:[e.value]})},onCancel:c})]})}const Po=[`Allow [y]`,`Allow always (this session) [s]`,`Allow always (this project) [p]`,`Deny [n]`];function Fo(e,t=!0){return[Po[0],`Allow ${e} always (this session) [s]`,t?`Allow ${e} always (this project) [p]`:`Project-wide approval unavailable`,Po[3]]}function Io(e,t,n=!0){if(e.resolved)return{state:e,effect:{type:`none`}};if(typeof t!=`string`)return t.index===2&&!n?{state:e,effect:{type:`none`}}:Ro(e,t.index);let r=Ln(e,t,{itemCount:Po.length});return r.effect.type!==`select`||r.effect.index===2&&!n?{state:r.state,effect:{type:`none`}}:{state:r.state,effect:{type:`resolve`,decision:Lo(r.effect.index)}}}function Lo(e){return e===0?!0:e===1?`allow-session`:e===2&&`allow-project`}function Ro(e,t){return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`resolve`,decision:Lo(t)}}}function zo(e){let t=Object.entries(e);return t.length===0?`(no arguments)`:t.map(([e,t])=>`${e}: ${typeof t==`string`?t:JSON.stringify(t)}`).join(`, `)}function Bo({request:e,armDelayMs:t=450}){let n=q(),r=e.canPersistProjectPermission!==!1,[i,a]=M.useState(()=>Pn()),o=M.useRef(i),s=M.useRef(e);if(s.current!==e){s.current=e;let t=Pn();o.current=t,a(t)}let[c,l]=M.useState();M.useEffect(()=>{if(t<=0)return;let n=setTimeout(()=>l(e),t);return()=>clearTimeout(n)},[e,t]);let u=t<=0||c===e,d=M.useCallback(t=>{let n=Io(o.current,t,r);o.current=n.state,a(n.state),n.effect.type===`resolve`&&e.resolve(n.effect.decision)},[e,r]),f=K(),p=Fo(C(e.toolName,e.toolArgs),r),m=Gn({enabled:f&&u,itemCount:p.length,onSelect:t=>{let n=Io(o.current,{type:`shortcut`,index:t},r);o.current=n.state,a(n.state),n.effect.type===`resolve`&&e.resolve(n.effect.decision)}}),h=m.clear;M.useEffect(()=>h(),[e,h]),Q(`permission-prompt`,e=>{if(!u)return;let t={"allow-once":0,"allow-session":1,"allow-project":2,deny:3};for(let n of e)n in t?d({type:`shortcut`,index:t[n]}):(n===`previous`||n===`next`||n===`confirm`)&&d(n===`confirm`?`select`:n)},{isActive:!f});let g=Z(`permission-prompt`,[[[`previous`,`next`],`Navigate`],[`confirm`,`Confirm`]]),_=e.requester?.kind===`background-agent`?e.requester.label:void 0;return f?V(Cr,{title:Za.permissionRequired,description:`${_===void 0?``:`Background agent ${_} wants to run `}${e.toolName} — ${zo(e.toolArgs)}${e.requestedByPeer===void 0?``:` (requested by another session: ${e.requestedByPeer})`}`,options:p,buffer:m.buffer,invalid:m.invalid}):H(k,{flexDirection:`column`,borderStyle:`round`,borderColor:u?n.border.attention:n.border.muted,paddingX:1,children:[H(k,{children:[V(G,{color:n.text.warning,bold:!0,children:`[Permission Required]`}),u?null:V(G,{dimColor:!0,children:` keys answer in a moment`})]}),_===void 0?H(G,{children:[`Tool:`,` `,V(G,{color:n.text.accent,bold:!0,children:e.toolName})]}):H(G,{color:n.text.warning,children:[`Background agent `,V(G,{bold:!0,children:_}),` wants to run`,` `,V(G,{color:n.text.accent,bold:!0,children:e.toolName})]}),H(G,{dimColor:!0,children:[` `,zo(e.toolArgs)]}),e.requestedByPeer===void 0?null:H(G,{color:n.text.warning,children:[`Requested by another session: `,e.requestedByPeer]}),V(k,{marginTop:1,flexDirection:`column`,children:p.map((e,t)=>{let r=u&&t===i.selectedIndex;return V(k,{children:H(G,{color:r?n.text.accent:void 0,bold:r,dimColor:!u,children:[r?`> `:` `,e]})},e)})}),V(Y,{hints:g})]})}function Vo(){return{buffer:``,resolved:!1}}const Ho=[`y`,`yes`],Uo=[`n`,`no`];function Wo(e,t,n){if(e.resolved)return{state:e,effect:{type:`none`}};if(n.backspace===!0||n.delete===!0)return{state:{...e,buffer:e.buffer.slice(0,-1)},effect:{type:`none`}};if(n.return===!0){let t=e.buffer.trim().toLowerCase();return Ho.includes(t)?{state:{buffer:``,resolved:!0},effect:{type:`select`,index:0}}:Uo.includes(t)?{state:{buffer:``,resolved:!0},effect:{type:`select`,index:1}}:{state:{...e,buffer:``},effect:{type:`none`}}}return/^[a-zA-Z]+$/.test(t)?{state:{...e,buffer:e.buffer+t},effect:{type:`none`}}:{state:e,effect:{type:`none`}}}function Go(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:typeof t==`string`?Ln(e,t,{itemCount:n}):{state:{...e,selectedIndex:t.index,resolved:!0},effect:{type:`select`,index:t.index}}}function Ko({message:e,options:t=[`Yes`,`No`],onSelect:n}){let r=q(),[i,a]=z(()=>Pn()),o=R(i),s=P(e=>{let r=Go(o.current,e,t.length);o.current=r.state,a(r.state),r.effect.type===`select`&&n(r.effect.index)},[n,t.length]),c=K(),[l,u]=z(Vo),d=R(l);Ee((e,t)=>{let r=Wo(d.current,e,t);d.current=r.state,u(r.state),r.effect.type===`select`&&n(r.effect.index)},{isActive:c}),Q(`confirm-prompt`,e=>{for(let n of e)n===`choose-yes`&&t.length===2?s({type:`shortcut`,index:0}):n===`choose-no`&&t.length===2?s({type:`shortcut`,index:1}):(n===`previous`||n===`next`||n===`confirm`)&&s(n===`confirm`?`select`:n)},{isActive:!c});let f=Z(`confirm-prompt`,[[[`previous`,`next`],`Navigate`],[`confirm`,`Confirm`]]);return c?H(k,{flexDirection:`column`,children:[V(G,{children:e}),H(G,{children:[`Answer y or n and press Enter`,l.buffer.length>0?` ${l.buffer}`:``]})]}):H(k,{flexDirection:`column`,borderStyle:`round`,borderColor:r.border.attention,paddingX:1,children:[V(G,{color:r.text.warning,children:e}),V(k,{marginTop:1,children:t.map((e,t)=>V(k,{marginRight:2,children:H(G,{color:t===i.selectedIndex?r.text.accent:void 0,bold:t===i.selectedIndex,children:[t===i.selectedIndex?`> `:` `,e]})},e))}),V(Y,{hints:f})]})}function qo(e,t,n,r,i){let[a,o]=z([]),[s,c]=z(!1),[l,u]=z();return I(()=>{if(o([]),u(void 0),e===`marketplace-list`)c(!0),n.marketplaceList().then(e=>{let t=[{label:`Add Marketplace`,value:`__add__`}],n=e.map(e=>({label:e.name,value:e.name,hint:e.type}));o([...t,...n]),c(!1)}).catch(e=>{u(e instanceof Error?e.message:String(e)),c(!1)});else if(e===`marketplace-browse`){let e=t??``;c(!0),n.listAvailablePlugins(e).then(e=>{o(e.map(e=>({label:e.name,value:e.name,hint:e.installed?`installed`:e.description}))),c(!1)}).catch(e=>{u(e instanceof Error?e.message:String(e)),c(!1)})}else e===`installed-list`&&(c(!0),n.listInstalled().then(e=>{o(e.map(e=>({label:e.name,value:e.name,hint:e.description}))),c(!1)}).catch(e=>{u(e instanceof Error?e.message:String(e)),c(!1)}))},[i,e,t,n,r]),{items:a,loading:s,error:l}}function Jo({title:e,items:t,onSelect:n,onBack:r,loading:i,error:a}){let o=q(),[s,c]=z(()=>Pn()),l=R(s),u=!i&&!a,d=K(),f=Gn({enabled:d&&u,itemCount:t.length,cancellable:!0,onSelect:e=>{let r=t[e];r!==void 0&&n(r.value)},onCancel:r}),p=P(e=>{let i=Ln(l.current,e,{itemCount:t.length,enabled:u});if(l.current=i.state,c(i.state),i.effect.type===`cancel`)r();else if(i.effect.type===`select`){let e=t[i.effect.index];e!==void 0&&n(e.value)}},[u,t,r,n]);Q(`menu-select`,e=>e.forEach(e=>p(e===`back`?`cancel`:e)),{isActive:!d});let m=Z(`menu-select`,[[[`previous`,`next`],`Navigate`],[`select`,`Select`],[`back`,`Back`]]),h=Z(`menu-select`,[[`back`,`Back`]]),g=Rn(s,{itemCount:t.length});g!==s&&(l.current=g);let _=g.selectedIndex;return d?V(Cr,{title:e,options:i||a?[]:t.map(e=>e.label),description:i?`Loading...`:a,cancellable:!0,buffer:f.buffer,invalid:f.invalid}):H(k,{flexDirection:`column`,borderStyle:`round`,borderColor:o.border.attention,paddingX:1,children:[V(G,{color:o.text.warning,bold:!0,children:e}),i&&V(k,{marginTop:1,children:V(G,{dimColor:!0,children:`Loading...`})}),a&&V(k,{marginTop:1,children:V(G,{color:o.text.error,children:a})}),!i&&!a&&V(k,{flexDirection:`column`,marginTop:1,children:t.map((e,t)=>H(k,{children:[H(G,{color:t===_?o.text.accent:void 0,bold:t===_,children:[t===_?`> `:` `,e.label]}),e.hint&&H(G,{dimColor:!0,children:[` `,e.hint]})]},e.value))}),V(Y,{hints:i?[]:a?h:m})]})}function Yo(e,t){e===`marketplace`?t.push({screen:`marketplace-list`}):e===`installed`&&t.push({screen:`installed-list`})}function Xo(e,t){e===`__add__`?t.push({screen:`marketplace-add`}):t.push({screen:`marketplace-action`,context:{marketplace:e}})}function Zo(e,t,n,r){e===`browse`?r.push({screen:`marketplace-browse`,context:{marketplace:t}}):e===`update`?n.marketplaceUpdate(t).then(()=>{r.notify(`Updated marketplace "${t}".`),r.pop()}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)}):e===`remove`&&r.setConfirm({message:`Remove marketplace "${t}" and all its plugins?`,onConfirm:()=>{r.setConfirm(void 0),n.marketplaceRemove(t).then(()=>{r.notify(`Removed marketplace "${t}".`),r.popN(2)}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})},onCancel:()=>r.setConfirm(void 0)})}function Qo(e,t,n,r){let i=`${e}@${t}`;n.find(t=>t.value===e)?.hint===`installed`?r.push({screen:`installed-action`,context:{pluginId:i}}):r.push({screen:`marketplace-install-scope`,context:{marketplace:t,pluginId:i}})}function $o(e,t,n,r){let i=e;n.install(t,i).then(()=>{r.notify(`Installed plugin "${t}" (${i} scope).`),r.popN(2)}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})}function es(e,t,n){n.setConfirm({message:`Uninstall plugin "${e}"?`,onConfirm:()=>{n.setConfirm(void 0),t.uninstall(e).then(()=>{n.notify(`Uninstalled plugin "${e}".`),n.refresh()}).catch(e=>{n.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})},onCancel:()=>n.setConfirm(void 0)})}function ts(e,t,n,r){e===`uninstall`&&r.setConfirm({message:`Uninstall plugin "${t}"?`,onConfirm:()=>{r.setConfirm(void 0),n.uninstall(t).then(()=>{r.notify(`Uninstalled plugin "${t}".`),r.popN(2)}).catch(e=>{r.notify(`Error: ${e instanceof Error?e.message:String(e)}`)})},onCancel:()=>r.setConfirm(void 0)})}function ns({callbacks:e,onClose:t,addMessage:n}){let[r,i]=z([{screen:`main`}]),[a,o]=z(),[s,c]=z(0),l=r[r.length-1]??{screen:`main`},u=P(e=>{i(t=>[...t,e])},[]),d=P(()=>{i(e=>e.length<=1?(t(),e):e.slice(0,-1))},[t]),f=P(e=>{i(n=>{let r=n.slice(0,Math.max(1,n.length-e));return r.length===0?(t(),n):r})},[t]),p=P(e=>{n?.({role:`system`,content:e})},[n]),m=P(()=>{c(e=>e+1)},[]),h=P(e=>o(e),[o]),g={push:P(e=>u({screen:e.screen,context:e.context}),[u]),pop:d,popN:f,notify:p,setConfirm:h,refresh:m},{items:_,loading:v,error:ee}=qo(l.screen,l.context?.marketplace,e,s,r.length),y=P(t=>{let n=l.screen,r=l.context;n===`main`?Yo(t,g):n===`marketplace-list`?Xo(t,g):n===`marketplace-action`?Zo(t,r?.marketplace??``,e,g):n===`marketplace-browse`?Qo(t,r?.marketplace??``,_,g):n===`marketplace-install-scope`?$o(t,r?.pluginId??``,e,g):n===`installed-list`?es(t,e,g):n===`installed-action`&&ts(t,r?.pluginId??``,e,g)},[l,_,e,u,d,f,p,o,m]),te=P(t=>{l.screen===`marketplace-add`&&e.marketplaceAdd(t).then(e=>{p(`Added marketplace "${e}" from ${t}.`),d()}).catch(e=>{p(`Error: ${e instanceof Error?e.message:String(e)}`),d()})},[l.screen,e,p,d]);if(a)return V(Ko,{message:a.message,onSelect:e=>{e===0?a.onConfirm():a.onCancel()}});let b=l.screen;return b===`marketplace-add`?V(Ao,{title:`Add Marketplace Source`,placeholder:`owner/repo or git URL`,onSubmit:te,onCancel:d,validate:e=>e.includes(`/`)?void 0:`Must be owner/repo or a git URL`}):b===`marketplace-action`?V(Jo,{title:`Marketplace: ${l.context?.marketplace??``}`,items:[{label:`Browse plugins`,value:`browse`},{label:`Update`,value:`update`},{label:`Remove`,value:`remove`}],onSelect:y,onBack:d},r.length):b===`marketplace-install-scope`?V(Jo,{title:`Install scope for "${l.context?.pluginId??``}"`,items:[{label:`User scope`,value:`user`},{label:`Project scope`,value:`project`}],onSelect:y,onBack:d},r.length):b===`installed-action`?V(Jo,{title:`Plugin: ${l.context?.pluginId??``}`,items:[{label:`Uninstall`,value:`uninstall`}],onSelect:y,onBack:d},r.length):V(Jo,{title:{main:`Plugin Management`,"marketplace-list":`Marketplace`,"marketplace-browse":`Browse: ${l.context?.marketplace??``}`,"installed-list":`Installed Plugins`}[b]??`Plugin Management`,items:{main:[{label:`Marketplace`,value:`marketplace`},{label:`Installed Plugins`,value:`installed`}]}[b]??_,onSelect:y,onBack:d,loading:v,error:ee},`${b}-${r.length}-${s}`)}function rs({notices:e}){let t=q();return e.length===0?null:V(k,{flexDirection:`column`,paddingX:1,children:e.map(e=>V(G,{color:t.text.muted,children:e.message},e.id))})}function is(e){let t=e.startsWith(`session_`)?e.slice(8):e;return t===``?e:t.slice(0,8)}function as(e){let t=[];return e.live===!0&&t.push(`● live`),e.clients!==void 0&&e.clients>0&&t.push(`${e.clients} ${e.clients===1?`client`:`clients`}`),t.length>0?t.join(` · `):null}function os({sessions:e,onSelect:t,onCancel:n}){let r=q();return H(k,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[V(G,{bold:!0,color:r.text.accent,children:`Select a session to resume:`}),V(bo,{items:[...e],renderItem:(e,t)=>{let n=as(e),i=e.preview?e.preview.slice(0,60)+(e.preview.length>60?`...`:``):``;return H(G,{children:[t?`> `:` `,V(G,{bold:!0,children:e.name??is(e.id)}),` `,V(G,{dimColor:!0,children:new Date(e.updatedAt).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}),` `,H(G,{dimColor:!0,children:[`msgs: `,e.messageCount]}),n===null?null:H(B,{children:[` `,V(G,{color:r.text.success,children:n})]}),i?H(B,{children:[`
|
|
37
|
+
`,V(G,{dimColor:!0,children:i})]}):null]})},onSelect:e=>t(e.id),onCancel:n})]})}function ss(e){let t=cs(e),n=e.hasPendingPrompt&&t.kind!==`queued`?[`queued`]:[],r=[t.label,...n].join(` · `);return{...t,segments:n,text:r}}function cs(e){return e.activeToolCount>0?{kind:`tools`,label:`Tools (${e.activeToolCount})`,tone:`accent`}:e.isThinking?{kind:`thinking`,label:`Thinking`,tone:`warning`}:e.activeBackgroundTaskCount>0?{kind:`background`,label:`Background (${e.activeBackgroundTaskCount})`,tone:`accent`}:e.hasPendingPrompt?{kind:`queued`,label:`Queued`,tone:`warning`}:{kind:`idle`,label:`Idle`,tone:`muted`}}const ls=` | `;function us(e,t){return e>=90?t.text.error:e>=70?t.text.warning:t.text.success}function ds({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r}){let i=q(),a=ss({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r});return V(G,{color:i.text[a.tone],bold:a.kind!==`idle`,children:a.text})}function fs({percentage:e,usedTokens:n,maxTokens:r}){return H(G,{color:us(e,q()),children:[`Context: `,Math.round(e),`% (`,t(n),`/`,t(r),` tokens)`]})}function ps(){return V(G,{color:q().text.warning,bold:!0,children:`Observing — read only`})}function ms({permissionMode:e}){return H(B,{children:[V(G,{color:q().text.accent,bold:!0,children:`Mode:`}),` `,V(G,{children:e})]})}function hs(e,t){return t||e!=="default"}function gs({activePresetId:e}){return H(B,{children:[V(G,{color:q().text.accent,bold:!0,children:`Preset:`}),` `,V(G,{children:e})]})}function _s(e){return e!==void 0&&e!=="default"}function vs({modelName:e,providerDisplayName:t,effort:n}){return H(G,{dimColor:!0,children:[t===void 0?e:`${t} ${e}`,n===void 0?``:` Effort: ${n}`]})}function ys(e){let t=q(),n=e.showGitBranch&&e.gitBranch!==void 0&&e.gitBranch.length>0,r=K(),i=hs(e.permissionMode,r),a=e.activePresetId,o=_s(a);return H(G,{children:[e.readOnly&&H(B,{children:[V(ps,{}),!r&&ls]}),!r&&V(ds,{isThinking:e.isThinking,activeToolCount:e.activeToolCount,activeBackgroundTaskCount:e.activeBackgroundTaskCount,hasPendingPrompt:e.hasPendingPrompt}),i&&H(B,{children:[ls,V(ms,{permissionMode:e.permissionMode})]}),o&&H(B,{children:[ls,V(gs,{activePresetId:a})]}),e.sessionName&&H(B,{children:[ls,V(G,{color:t.text.session,children:e.sessionName})]}),n&&H(B,{children:[ls,H(G,{dimColor:!0,children:[`git: `,e.gitBranch]})]}),ls,V(vs,{modelName:e.modelName,providerDisplayName:e.providerDisplayName,effort:e.effort}),!r&&H(B,{children:[ls,V(fs,{percentage:e.contextPercentage,usedTokens:e.contextUsedTokens,maxTokens:e.contextMaxTokens})]})]})}function bs({permissionMode:e,modelName:t,providerDisplayName:n,sessionId:r,isThinking:i,activeToolCount:a=0,activeBackgroundTaskCount:o=0,hasPendingPrompt:s=!1,contextPercentage:c,contextUsedTokens:l,contextMaxTokens:u,sessionName:d,gitBranch:f,showGitBranch:p=!0,activeAgentLabel:m,activePresetId:h,effort:g,readOnly:_=!1}){let v=q();return H(k,{paddingLeft:1,paddingRight:1,justifyContent:`space-between`,children:[V(ys,{permissionMode:e,modelName:t,providerDisplayName:n,isThinking:i,activeToolCount:a,activeBackgroundTaskCount:o,hasPendingPrompt:s,contextPercentage:c,contextUsedTokens:l,contextMaxTokens:u,sessionName:d,gitBranch:f,showGitBranch:p,activePresetId:h,effort:g,readOnly:_}),m!==void 0&&H(G,{color:v.text.warning,bold:!0,children:[`[`,m,`]`]})]})}const xs=N(null),Ss=xs.Provider;function Cs(){let e=F(xs);if(!e)throw Error(`TuiCliAdapterContext not provided`);return e}function ws({cwd:e,permissionMode:t,modelId:n,providerType:r,sessionId:i,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextState:l,sessionName:u,settings:d,activeAgentLabel:f,activePresetId:p,effort:m,gitRefreshToken:h,readOnly:g=!1}){let _=Cs(),v=L(()=>_.getGitBranch(e),[_,e,h]),ee=L(()=>r===void 0?void 0:_.getProviderDisplayName(r),[_,r]);return d.enabled?V(bs,{permissionMode:t,modelName:n??``,providerDisplayName:ee,sessionId:i,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextPercentage:l.percentage,contextUsedTokens:l.usedTokens,contextMaxTokens:l.maxTokens,sessionName:u,gitBranch:v,showGitBranch:d.gitBranch,activeAgentLabel:f,activePresetId:p,effort:m,readOnly:g}):g?V(ps,{}):null}function Ts(e,t){let n=un(e);return{color:ln(t,n),icon:cn[n],strikethrough:n===`error`||n===`denied`}}function Es({isThinking:e}){let t=q();return e?V(k,{marginBottom:1,children:V(G,{color:t.text.warning,children:`Thinking...`})}):V(B,{})}function Ds({activeTools:e}){let t=q(),n=Xa();return H(k,{flexDirection:`column`,marginBottom:1,children:[V(G,{color:t.text.emphasis,bold:!0,children:`Tools:`}),V(G,{children:` `}),e.map((e,r)=>{let{color:i,icon:a,strikethrough:o}=Ts(e,t);return H(k,{flexDirection:`column`,children:[H(G,{color:i,strikethrough:o,children:[` `,a,` `,Wa(e.toolName,n),`(`,Ga(e.firstArg),`)`]}),e.diffLines&&e.diffLines.length>0&&V(co,{file:e.diffFile,lines:e.diffLines})]},`${e.toolName}-${r}`)})]})}function Os(e,t,n,r){let i=t.map(e=>Wa(e.toolName,r)).join(`, `),a=[i.length>0?`${Za.tool} ${i}`:void 0,e.length>0?e:n?Za.thinking:void 0].filter(e=>e!==void 0);return a.length===0?V(B,{}):V(G,{children:a.join(` — `)})}function ks({text:e,activeTools:t,isThinking:n=!1}){let r=q(),i=Ha(),a=t.length>0,o=e.length>0,s=K(),c=Ya(),l=Xa();return s?Os(e,t,n,l):!a&&!o?V(Es,{isThinking:n}):H(k,{flexDirection:`column`,children:[a&&V(Ds,{activeTools:t}),o&&H(k,{flexDirection:`column`,marginBottom:1,children:[H(G,{color:r.text.accent,bold:!0,children:[c,`:`]}),V(G,{children:` `}),V(k,{marginLeft:2,children:V(nt,{wrap:`wrap`,children:i(e)})})]})]})}function As(e,t){let n=t?` (current)`:``;return`${e.name} — ${e.appearance}, ${e.source}${n}`}function js({theme:e,isFocused:t,isActive:n,rowNumber:r}){let i=q(),a=r===void 0?t?`> `:` `:xr(r);return H(G,{...t&&r===void 0?{color:i.text.accent,bold:!0}:{},children:[a,As(e,n)]})}function Ms({itemCount:e,buffer:t,invalid:n}){let r=br(e,!0);return H(k,{flexDirection:`column`,children:[H(G,{children:[r,t.length>0?` ${t}`:``]}),n&&V(G,{children:r})]})}function Ns(e,t){let n=e.findIndex(e=>e.id===t);return n<0?0:n}function Ps(e){let[t,n]=M.useState(()=>({syntaxHighlighting:e.syntaxHighlighting,reducedMotion:e.reducedMotion}));return{toggles:t,setToggles:n}}function Fs(e){let{themes:t,activeThemeId:n,preview:r}=e,[i,a]=M.useState(()=>Ns(t,n));return{focusedIndex:i,move:M.useCallback(e=>{t.length!==0&&a(n=>{let i=(n+e+t.length)%t.length,a=t[i];return a&&r(a.id),i})},[r,t])}}function Is(e,t){let{themes:n,select:r,cancel:i}=e,{focusedIndex:a,move:o}=Fs(e),{toggles:s,setToggles:c}=Ps(e),l=M.useRef(s);l.current=s;let u=M.useCallback(e=>{let t=n[e];t&&r(t.id,l.current)},[r,n]),d=Gn({enabled:t&&n.length>0,itemCount:n.length,cancellable:!0,onSelect:u,onCancel:i}),f=M.useCallback(e=>{c(t=>({...t,[e]:!t[e]}))},[c]);return Q(`theme-picker`,e=>{for(let t of e)t===`previous`?o(-1):t===`next`?o(1):t===`select`?u(a):t===`toggle-syntax`?f(`syntaxHighlighting`):t===`toggle-motion`?f(`reducedMotion`):t===`cancel`&&i()},{isActive:!t}),{focusedIndex:a,toggles:s,numbered:d}}function Ls({themes:e,activeThemeId:t,focusedIndex:n,screenReader:r}){return e.length===0?V(G,{dimColor:!0,children:`No themes installed`}):V(B,{children:e.map((e,i)=>V(js,{theme:e,isFocused:i===n,isActive:e.id===t,...r?{rowNumber:i}:{}},e.id))})}function Rs(){return ut()?V(B,{}):V(G,{dimColor:!0,children:`Colour is off for this terminal — themes apply, previews cannot show.`})}function zs({skipped:e}){return e.length===0?V(B,{}):V(k,{flexDirection:`column`,marginTop:1,children:e.map((e,t)=>V(G,{dimColor:!0,children:` Skipped "${e.fileName}" — ${e.reason}`},t))})}function Bs({toggles:e,reducedMotionPin:t,screenReader:n}){let r=e=>e?`on`:`off`,i=t===void 0?``:` (this run: motion ${r(!t.reducedMotion)}, pinned by ${t.tier})`;return H(k,{flexDirection:`column`,children:[V(G,{dimColor:!0,children:`syntax ${r(e.syntaxHighlighting)} · motion ${r(!e.reducedMotion)}${i}`}),n&&V(G,{dimColor:!0,children:`Change with /theme syntax on|off or /theme motion on|off`})]})}function Vs({screenReader:e,itemCount:t,numbered:n}){let r=Z(`theme-picker`,[[[`previous`,`next`],`Preview`],[`select`,`Apply`],[`toggle-syntax`,`Syntax`],[`toggle-motion`,`Motion`],[`cancel`,`Cancel`]]);return e?V(Ms,{itemCount:t,buffer:n.buffer,invalid:n.invalid}):V(Y,{hints:r})}function Hs({picker:e}){let t=q(),n=K(),{themes:r,activeThemeId:i}=e,{focusedIndex:a,toggles:o,numbered:s}=Is(e,n);return H(k,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.focused},paddingX:1,children:[V(G,{color:t.text.accent,bold:!0,children:`Theme`}),V(Rs,{}),V(Bs,{toggles:o,reducedMotionPin:e.reducedMotionPin,screenReader:n}),V(k,{flexDirection:`column`,marginTop:1,children:V(Ls,{themes:r,activeThemeId:i,focusedIndex:a,screenReader:n})}),V(zs,{skipped:e.skipped}),V(Vs,{screenReader:n,itemCount:r.length,numbered:s})]})}function Us({entry:e,selected:t}){let n=q(),r=e.config.enabled,i=r?`●`:`○`,a=r?`[on] `:`[off]`,o=e.config.options?.port,s=typeof o==`number`?`port: ${o}`:``;return V(k,{children:V(G,{color:t?n.text.accent:void 0,bold:t,children:`${i} ${e.transport.name.padEnd(18)} ${a} ${s}`})})}function Ws(e,t,n,r,i,a,o,s,c){Q(`transport-settings`,P(l=>{if(!n){if(l.includes(`previous`)){i(e=>Math.max(0,e-1));return}if(l.includes(`next`)){i(t=>Math.min(e.length-1,t+1));return}if(l.includes(`close`)){s();return}if(l.includes(`toggle`)){let n=e[t];if(!n)return;a(!0),o(void 0),r.setEnabled(n.transport.name,!n.config.enabled).then(()=>{c(),a(!1)}).catch(e=>{o(e instanceof Error?e.message:`could not save the setting`),a(!1)})}}},[n,e,t,r,s,c,i,a,o]))}function Gs({registry:e,onClose:t}){let n=q(),r=Ya(),[i,a]=z(()=>e.getAll()),[o,s]=z(0),[c,l]=z(!1),[u,d]=z(void 0),f=P(()=>{a(e.getAll())},[e]),p=Z(`transport-settings`,[[[`previous`,`next`],`Select`],[`toggle`,`Toggle`],[`close`,`Close`]]);return Ws(i,o,c,e,s,l,d,t,f),H(k,{flexDirection:`column`,paddingX:2,paddingY:1,children:[V(G,{bold:!0,children:`Settings › Transports`}),V(k,{marginTop:1,flexDirection:`column`,children:i.map((e,t)=>V(Us,{entry:e,selected:t===o},e.transport.name))}),H(k,{marginTop:1,flexDirection:`column`,children:[V(Y,{hints:p}),H(G,{dimColor:!0,children:[`A toggle is saved now and applies the next time `,r,` starts.`]})]}),c&&V(k,{marginTop:1,children:V(G,{color:n.text.warning,children:`Saving…`})}),u!==void 0&&V(k,{marginTop:1,children:V(G,{color:n.text.error,children:`Not saved — ${u}`})})]})}function Ks({message:e}){return V(k,{paddingX:1,marginBottom:1,children:V(G,{color:q().text.warning,children:e})})}function qs({model:e}){return V(Se,{items:e.staticItems,children:e=>e.kind===`banner`?V(an,{version:e.version},`logo`):V(vo,{entry:e.entry},e.entry.id)},e.transcriptKey)}function Js({model:e}){let t=q(),{background:n,stream:r}=e;return H(k,{flexDirection:`column`,paddingX:1,flexGrow:1,children:[n.selectedEntry&&n.selectedEntry.kind!==`main_thread`&&V(Mn,{entry:n.selectedEntry,page:n.detail.page,loading:n.detail.loading,error:n.detail.error}),e.isShuttingDown&&V(G,{color:t.text.warning,children:`Shutting down...`}),(r.isThinking||r.activeTools.length>0)&&H(k,{flexDirection:`column`,marginBottom:1,children:[V(ks,{text:r.text,activeTools:r.activeTools,isThinking:r.isThinking}),r.isStalled&&V(G,{color:t.text.warning,children:`⚠ Still waiting on the provider — the network may be stalled. Esc to interrupt.`})]}),!r.isThinking&&r.lastErrorMessage&&V(G,{color:t.text.error,children:`✖ Last turn failed — the session is alive; type your next prompt when ready.`}),V(An,{entries:n.entries,focusedIndex:n.focusedIndex})]})}function Ys({model:e}){if(e.coordinationError!==void 0||e.coordinationPending)return V(B,{});let{background:t,plugin:n,sessionPicker:r,transport:i}=e,a=e.pendingUserAction;return H(B,{children:[t.switcherVisible&&V(Tr,{snapshot:t.snapshot,selectedEntryId:t.selectedEntryId,onSelect:t.select,onClose:t.closeSwitcher,onAttach:t.attachToFork}),e.permissionRequest&&V(Bo,{request:e.permissionRequest}),a&&V(No,{request:a,onAnswer:t=>e.resolveUserAction(a,t)}),n.visible&&V(ns,{callbacks:n.callbacks,onClose:n.close,addMessage:e=>n.addMessage(e.content)}),i.visible&&i.registry&&V(Gs,{registry:i.registry,onClose:i.close}),r.visible&&V(os,{sessions:r.sessions,onSelect:r.select,onCancel:r.cancel}),e.theme.picker.visible&&V(Hs,{picker:e.theme.picker})]})}function Xs({model:e}){let{input:t}=e;return H(B,{children:[V(jn,{percentage:e.contextPercentage}),V(_a,{onSubmit:t.submit,onCancelQueue:t.cancelQueue,isDisabled:t.disabled,isQueueCancellationDisabled:t.queueCancellationDisabled,isAborting:t.isAborting,pendingPrompt:t.pendingPrompt,pendingCount:t.pendingCount,commandQueryPort:t.commandQueryPort,sessionName:t.sessionName,history:t.history,onRequestFocusBackgroundList:t.focusBackgroundList,historySearch:t.historySearch,initialValue:t.initialValue,consumeInitialValue:t.consumeInitialValue,externalPromptOrigin:t.externalPromptOrigin}),V(ws,{...e.status})]})}function Zs({viewModel:e}){let t=q(),n=yr();return H(k,{flexDirection:`column`,children:[V(qs,{model:e}),!e.handoffSuspended&&H(B,{children:[e.updateNotice&&V(Ks,{message:e.updateNotice}),e.coordinationError&&H(G,{color:t.text.error,children:[e.coordinationError,` Press Enter to retry.`]}),n.diagnostic&&V(G,{color:t.text.error,children:`Keybindings ${n.diagnostic.file} ${n.diagnostic.path}: ${n.diagnostic.message} Last valid bindings remain active.`}),n.warnings.map(e=>V(G,{color:t.text.warning,children:`Keybindings ${e.path}: ${e.message}`},`${e.path}:${e.code}`)),e.theme.unknownThemeNotice!==void 0&&V(G,{color:t.text.warning,children:e.theme.unknownThemeNotice}),V(rs,{notices:e.sessionEventNotices}),V(Js,{model:e}),V(Ys,{model:e}),V(Xs,{model:e})]})]})}function Qs(e){return[...e.screenReader?[]:[{kind:`banner`,version:e.version??`0.0.0`}],...e.history.map(e=>({kind:`entry`,entry:e}))]}function $s(e){let t=e.forceExit??(e=>process.exit(e));if(e.isShuttingDown){t(130);return}e.graceful()}function ec(e){let t=e.write??(e=>{process.stdout.write(e)}),n=e.now??(()=>Date.now()),r=e.longToolBellMs??5e3,i=new Map,a=()=>{e.enabled&&t(`\x07`)};return{replyCompleted:a,promptMounted:a,toolStarted(t){e.enabled&&i.set(t,n())},toolCompleted(e){let t=i.get(e);i.delete(e),t!==void 0&&(n()-t<=r||a())}}}const tc={promptStart:`A`,promptEnd:`B`,turnStart:`C`,turnEnd:`D`};function nc(e){return`\x1b]133;${tc[e]}\x07`}function rc(e){let t=e.write??(e=>{process.stdout.write(e)});return{emit(n){!e.enabled||!e.supported()||t(nc(n))}}}function ic(e,t){return e.executionId??`${e.toolName}#${t}`}function ac(e){let t=new Set;return e.forEach((e,n)=>{e.isRunning&&t.add(ic(e,n))}),t}function oc(e){let{enabled:t,isThinking:n,activeTools:r,awaitingAnswer:i}=e,a=L(()=>ec({enabled:t}),[t]),o=oi(),s=li(),c=L(()=>rc({enabled:t,supported:()=>ft({override:s.turnMarks}),write:e=>o.write(e)}),[t,o,s.turnMarks]),l=R(!1),u=R(new Set);I(()=>{n&&!l.current?(c.emit(`promptEnd`),c.emit(`turnStart`)):!n&&l.current&&(c.emit(`turnEnd`),c.emit(`promptStart`),a.replyCompleted()),l.current=n},[n,a,c]),I(()=>{c.emit(`promptStart`)},[c]),I(()=>{i&&a.promptMounted()},[i,a]),I(()=>{let e=ac(r);for(let t of e)u.current.has(t)||a.toolStarted(t);for(let t of u.current)e.has(t)||a.toolCompleted(t);u.current=e},[r,a])}function sc(e){return!!(e.permissionRequest||e.pendingUserAction||e.pluginVisible||e.transportVisible||e.sessionPickerVisible||e.workspaceSwitcherVisible||e.historySearchOpen||e.themePickerVisible||e.coordinationBlocked)}function cc(e){Q(e.isThinking?`thinking`:`background-detail`,t=>{if(sc(e))return;if(t.includes(`abort`)&&e.isThinking){e.readOnly||e.abort();return}let n=e.selectedEntry;if(t.includes(`return-to-main`)&&n&&n.kind!==`main_thread`&&e.mainThreadEntryId){e.selectWorkspaceEntry(e.mainThreadEntryId);return}t.includes(`return-to-main`)&&!e.backgroundListFocused&&!e.readOnly&&e.stopWaitingLoop()})}function lc(e){Q(`app`,t=>{t.includes(`open-workspace-switcher`)&&(e.permissionRequest||e.pendingUserAction||e.pluginVisible||e.sessionPickerVisible||e.historySearchOpen||e.themePickerVisible||e.coordinationBlocked||e.isShuttingDown||e.toggleWorkspaceSwitcher())})}function uc(e){Q(`recovery`,t=>{e.recoveryError!==void 0&&!e.recoveryPending&&t.includes(`retry`)&&e.retryRecovery()})}function dc(e,t){return e===``||t&&e===`]`}function fc(e){let{exit:t}=we(),n=n=>{$s({isShuttingDown:e.isShuttingDown,graceful:()=>void e.shutdown(n).finally(()=>t())})};Ee((t,r)=>{(r.ctrl&&t===`c`||e.attached&&dc(t,r.ctrl))&&n(`prompt_input_exit`)}),I(()=>{let e=()=>n(`other`);return process.on(`SIGINT`,e),process.on(`SIGTERM`,e),()=>{process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}})}function pc(e){cc(e),uc(e),lc(e),fc(e);let t=K();return oc({enabled:t,isThinking:e.isThinking,activeTools:e.activeTools,awaitingAnswer:e.permissionRequest!==null||e.pendingUserAction!==null}),t}function mc(){return Promise.reject(Error(`Plugin management is unavailable in this host.`))}function hc(){return{listInstalled:mc,listAvailablePlugins:mc,install:mc,uninstall:mc,enable:mc,disable:mc,marketplaceAdd:mc,marketplaceRemove:mc,marketplaceUpdate:mc,marketplaceList:mc,reloadPlugins:mc}}function gc(e){return e??hc()}function _c(e){return L(()=>gc(e),[e])}function vc(e){let t=_c(e.pluginAdapter),n=P(t=>e.addEntry(a(i(t))),[e.addEntry]),r=P(t=>{e.setSessionPickerVisible(!1),e.onSessionSwitch(t)},[e.onSessionSwitch,e.setSessionPickerVisible]),o=P(()=>{e.setSessionPickerVisible(!1),e.addEntry(a(i(`Session resume cancelled.`)))},[e.addEntry,e.setSessionPickerVisible]),s=e.hostSessions??m(e.sessionStore,e.cwd),c=e.sessionPickerVisible&&s.length===0;return I(()=>{c&&(e.setSessionPickerVisible(!1),e.addEntry(a(i(`No saved sessions to resume in this workspace.`))))},[c,e.addEntry,e.setSessionPickerVisible]),{plugin:{visible:e.pluginVisible,callbacks:t,close:()=>e.setPluginVisible(!1),addMessage:n},transport:{visible:e.transportVisible,registry:e.transportRegistry,close:()=>e.setTransportVisible(!1)},sessionPicker:{visible:e.sessionPickerVisible&&!c,sessions:s,select:r,cancel:o}}}function yc(e){let[t,n]=z(0),r=P(async t=>{let n=e.selectedEntry;if(n&&n.kind!==`main_thread`&&n.controls.includes(`send`)){await e.sendAgentJob(n.sourceId,t);return}await e.submit(t)},[e.selectedEntry,e.sendAgentJob,e.submit]),i=P(async e=>{n(e=>e+1),await r(e)},[r]),a=R(!1);return I(()=>{a.current&&!e.isThinking&&n(e=>e+1),a.current=e.isThinking},[e.isThinking]),{submit:i,gitRefreshToken:t}}function bc(e){let{screens:t,workspace:n}=e.shell,r=yc({selectedEntry:n.background.selectedEntry,submit:t.handleSubmit,sendAgentJob:e.state.sendAgentJob,isThinking:e.state.isThinking}),i=pc({isThinking:e.state.isThinking,isShuttingDown:e.state.isShuttingDown,readOnly:e.state.readOnly,attached:e.state.attached,permissionRequest:e.state.permissionRequest,pendingUserAction:e.state.pendingUserAction,pluginVisible:t.showPluginTUI,transportVisible:t.showTransportTUI,sessionPickerVisible:t.showSessionPicker,workspaceSwitcherVisible:n.background.switcherVisible,historySearchOpen:e.shell.historySearchOpen,themePickerVisible:t.showThemePicker,selectedEntry:n.background.selectedEntry,backgroundListFocused:n.isBackgroundListFocused,mainThreadEntryId:n.mainThreadEntryId,activeTools:e.state.activeTools,abort:e.state.handleAbort,stopWaitingLoop:e.state.handleStopWaitingLoop,toggleWorkspaceSwitcher:n.toggleSwitcher,selectWorkspaceEntry:e.state.selectExecutionWorkspaceEntry,shutdown:e.state.handleShutdown,recoveryError:e.recoveryError,recoveryPending:e.recoveryPending,coordinationBlocked:e.coordinationBlocked,retryRecovery:e.retryRecovery});return{submission:r,overlays:vc({cwd:e.cwd,pluginAdapter:e.pluginAdapter,pluginVisible:t.showPluginTUI,setPluginVisible:t.setShowPluginTUI,transportRegistry:e.transportRegistry,transportVisible:t.showTransportTUI,setTransportVisible:t.setShowTransportTUI,sessionStore:e.sessionStore,hostSessions:e.state.hostSessions,sessionPickerVisible:t.showSessionPicker,setSessionPickerVisible:t.setShowSessionPicker,onSessionSwitch:e.onSessionSwitch,addEntry:e.state.addEntry}),screenReader:i}}function xc(e){let t=Ya();I(()=>{let n=W(e??``),r=W(t),i=n?`${r} — ${n}`:r;process.stdout.write(`\x1b]0;${i}\x07`)},[e,t])}function Sc(e){let[t,n]=z(!1);return I(()=>{if(e)return e.registerSuspendHooks({suspend:async()=>{n(!0),await new Promise(e=>setTimeout(e,50))},resume:()=>n(!1)})},[e]),t}function Cc(e){let[t,n]=z(),[r,i]=z(!0),a=P(()=>{i(!0),e.start().then(()=>n(void 0)).catch(e=>{let t=e instanceof Error?e.message:String(e);n(`TUI start failed: ${t}`)}).finally(()=>i(!1))},[e]);return I(()=>{a()},[e,a]),{startError:t,startPending:r,retryStart:a}}function wc(e){let[t,n]=z();return I(()=>{let t=!0;return e?.then(e=>{t&&e!==void 0&&n(e)}).catch(()=>{}),()=>{t=!1}},[e]),t}function Tc(e,t){let n=Cc(e),[r,i]=z(e.sessionName);return I(()=>{e.sessionName!==void 0&&e.sessionName!==r&&i(e.sessionName)},[e,e.sessionName,r]),xc(r),{sessionName:r,setSessionName:i,handoffSuspended:Sc(e.terminalHandoffController),updateNotice:wc(t),...n}}function Ec(e){return ce(e.readSettings(e.getUserSettingsPath()))}function Dc(){let e=Cs(),[t,n]=z(()=>Ec(e));return[t,P(()=>{n(Ec(e))},[e])]}function Oc(e){let[t,n]=z(null),[r,i]=z(),[a,o]=z(!1),{entry:s,snapshot:c,read:l}=e;return I(()=>{if(!s||s.kind===`main_thread`){n(null),i(void 0),o(!1);return}let e=!0;return o(!0),i(void 0),l(s.id).then(t=>{e&&(n(t),o(!1))}).catch(t=>{e&&(i(t.message),o(!1))}),()=>{e=!1}},[c,l,s]),{page:t,error:r,loading:a}}function kc(e,t){let n=h(e,{hasSessionRecord:t.hasSessionRecord});if(n.type===`refused`){let e=n.resumeSessionId&&t.formatResumeCommand?.(n.resumeSessionId);t.notify(e?`${n.reason} Open it with: ${e}`:n.reason);return}return t.switchSession(n.sessionId),{sessionId:n.sessionId}}function Ac({sessionStore:e,onSessionSwitch:t,addEntry:n}){let r=Cs();return P(o=>{let s=e=>n(a(i(e)));if(e===void 0){s(`This surface has no session store, so it cannot attach to a forked session.`);return}kc(o,{hasSessionRecord:t=>e.load(t).status===`valid`,switchSession:t,notify:s,...r.formatResumeCommand===void 0?{}:{formatResumeCommand:r.formatResumeCommand}})},[n,r,t,e])}function jc(e){let{snapshot:t,selectedEntryId:n}=e,r=L(()=>t?.entries.find(e=>e.id===n),[t,n]);return{entry:r,detail:Oc({entry:r,snapshot:t,read:e.read}),attachToFork:Ac({sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.addEntry})}}function Mc(e,t,n){return t<=0?{type:`exit`}:n.upArrow?{type:`move`,index:e>0?e-1:null}:n.downArrow?{type:`move`,index:e<t-1?e+1:e}:n.return?{type:`open`,index:Math.min(Math.max(e,0),t-1)}:n.escape?{type:`exit`}:{type:`none`}}function Nc(e,t,n,r,i){Q(`background-list`,i=>{if(e===null)return;let a=Mc(e,t.length,{upArrow:i.includes(`previous`),downArrow:i.includes(`next`),return:i.includes(`open`),escape:i.includes(`close`)});if(a.type===`move`&&n(a.index),a.type===`open`){let e=t[a.index];e&&r(e),n(null)}a.type===`exit`&&n(null)},{isActive:e!==null&&i})}function Pc(e,t,n){let[r,i]=z(null);return I(()=>{i(t=>t===null||e.length===0?null:Math.min(t,e.length-1))},[e.length]),Nc(r,e,i,t,n),{focusedIndex:r,focusList:P(()=>{e.length>0&&i(0)},[e.length])}}function Fc(e){return{open:P(()=>e(!0),[e]),toggle:P(()=>e(e=>!e),[e]),close:P(()=>e(!1),[e])}}function Ic(e){let t=L(()=>hn(e.snapshot),[e.snapshot]),{focusedIndex:n,focusList:r}=Pc(t.map(e=>e.id),e.select,e.navigationEnabled),i=jc({selectedEntryId:e.selectedEntryId,snapshot:e.snapshot,read:e.read,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.addEntry}),a=Fc(e.setSwitcherVisible),o=i.entry;return{background:{entries:t,focusedIndex:n,selectedEntry:o,detail:i.detail,switcherVisible:e.switcherVisible,snapshot:e.snapshot,selectedEntryId:e.selectedEntryId,select:e.select,closeSwitcher:a.close,attachToFork:i.attachToFork},activeBackgroundTaskCount:gn(e.snapshot),activeAgentLabel:o?.kind===`main_thread`?void 0:o?.title,mainThreadEntryId:e.snapshot?.entries.find(e=>e.kind===`main_thread`)?.id,isSelectedEntryInteractive:!o||o.kind===`main_thread`||o.controls.includes(`send`),isBackgroundListFocused:n!==null,openSwitcher:a.open,toggleSwitcher:a.toggle,focusBackgroundList:r}}function Lc(e,t,n){let r=e=>{if(e.requesterDriverId===T)switch(e.intent.type){case`show-plugin-manager`:t.setShowPluginTUI(!0);return;case`show-settings`:t.setShowTransportTUI(!0);return;case`show-session-picker`:t.setShowSessionPicker(!0);return;case`show-agent-switcher`:n.current.openAgentSwitcher?.();return;case`show-theme-picker`:t.setShowThemePicker(!0);return}},i=e=>{n.current.setSessionName(e.name)};return e.on(`ui_intent`,r),e.on(`session_renamed`,i),()=>{e.off(`ui_intent`,r),e.off(`session_renamed`,i)}}function Rc(e){let t=R(e);return t.current=e,t}function zc({uiEventPort:e,baseHandleSubmit:t,setSessionName:n,refreshStatusLineSettings:r,refreshAppearanceSettings:i,showSessionPickerOnStart:a,openAgentSwitcher:o}){let[s,c]=z(!1),[l,u]=z(a??!1),[d,f]=z(!1),[p,m]=z(!1),h=Rc({setSessionName:n,refreshStatusLineSettings:r,refreshAppearanceSettings:i,openAgentSwitcher:o});return Ae(()=>Lc(e,{setShowPluginTUI:c,setShowTransportTUI:f,setShowSessionPicker:u,setShowThemePicker:m},h),[e]),{handleSubmit:P(async e=>{await t(e),e.trimStart().startsWith(`/`)&&(h.current.refreshStatusLineSettings(),h.current.refreshAppearanceSettings())},[t]),showPluginTUI:s,showSessionPicker:l,showTransportTUI:d,showThemePicker:p,setShowPluginTUI:c,setShowSessionPicker:u,setShowTransportTUI:f,setShowThemePicker:m}}function Bc(e){let t={...v},n=e.statusline;return Vc(n)?{enabled:typeof n.enabled==`boolean`?n.enabled:t.enabled,gitBranch:typeof n.gitBranch==`boolean`?n.gitBranch:t.gitBranch}:t}function Vc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Hc(e){return Bc(e.readSettings(e.getUserSettingsPath()))}function Uc(){let e=Cs(),[t,n]=z(()=>Hc(e));return[t,P(()=>{n(Hc(e))},[e])]}function Wc(e){let[t,n]=z(!1),[r,i]=z(!1),[a,o]=Uc(),[s,c]=Dc(),l=zc({uiEventPort:e.state.uiEventPort,baseHandleSubmit:e.state.handleSubmit,setSessionName:e.setSessionName,refreshStatusLineSettings:o,refreshAppearanceSettings:c,showSessionPickerOnStart:e.showSessionPickerOnStart,openAgentSwitcher:()=>n(!0)}),u=e.state.permissionRequest===null&&e.state.pendingUserAction===null&&!l.showPluginTUI&&!l.showTransportTUI&&!l.showSessionPicker&&!l.showThemePicker&&!t&&!r&&!e.coordinationBlocked;return{screens:l,workspace:Ic({snapshot:e.state.executionWorkspaceSnapshot,selectedEntryId:e.state.selectedExecutionEntryId,select:e.state.selectExecutionWorkspaceEntry,read:e.state.readExecutionWorkspaceDetail,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.state.addEntry,navigationEnabled:u,switcherVisible:t,setSwitcherVisible:n}),statusSettings:a,appearance:s,historySearchOpen:r,setHistorySearchOpen:i}}function Gc(e=ot(),t=[]){let n=new Map(e.map(e=>[e.id,e]));return{list:()=>e,skipped:()=>t,get:e=>n.get(e),resolve:e=>{if(e===void 0||e===at)return{theme:st(n.get(at))};let t=n.get(e);return t?{theme:t}:{theme:st(n.get(at)),unknownId:e}}}}function Kc(e){return`Theme "${e}" is not installed — using "${at}".`}function qc(e){return{id:e.id,name:e.name,appearance:e.appearance,source:e.source}}function Jc(e){return{listThemes:()=>e.registry.list().map(qc),getTheme:t=>{let n=e.registry.get(t);return n?qc(n):void 0},getAppearance:()=>({settings:e.readAppearance(),...e.reducedMotionPin===void 0?{}:{reducedMotionPin:e.reducedMotionPin}})}}function Yc(e){let t=L(()=>e.registry??Gc(),[e.registry]),[n,r]=z(void 0),i=L(()=>t.resolve(n??e.appearance.theme),[t,n,e.appearance.theme]),{setVisible:a,submit:o}=e,s=P(()=>{r(void 0),a(!1)},[a]),{syntaxHighlighting:c,reducedMotion:l}=e.appearance,u=P((e,t)=>{r(void 0),a(!1);let n=[`/theme ${e}`];t.syntaxHighlighting!==c&&n.push(`syntax ${t.syntaxHighlighting?`on`:`off`}`),t.reducedMotion!==l&&n.push(`motion ${t.reducedMotion?`off`:`on`}`),o(n.join(` `))},[l,a,o,c]),d=n===void 0?i.unknownId:void 0,f=e.reducedMotion??e.appearance.reducedMotion;return{resolved:i.theme,reducedMotion:f,syntaxHighlighting:e.appearance.syntaxHighlighting,...d===void 0?{}:{unknownThemeNotice:Kc(d)},picker:{visible:e.visible,themes:t.list(),skipped:t.skipped(),activeThemeId:e.appearance.theme,syntaxHighlighting:e.appearance.syntaxHighlighting,reducedMotion:e.appearance.reducedMotion,...e.reducedMotionOverride===void 0||e.reducedMotion===void 0?{}:{reducedMotionPin:{tier:e.reducedMotionOverride,reducedMotion:e.reducedMotion}},preview:r,select:u,cancel:s}}}function Xc(e){let[,t]=z(0);I(()=>e.subscribe(()=>t(e=>e+1)),[e]);let n=e.getSnapshot(),r=P(t=>e.selectExecutionWorkspaceEntry(t),[e]),i=P(t=>e.readExecutionWorkspaceDetail(t),[e]);return{uiEventPort:e.getSessionUiEventPort(),commandQueryPort:e.getCommandQueryPort(),history:n.history,addEntry:t=>e.addEntry(t),streamingText:n.streamingText,activeTools:n.activeTools,isThinking:n.isThinking,isAborting:n.isAborting,lastErrorMessage:n.lastErrorMessage,isStalled:n.isStalled,sessionEventNotices:n.sessionEventNotices,isShuttingDown:n.isShuttingDown,pendingPrompt:n.pendingPrompt,pendingCount:n.pendingCount,executionWorkspaceSnapshot:n.executionWorkspaceSnapshot,selectedExecutionEntryId:n.selectedExecutionEntryId,permissionRequest:n.permissionRequest,pendingUserAction:n.pendingUserAction,contextState:n.contextState,hostSessions:n.hostSessions,transcriptGeneration:n.transcriptGeneration??0,readOnly:n.readOnly===!0,attached:n.attached===!0,handleSubmit:t=>e.handleInput(t),handleAbort:()=>e.abort(),handleCancelQueue:()=>e.cancelQueue(),handleStopWaitingLoop:()=>e.stopWaitingSelfPacedLoop(),handleShutdown:t=>e.shutdown({reason:t}),sendAgentJob:(t,n)=>e.sendAgentJob(t,n),resolveUserAction:(t,n)=>e.resolveUserAction(t,n),getRuntimeStatusSnapshot:t=>e.getRuntimeStatusSnapshot(t),selectExecutionWorkspaceEntry:r,readExecutionWorkspaceDetail:i}}function Zc(e,t){let n=e.sessionSwitchError??t.startError,r=!!(e.sessionSwitchPending||t.startPending);return{error:n,pending:r,blocked:n!==void 0||r}}function Qc(e){let{promptHistorySource:t,promptHistoryProject:n}=e.props;if(t!==void 0&&n!==void 0)return{source:t,project:n,sessionId:e.runtime.sessionId,onOpenChange:e.shell.setHistorySearchOpen}}function $c(e){let{screens:t,workspace:n}=e.shell,r=e.state,i=!!(r.permissionRequest||r.pendingUserAction||t.showPluginTUI||t.showTransportTUI||t.showSessionPicker||t.showThemePicker||n.background.switcherVisible),a=e.coordination.blocked||i||r.isShuttingDown||!n.isSelectedEntryInteractive||n.isBackgroundListFocused;return{submit:e.interaction.submission.submit,cancelQueue:r.handleCancelQueue,disabled:a||r.isThinking&&r.pendingPrompt!==null,queueCancellationDisabled:a||r.readOnly,isAborting:r.isAborting,pendingPrompt:r.pendingPrompt,pendingCount:r.pendingCount,commandQueryPort:r.commandQueryPort,sessionName:e.lifecycle.sessionName,history:r.history,focusBackgroundList:n.focusBackgroundList,historySearch:Qc(e)}}function el(e){let{props:t,runtime:n,state:r}=e,i=e.shell.workspace;return{cwd:t.cwd,permissionMode:n.permissionMode,modelId:n.modelId??t.modelId,providerType:t.providerType,sessionId:n.sessionId,isThinking:r.isThinking,activeToolCount:r.activeTools.length,activeBackgroundTaskCount:i.activeBackgroundTaskCount,hasPendingPrompt:r.pendingPrompt!==null,contextState:r.contextState,sessionName:e.lifecycle.sessionName,settings:e.shell.statusSettings,activeAgentLabel:i.activeAgentLabel,activePresetId:n.activePresetId,effort:n.effort,gitRefreshToken:e.interaction.submission.gitRefreshToken,readOnly:r.readOnly}}function tl(e){let{interaction:t,lifecycle:n,shell:r,state:i}=e;return{staticItems:e.staticItems,transcriptKey:i.transcriptGeneration,handoffSuspended:n.handoffSuspended,updateNotice:n.updateNotice,coordinationError:e.coordination.error,coordinationPending:e.coordination.pending,sessionEventNotices:i.sessionEventNotices,isShuttingDown:i.isShuttingDown,stream:{text:i.streamingText,activeTools:i.activeTools,isThinking:i.isThinking,isStalled:i.isStalled,lastErrorMessage:i.lastErrorMessage},background:r.workspace.background,permissionRequest:i.permissionRequest,pendingUserAction:i.pendingUserAction,resolveUserAction:i.resolveUserAction,...t.overlays,theme:e.theme,contextPercentage:i.contextState.percentage,input:$c(e),status:el(e)}}function nl(e,t){return Yc({appearance:t.appearance,registry:e.themeRegistry,reducedMotion:e.reducedMotion,reducedMotionOverride:e.reducedMotionOverride,visible:t.screens.showThemePicker,setVisible:t.screens.setShowThemePicker,submit:e=>void t.screens.handleSubmit(e)})}function rl(e,t){let[n,r]=z(e);return{initialValue:n,consumeInitialValue:P(()=>r(void 0),[]),externalPromptOrigin:t===`external-link`}}function il(e,t,n){return L(()=>Qs({history:e,version:t,screenReader:n}),[e,n,t])}function al(e){let t=rl(e.initialInput,e.initialInputOrigin),n=Xc(e.channel),r=Tc(e.channel,e.startupUpdateNotice),i=Zc(e,r),a=Wc({state:n,setSessionName:r.setSessionName,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,showSessionPickerOnStart:e.showSessionPickerOnStart,coordinationBlocked:i.blocked}),o=bc({cwd:e.cwd,state:n,shell:a,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,pluginAdapter:e.pluginAdapter,transportRegistry:e.transportRegistry,recoveryError:i.error,recoveryPending:i.pending,coordinationBlocked:i.blocked,retryRecovery:e.sessionSwitchError===void 0?r.retryStart:e.onRetrySessionSwitch}),s=tl({props:e,state:n,lifecycle:r,shell:a,interaction:o,staticItems:il(n.history,e.version,o.screenReader),runtime:n.getRuntimeStatusSnapshot(e.permissionMode??`default`),coordination:i,theme:nl(e,a)});return{...s,input:{...s.input,...t}}}function ol(e){let t=al(e);return V(_t,{theme:t.theme.resolved,reducedMotion:t.theme.reducedMotion,syntaxHighlighting:t.theme.syntaxHighlighting,children:V(Zs,{viewModel:t})})}function sl(e){let[t,n]=z(()=>({channel:e.createChannel(e.resumeSessionId),sessionId:e.resumeSessionId})),[r,i]=z(e.showSessionPickerOnStart??!1),[a,o]=z(),[s,c]=z(!1),[l,u]=z(),d=R(!1),f=R(!0);I(()=>()=>{f.current=!1},[]);let p=P(async r=>{if(!d.current){d.current=!0,c(!0);try{if(i(!1),e.requestSessionSwitch)await e.requestSessionSwitch(r);else{if(await t.channel.stop(),!f.current)return;n({channel:e.createChannel(r),sessionId:r})}if(!f.current)return;u(void 0),o(void 0)}catch(e){let t=e instanceof Error?e.message:String(e);o(`Session switch failed: ${t}`),u(r)}finally{d.current=!1,c(!1)}}},[e.createChannel,e.requestSessionSwitch,t.channel]);return{state:t,showPicker:r,error:a,switching:s,switchSession:p,retrySwitch:P(()=>{l!==void 0&&p(l)},[l,p])}}function cl(e){let t=sl(e);return V(Ss,{value:e.cliAdapter,children:V(ol,{cwd:e.cwd,channel:t.state.channel,onSessionSwitch:t.switchSession,onRetrySessionSwitch:t.retrySwitch,sessionSwitchError:t.error,sessionSwitchPending:t.switching,showSessionPickerOnStart:t.showPicker,...e.initialInput===void 0?{}:{initialInput:e.initialInput},...e.initialInputOrigin===void 0?{}:{initialInputOrigin:e.initialInputOrigin},...e.providerType===void 0?{}:{providerType:e.providerType},...e.modelId===void 0?{}:{modelId:e.modelId},...e.permissionMode===void 0?{}:{permissionMode:e.permissionMode},...e.version===void 0?{}:{version:e.version},...e.sessionStore===void 0?{}:{sessionStore:e.sessionStore},...e.startupUpdateNotice===void 0?{}:{startupUpdateNotice:e.startupUpdateNotice},...e.transportRegistry===void 0?{}:{transportRegistry:e.transportRegistry},...e.pluginAdapter===void 0?{}:{pluginAdapter:e.pluginAdapter},...e.promptHistorySource===void 0?{}:{promptHistorySource:e.promptHistorySource},...e.promptHistoryProject===void 0?{}:{promptHistoryProject:e.promptHistoryProject},...e.themeRegistry===void 0?{}:{themeRegistry:e.themeRegistry},...e.reducedMotion===void 0?{}:{reducedMotion:e.reducedMotion},...e.reducedMotionOverride===void 0?{}:{reducedMotionOverride:e.reducedMotionOverride}},t.state.sessionId??`__new__`)})}var ll=class{options;attendedState=!0;focusObserved=!1;listeners=new Set;idleTimer;idleThresholdMs;constructor(e){this.options=e,this.idleThresholdMs=e.idleThresholdMs??3e5}get attended(){return this.attendedState}get source(){return this.focusObserved?`focus`:`idle`}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}start(){this.focusObserved||this.armIdleTimer()}focusIn(){this.observeFocus(),this.transition(!0)}focusOut(){this.observeFocus(),this.transition(!1)}keystroke(){this.focusObserved||(this.transition(!0),this.armIdleTimer())}observeFocus(){if(!this.options.focusReporting)throw Error(`AttentionTracker: a focus event arrived although focus reporting is off.`);this.focusObserved||(this.focusObserved=!0,this.idleTimer!==void 0&&clearTimeout(this.idleTimer),this.idleTimer=void 0)}dispose(){this.idleTimer!==void 0&&clearTimeout(this.idleTimer),this.idleTimer=void 0,this.listeners.clear()}armIdleTimer(){this.idleTimer!==void 0&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.transition(!1)},this.idleThresholdMs),typeof this.idleTimer==`object`&&`unref`in this.idleTimer&&this.idleTimer.unref()}transition(e){if(this.attendedState===e)return;this.attendedState=e;let t={kind:e?`returned`:`lost`,at:new Date(this.options.now()).toISOString()};for(let e of this.listeners)e(t)}};function ul(e,t){if(!t||!e.includes(27))return{forwarded:e,focusIn:0,focusOut:0};let n=e.toString(`latin1`),r=0,i=0,a=``,o=0;for(;o<n.length;)n.startsWith(`\x1B[I`,o)?(r+=1,o+=3):n.startsWith(`\x1B[O`,o)?(i+=1,o+=3):(a+=n[o],o+=1);return{forwarded:Buffer.from(a,`latin1`),focusIn:r,focusOut:i}}var dl=class extends ye{source;hooks;onData=e=>{let t=ul(typeof e==`string`?Buffer.from(e):e,this.hooks.negotiated());for(let e=0;e<t.focusOut;e+=1)this.hooks.onFocusOut();for(let e=0;e<t.focusIn;e+=1)this.hooks.onFocusIn();t.forwarded.length!==0&&(this.hooks.onKeystroke(),this.push(t.forwarded))};constructor(e,t){super({read(){}}),this.source=e,this.hooks=t,e.on(`data`,this.onData)}get isTTY(){return this.source.isTTY===!0}setRawMode(e){return this.source.setRawMode?.(e),this}ref(){return this.source.ref?.(),this}unref(){return this.source.unref?.(),this}asInkStdin(){return this}detach(){this.source.off(`data`,this.onData)}};function fl(e){if(e.enabled)return`[Screen reader mode: on via ${e.channel??`settings`}]`;if(e.hint===!0)return`[Screen reader mode: off — run with --screen-reader]`}function pl(e,t=e=>{process.stdout.write(e)}){let n=fl(e);n!==void 0&&t(`${n}\n`)}function ml(e){return e??(e=>{process.stderr.write(`${e}\n`)})}function hl(e,t,n,r,i){if(e===void 0||e.trim()===``)return n;let a=Number(e.trim());return!Number.isFinite(a)||!Number.isInteger(a)||a<0?(i(`${t}: ignoring "${e}" — expected a whole number of milliseconds. Using ${n}.`),n):a>r?(i(`${t}: clamping ${a} to the ${r} ms sanity bound.`),r):a}function gl(e){if(!e.enabled)return{startupQuietMs:0,preparkMs:0};let t=ml(e.warn);return{startupQuietMs:hl(e.overrides?.startupQuiet?.raw,e.overrides?.startupQuiet?.label??`startup quiet period`,900,6e5,t),preparkMs:hl(e.overrides?.prepark?.raw,e.overrides?.prepark?.label??`pre-write park`,50,5e3,t)}}function _l(e){return e?.isTTY!==!0||typeof e.setRawMode!=`function`?()=>{}:(e.setRawMode(!0),()=>{e.setRawMode?.(!1)})}async function vl(e,t){if(e<=0)return`elapsed`;let n=_l(t);return new Promise(r=>{let i=e=>{n(),t?.pause?.(),r(e)},a=()=>{clearTimeout(o),i(`keypress`)},o=setTimeout(()=>{t!==void 0&&t.off(`data`,a),i(`elapsed`)},e);o.unref?.(),t!==void 0&&(t.once(`data`,a),t.resume?.())})}function yl(e){return typeof e==`string`?e:Buffer.from(e).toString(`utf8`)}function bl(e){return W(e).trim().length>0}var xl=class{source;preparkMs;now;open;queue=[];timer;lastPrintableReleaseAt;echoArmed=!1;echoExpiryScheduled=!1;flushing=!1;drainWaiters=[];constructor(e){this.source=e.stdout,this.preparkMs=e.preparkMs,this.now=e.now??Date.now,this.on=((...e)=>this.source.on(...e)),this.off=((...e)=>this.source.off(...e))}get columns(){return this.source.columns??80}get rows(){return this.source.rows??24}get isTTY(){return this.source.isTTY??!1}get destroyed(){return this.source.destroyed??!1}get writable(){return this.source.writable??!0}get writableEnded(){return this.source.writableEnded??!1}get writableLength(){return this.source.writableLength??0}get writableNeedDrain(){return this.source.writableNeedDrain??!1}on;off;write(e,t,n){let r=typeof t==`function`?t:n,i=yl(e),a=this.open;if(a===void 0){let e={chunks:[],echo:this.echoArmed,printable:!1,barrier:!1};a=e,this.open=e,process.nextTick(()=>this.close(e))}return a.chunks.push({text:i,callback:r}),i.length===0?a.barrier=!0:!a.printable&&bl(i)&&(a.printable=!0),!this.writableNeedDrain}asInkStdout(){return this}armEchoRelease(){this.echoArmed=!0,!this.echoExpiryScheduled&&(this.echoExpiryScheduled=!0,setImmediate(()=>{this.echoArmed=!1,this.echoExpiryScheduled=!1}))}drain(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0);for(let e of this.queue.splice(0))this.release(e);return this.settled()}flush(){return this.flushing=!0,this.drain()}settled(){return this.open===void 0&&this.queue.length===0?Promise.resolve():new Promise(e=>{this.drainWaiters.push(e)})}close(e){if(this.open===e){if(this.open=void 0,this.isParked(e)){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0);for(let e of this.queue.splice(0))this.release(e)}this.queue.push(e),this.pump()}}isParked(e){return this.preparkMs>0&&this.lastPrintableReleaseAt!==void 0&&e.printable&&!e.echo&&!this.flushing}pump(){for(this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0);this.queue.length>0;){let e=this.queue[0];if(this.isParked(e)){let e=(this.lastPrintableReleaseAt??0)+this.preparkMs-this.now();if(e>0){this.timer=setTimeout(()=>{this.timer=void 0,this.pump()},e);return}}this.queue.shift(),this.release(e)}if(this.open===void 0){let e=this.drainWaiters;this.drainWaiters=[];for(let t of e)t()}}release(e){for(let t of e.chunks)this.source.write(t.text,t.callback);e.printable&&(this.lastPrintableReleaseAt=this.now())}};function Sl(e){return new xl(e)}function Cl(e){return{armEchoRelease:()=>e.armEchoRelease(),write:t=>{e.write(t)}}}function wl(e){let t=e.write??(e=>{process.stdout.write(e)}),n=!1;return{get negotiated(){return n},enable(){n||!e.supported()||(n=!0,t(`\x1B[?1004h`))},disable(){n&&(n=!1,t(`\x1B[?1004l`))}}}var Tl=class{hooks;instance;modeHooks;registerSuspendHooks(e){return this.hooks=e,()=>{this.hooks===e&&(this.hooks=void 0)}}setTerminalModeHooks(e){this.modeHooks=e}setInkInstance(e){this.instance=e}get canHandoffTerminal(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&this.hooks!==void 0}async runWithTerminal(e){let t=this.hooks;if(!this.canHandoffTerminal||t===void 0)throw Error(`TUI terminal handoff unavailable: no interactive TTY, or the App is not mounted.`);await t.suspend(),await this.modeHooks?.preSuspend(),this.instance?.clear();let n=process.stdin;n.isTTY&&typeof n.setRawMode==`function`&&n.setRawMode(!1),n.pause();try{return await e()}finally{n.isTTY&&typeof n.setRawMode==`function`&&n.setRawMode(!0),n.resume(),t.resume(),this.modeHooks?.postResume()}}};const El=new Set([`completed`,`failed`,`stopped`]);var Dl=class{lostAt;lastTurnSource=`user`;turnsFinished=0;wakeTurnsFinished=0;needsInputCount=0;errorCount=0;currentStates=new Map;reachedTerminal=new Map;baseline=new Map;baselinePending=!1;get away(){return this.lostAt!==void 0}onLost(e){this.lostAt=Date.parse(e),this.reset(),this.baseline=new Map(this.currentStates),this.baselinePending=this.currentStates.size===0}onReturned(e){if(this.lostAt===void 0)return;let t=Math.max(0,Date.parse(e)-this.lostAt);this.lostAt=void 0;let n=this.parts();if(this.reset(),n.length!==0)return Al(`While away ${kl(t)}: ${n.join(` · `)}`)}turnSource(e){this.lastTurnSource=e}turnCompleted(){this.away&&(this.turnsFinished+=1,this.lastTurnSource===`agent-wakeup`&&(this.wakeTurnsFinished+=1))}needsInput(){this.away&&(this.needsInputCount+=1)}error(){this.away&&(this.errorCount+=1)}entryState(e,t){if(this.currentStates.set(e,t),!this.away)return;if(this.baselinePending){this.baseline.set(e,t);return}let n=this.baseline.get(e),r=n!==void 0&&El.has(n);if(!El.has(t)||r){this.reachedTerminal.delete(e);return}this.reachedTerminal.set(e,t)}snapshotComplete(){this.baselinePending=!1}parts(){let e=[];if(this.turnsFinished>0){let t=this.wakeTurnsFinished>0?` (${this.wakeTurnsFinished} wake)`:``;e.push(`${this.turnsFinished} ${Ol(this.turnsFinished,`turn`)} finished${t}`)}this.needsInputCount>0&&e.push(`${this.needsInputCount} needs input`);let t={completed:0,failed:0,stopped:0};for(let e of this.reachedTerminal.values())e in t&&(t[e]+=1);for(let n of[`completed`,`failed`,`stopped`])t[n]>0&&e.push(`${t[n]} ${n}`);return this.errorCount>0&&e.push(`${this.errorCount} ${Ol(this.errorCount,`error`)}`),e}reset(){this.turnsFinished=0,this.wakeTurnsFinished=0,this.needsInputCount=0,this.errorCount=0,this.reachedTerminal.clear()}};function Ol(e,t){return e===1?t:`${t}s`}function kl(e){let t=Math.floor(e/6e4);if(t<1)return`<1m`;let n=Math.floor(t/60),r=t%60;return n===0?`${r}m`:r===0?`${n}h`:`${n}h ${r}m`}function Al(e){return e.length<=120?e:`${e.slice(0,119)}…`}var jl=class{options;recap=new Dl;unsubscribe;now;constructor(e){this.options=e,this.now=e.now??Date.now}wire(){this.unsubscribe===void 0&&(this.options.source.attended||this.recap.onLost(new Date(this.now()).toISOString()),this.unsubscribe=this.options.source.subscribe(e=>{if(e.kind===`lost`){this.recap.onLost(e.at);return}let t=this.recap.onReturned(e.at);t!==void 0&&this.options.onRecap(t)}))}unwire(){this.unsubscribe?.(),this.unsubscribe=void 0}onTurnSource=e=>{this.recap.turnSource(e)};onComplete=()=>{this.recap.turnCompleted()};onError=()=>{this.recap.error()};onNeedsInput=()=>{this.recap.needsInput()};onWorkspaceSnapshot=e=>{for(let t of e.entries)t.kind!==`main_thread`&&this.recap.entryState(t.id,t.state);this.recap.snapshotComplete()}};function Ml(e){return/not initialized/i.test(e.message)}function Nl(e){let t=e.isBenignError??Ml,n=null,r=0,i;function a(){n!==null&&(clearInterval(n),n=null)}function o(){r+=e.intervalMs;try{e.check()}catch(n){let o=n instanceof Error?n:Error(String(n));if(!t(o)){a(),e.onFailure({kind:`error`,error:o});return}i=o,r>=e.timeoutMs&&(a(),e.onFailure({kind:`timeout`,lastError:i}));return}a(),e.onReady()}return{start(){n===null&&(r=0,n=setInterval(o,e.intervalMs))},stop:a}}function Pl(e,t,n,r,o){if(e.data?.pluginRegistryReloaded===!0&&o?.(n),r.addEntry(a(i(e.message))),t.isInitialized){let e=t.getContextState();r.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})}}function Fl(e){let t=e.slice(1).split(/\s+/);return{name:t[0]?.toLowerCase()??``,args:t.slice(1).join(` `)}}var Il=class extends AggregateError{},Ll=class{operations;defaultShutdownTimeoutMs;started=!1;startPromise;teardownBegun=!1;stopped=!1;shuttingDown=!1;shutdownPromise;stopPromise;constructor(e,t){this.operations=e,this.defaultShutdownTimeoutMs=t}get isShuttingDown(){return this.shuttingDown}get isActiveForPeerStatus(){return this.started&&!this.teardownBegun&&!this.shuttingDown}async start(){if(this.teardownBegun)throw Error(`Cannot start a channel after teardown has begun.`);if(this.started)return;let e=this.startPromise??=this.operations.start();try{await e,this.started=!0}catch(e){throw e instanceof Il&&(this.teardownBegun=!0),e}finally{this.startPromise===e&&(this.startPromise=void 0)}}async stop(){if(this.teardownBegun=!0,!this.stopped){this.stopPromise??=this.performStop();try{await this.stopPromise}catch(e){throw this.stopPromise=void 0,e}}}async performStop(){let e=this.startPromise,t;if(e!==void 0)try{await e}catch(e){t=e instanceof Error?e:Error(String(e))}let n;try{await this.operations.stop()}catch(e){n=e instanceof Error?e:Error(String(e))}if(this.shutdownPromise??=this.shutdownSessionBounded({reason:`other`,message:`channel stopped`},this.defaultShutdownTimeoutMs),await this.shutdownPromise,n!==void 0&&t!==void 0)throw AggregateError([t,n],`TUI channel start and teardown both failed.`);if(n!==void 0)throw n;if(this.started=!1,this.stopped=!0,t!==void 0)throw t}async shutdown(e){this.teardownBegun=!0,this.shuttingDown||(this.shuttingDown=!0,this.operations.beginShutdown());let t=this.stopPromise;if(t!==void 0){await t.catch(()=>void 0);return}this.shutdownPromise??=this.performShutdown(e),await this.shutdownPromise}async performShutdown(e){let t=this.startPromise;t!==void 0&&await t.catch(()=>void 0),await this.shutdownSessionBounded({reason:e?.reason??`prompt_input_exit`,message:`CLI shutdown`},e?.timeoutMs??this.defaultShutdownTimeoutMs)}async shutdownSessionBounded(e,t){let n,r=new Promise(e=>{n=setTimeout(e,t),n.unref?.()});await Promise.race([this.operations.shutdownSession(e).catch(()=>void 0),r]),n&&clearTimeout(n)}},Rl=class{onChange;entries=[];processing=!1;constructor(e){this.onChange=e}get current(){return this.processing?this.entries[0]?.presentedRequest??null:null}enqueue(e,t){return new Promise(n=>{this.entries.push({presentedRequest:{...e},resolve:n,...t===void 0?{}:{id:t}}),this.processNext()})}resolveCurrent(e,t){if(this.entries[0]?.presentedRequest!==e)return;let n=this.entries.shift();n&&(this.processing=!1,this.onChange(),n.resolve(t),this.processNext())}dismissById(e){let t=this.entries.filter(t=>t.id===e);if(t.length===0)return!1;this.entries=this.entries.filter(t=>t.id!==e),this.processing=!1;for(let e of t)e.resolve({type:`cancelled`});return this.processNext(),!0}cancelAll(){let e=this.entries;this.entries=[],this.processing=!1;for(let t of e)t.resolve({type:`cancelled`});this.onChange()}processNext(){if(!this.processing){if(!this.entries[0]){this.onChange();return}this.processing=!0,this.onChange()}}},zl=class{onChange;entries=[];processing=!1;currentRequest=null;constructor(e){this.onChange=e}get current(){return this.currentRequest}enqueue(e,t,n,r,i,a){return new Promise(o=>{this.entries.push({toolName:e,toolArgs:t,resolve:o,...n===void 0?{}:{id:n},...r===void 0?{}:{canPersistProjectPermission:r},...i===void 0?{}:{requestedByPeer:i},...a===void 0?{}:{requester:a}}),this.processNext()})}dismissById(e){let t=this.entries.filter(t=>t.id===e);if(t.length===0)return!1;let n=this.entries[0]?.id===e;this.entries=this.entries.filter(t=>t.id!==e);for(let e of t)e.resolve(!1);return n&&(this.processing=!1,this.currentRequest=null,this.processNext()),!0}cancelAll(){let e=this.entries;this.entries=[],this.processing=!1,this.currentRequest=null;for(let t of e)t.resolve(!1);this.onChange()}processNext(){if(this.processing)return;let e=this.entries[0];if(!e){this.currentRequest=null,this.onChange();return}this.processing=!0,this.currentRequest={toolName:e.toolName,toolArgs:e.toolArgs,...e.canPersistProjectPermission===void 0?{}:{canPersistProjectPermission:e.canPersistProjectPermission},...e.requestedByPeer===void 0?{}:{requestedByPeer:e.requestedByPeer},...e.requester===void 0?{}:{requester:e.requester},resolve:t=>{this.entries[0]===e&&(this.entries.shift(),this.processing=!1,this.currentRequest=null,e.resolve(t),setTimeout(()=>this.processNext(),0))}},this.onChange()}};function Bl(e,t){let n=null;try{n=t.getActiveDriverId?.()??null}catch{n=null}return a(s(e,n?{metadata:{driverId:n}}:{}))}function Vl(e,t){e(`plan_event`,e=>t.addSessionEventNotice({event:`plan_event`,payload:e})),e(`context_file_refreshed`,e=>t.addSessionEventNotice({event:`context_file_refreshed`,payload:e})),e(`branch_event`,e=>t.addSessionEventNotice({event:`branch_event`,payload:e}))}function Hl(e,t,n,r,i){let a=((...e)=>{try{n(...e)}catch(e){let n=e instanceof Error?e:Error(String(e));try{r(n,t)}catch{}}});e.on(t,a),i.push({event:t,handler:a})}var Ul=class{options;bindings=[];constructor(e){this.options=e}wire(){if(this.bindings.length>0)return;let{session:e,manager:t,attention:r}=this.options,i=n=>{t.addUserEcho(Bl(n,e))},a=()=>t.syncHistory(e.getFullHistory());this.bind(`user_message`,i),this.bind(`text_delta`,t.onTextDelta),this.bind(`tool_start`,t.onToolStart),this.bind(`tool_end`,t.onToolEnd),this.bind(`thinking`,t.onThinking),this.bind(`complete`,e=>{t.onComplete(e),r?.onComplete(),a()}),this.bind(`interrupted`,t.onInterrupted),this.bind(`error`,e=>{t.onError(e),r?.onError(),a()}),this.bind(`context_update`,t.onContextUpdate),this.bind(`compact`,a),this.bind(`skill_activation`,a),this.bind(`memory_event`,a),this.bind(`execution_workspace_event`,e=>{t.syncExecutionWorkspaceSnapshot(e.snapshot),r?.onWorkspaceSnapshot(e.snapshot)}),this.bind(`history_cleared`,()=>t.clearHistory()),this.bind(`turn_source`,e=>r?.onTurnSource(e)),Vl(this.bind.bind(this),t),this.bind(`permission_request`,({id:t,toolName:i,toolArgs:a,canPersistProjectPermission:o,requesterDriverId:s,requester:c})=>{r?.onNeedsInput();let l=s?.startsWith(`peer:`)?n(s):void 0;this.options.requestPermission(i,a,t,o,l,c).then(n=>e.resolvePermission(t,n)).catch(()=>e.resolvePermission(t,!1))}),this.bind(`ask_request`,({id:t,request:n})=>{r?.onNeedsInput(),this.options.askUser(n,t).then(n=>e.resolveAsk(t,n)).catch(()=>e.resolveAsk(t,{type:`cancelled`}))}),this.bind(`prompt_resolved`,({id:e})=>this.options.dismissPrompt(e)),r?.wire()}unwire(){let{session:e}=this.options;this.options.attention?.unwire();for(let{event:t,handler:n}of this.bindings)e.off(t,n);this.bindings.length=0}bind(e,t){Hl(this.options.session,e,t,t=>{let n=this.options.onDeliveryError;n?n(t,e):this.options.manager.addSessionEventDeliveryError(t,e)},this.bindings)}};function Wl(e){return{cwd:e.cwd,...e.livePromptTrace?{livePromptTrace:e.livePromptTrace}:{},provider:e.provider,...e.providerErrorGuidance===void 0?{}:{providerErrorGuidance:e.providerErrorGuidance},...e.promptFileReferenceTag===void 0?{}:{promptFileReferenceTag:e.promptFileReferenceTag},...e.modelCommandToolPrefix===void 0?{}:{modelCommandToolPrefix:e.modelCommandToolPrefix},...e.subagentHookEnvironmentNames===void 0?{}:{subagentHookEnvironmentNames:e.subagentHookEnvironmentNames},...e.observerFailureWarningCode===void 0?{}:{observerFailureWarningCode:e.observerFailureWarningCode},...e.commandHookShell===void 0?{}:{commandHookShell:e.commandHookShell},...e.bare===!0?{bare:!0}:{},...e.skipConfiguredHooks===!0?{skipConfiguredHooks:!0}:{},...e.orgPolicy===void 0?{}:{orgPolicy:e.orgPolicy},...e.projectAccess===void 0?{}:{projectAccess:e.projectAccess},...e.projectSettingsPaths===void 0?{}:{projectSettingsPaths:e.projectSettingsPaths},...e.baselinePermissionAllow===void 0?{}:{baselinePermissionAllow:e.baselinePermissionAllow},...e.taskContext===void 0?{}:{taskContext:e.taskContext},...e.contributionSources===void 0?{}:{contributionSources:e.contributionSources},...e.skillRoots===void 0?{}:{skillRoots:e.skillRoots},...e.userSettingsSources===void 0?{}:{userSettingsSources:e.userSettingsSources},...e.environment===void 0?{}:{environment:e.environment},...e.resolveProviderCredential===void 0?{}:{resolveProviderCredential:e.resolveProviderCredential},...e.editCheckpointStore===void 0?{}:{editCheckpointStore:e.editCheckpointStore},...e.externalEventVerifierFactory===void 0?{}:{externalEventVerifierFactory:e.externalEventVerifierFactory},...e.externalEventGrantHistory===void 0?{}:{externalEventGrantHistory:e.externalEventGrantHistory},...e.model===void 0?{}:{model:e.model},...e.effort===void 0?{}:{effort:e.effort},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt},...e.responseFormat===void 0?{}:{responseFormat:e.responseFormat},...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},permissionMode:e.permissionMode,maxTurns:e.maxTurns,sessionStore:e.sessionStore,disableSessionLoops:e.disableSessionLoops,resolveDefaultLoopPrompt:e.resolveDefaultLoopPrompt,resumeSessionId:e.resumeSessionId,forkSession:e.forkSession,...e.workspaceMovedFrom===void 0?{}:{workspaceMovedFrom:e.workspaceMovedFrom},sessionName:e.sessionName,autoName:!0,backgroundTaskRunners:e.backgroundTaskRunners,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.agentDefinitions===void 0?{}:{agentDefinitions:e.agentDefinitions},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.pluginDirectories===void 0?{}:{pluginDirectories:e.pluginDirectories},...e.additionalTools===void 0?{}:{additionalTools:e.additionalTools},...e.defaultTools===void 0?{}:{defaultTools:e.defaultTools},...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},...e.sandboxClient===void 0?{}:{sandboxClient:e.sandboxClient},commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,...e.remoteCommandPolicy?{remoteCommandPolicy:e.remoteCommandPolicy}:{},language:e.language,agentName:e.agentName,activePresetId:e.activePresetId,persona:e.persona,systemPrompt:e.systemPrompt,appendSystemPrompt:e.appendSystemPrompt,allowedTools:e.allowedTools,deniedTools:e.deniedTools,enableParallelSubagents:e.enableParallelSubagents,selfVerification:e.selfVerification,terminalHandoff:e.terminalHandoff,...e.providerDefinitions?{providerDefinitions:e.providerDefinitions}:{},...e.memoryStore?{memoryStore:e.memoryStore}:{},...e.automaticMemory?{automaticMemory:e.automaticMemory}:{},...e.recallMemory?{recallMemory:e.recallMemory}:{},...e.promptHistory?{promptHistory:e.promptHistory}:{}}}function Gl(e,t){switch(t.event){case`plan_event`:return{id:e,event:t.event,message:`Plan ${t.payload.type.replaceAll(`_`,` `)}`};case`context_file_refreshed`:return{id:e,event:t.event,message:`Context refreshed: ${t.payload.filePath}`};case`branch_event`:return{id:e,event:t.event,message:`Branch ${t.payload.kind.replaceAll(`_`,` `)}: ${t.payload.branchId} @ ${t.payload.checkpointId}`}}}var Kl=class{sequence=0;notices=[];add(e){this.append(Gl(this.nextId(),e))}addDeliveryError(e,t){this.append({id:this.nextId(),event:`delivery-error`,message:`Session event delivery failed (${t}): ${e.message}`})}addAttentionRecap(e){this.append({id:this.nextId(),event:`attention-recap`,message:e})}nextId(){return this.sequence+=1,`session-event-${this.sequence}`}append(e){this.notices.push(e);let t=this.notices.length-50;t>0&&this.notices.splice(0,t)}};function ql(e,t){let n=null;return{schedule(){n||=setTimeout(()=>{n=null,e()},t)},flush(){n&&=(clearTimeout(n),null)}}}var Jl=class{history=[];localNotices=[];streamingText=``;activeTools=[];isThinking=!1;isAborting=!1;pendingPrompt=null;contextState={percentage:0,usedTokens:0,maxTokens:0};executionWorkspaceSnapshot=null;selectedExecutionEntryId;lastErrorMessage=null;isStalled=!1;sessionNoticeStore=new Kl;sessionEventNotices=this.sessionNoticeStore.notices;onChange=null;streamBuf=``;debouncedStreamNotify=ql(()=>this.notify(),300);stallTimer=null;armStallTimer(){this.clearStallTimer(),this.stallTimer=setTimeout(()=>{this.stallTimer=null,this.isStalled=!0,this.notify()},15e3)}clearStallTimer(){this.stallTimer&&=(clearTimeout(this.stallTimer),null),this.isStalled&&=!1}notify(){this.onChange?.()}onTextDelta=e=>{this.isThinking&&this.armStallTimer(),this.streamBuf+=e,this.streamingText=this.streamBuf,this.debouncedStreamNotify.schedule()};onToolStart=e=>{this.clearStallTimer(),this.activeTools=[...this.activeTools,e],this.notify()};onToolEnd=e=>{let t=e.executionId===void 0?this.activeTools.findLastIndex(t=>t.toolName===e.toolName&&t.isRunning):this.activeTools.findIndex(t=>t.executionId===e.executionId&&t.isRunning);if(t!==-1){let n=[...this.activeTools];n[t]=e,this.activeTools=n}this.isThinking&&!this.activeTools.some(e=>e.isRunning)&&this.armStallTimer(),this.notify()};onThinking=e=>{this.isThinking=e,e?(this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.lastErrorMessage=null,this.armStallTimer()):(this.isAborting=!1,this.activeTools=[],this.clearStallTimer()),this.notify()};onComplete=e=>{this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.contextState={percentage:e.contextState.usedPercentage,usedTokens:e.contextState.usedTokens,maxTokens:e.contextState.maxTokens},this.notify()};onInterrupted=()=>{this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onError=e=>{this.clearStallTimer(),this.lastErrorMessage=e?.message??`Unknown error`,this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onContextUpdate=e=>{this.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})};syncHistory(e){e.length!==0&&(this.history=this.withLocalNotices(e),this.notify())}syncHostHistory(e,t){this.history=[...this.withLocalNotices(e),...t],this.notify()}withLocalNotices(e){let t=[],n=0;for(let r of this.localNotices){let i=Math.min(r.afterSessionEntries,e.length);for(;n<i;)t.push(e[n++]);t.push(r.entry)}for(;n<e.length;)t.push(e[n++]);return t}addEntry(e){this.localNotices.push({entry:e,afterSessionEntries:this.history.length-this.localNotices.length}),this.history=[...this.history,e],this.notify()}addUserEcho(e){this.history=[...this.history,e],this.notify()}clearHistory(){this.history=[],this.localNotices=[],this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()}setPendingPrompt(e){this.pendingPrompt=e,this.notify()}setAborting(e){this.isAborting=e,this.notify()}setContextState(e){this.contextState=e,this.notify()}addSessionEventNotice(e){this.sessionNoticeStore.add(e),this.notify()}addAttentionRecap(e){this.sessionNoticeStore.addAttentionRecap(e),this.notify()}addSessionEventDeliveryError(e,t){this.sessionNoticeStore.addDeliveryError(e,t),this.notify()}syncExecutionWorkspaceSnapshot(e){let t=this.selectedExecutionEntryId,n=t!==void 0&&e.entries.some(e=>e.id===t)?t:e.selectedEntryId??e.entries[0]?.id;this.executionWorkspaceSnapshot={...e,...n?{selectedEntryId:n}:{}},this.selectedExecutionEntryId=n,this.notify()}selectExecutionWorkspaceEntry(e){this.executionWorkspaceSnapshot?.entries.some(t=>t.id===e)&&(this.selectedExecutionEntryId=e,this.executionWorkspaceSnapshot={...this.executionWorkspaceSnapshot,selectedEntryId:e},this.notify())}dispose(){this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.onChange=null}};function Yl(e){switch(e.kind){case`none`:return;case`several`:return e.message;case`stopped`:return`Loop ${e.loopId} stopped by Esc.`;case`failed`:return e.message}}const Xl=15e3;var Zl=class{stateManager;interactiveSession;registry;opts;submitHandler=null;userActions;permissions;eventProjector;attention;lifecycle;availableCommands=[];sessionName;initPoller=null;get terminalHandoffController(){return this.opts.terminalHandoff}onChange=null;constructor(e){this.opts=e,this.sessionName=e.sessionName,this.stateManager=new Jl,this.stateManager.onChange=()=>this.onChange?.(),this.userActions=new Rl(()=>this.onChange?.()),this.permissions=new zl(()=>this.onChange?.()),this.interactiveSession=this.createSession(),this.registry=this.createRegistry(),this.attention=this.createAttention(e.attention),this.eventProjector=new Ul({session:this.interactiveSession,manager:this.stateManager,...this.attention?{attention:this.attention}:{},requestPermission:(e,t,n,r,i,a)=>this.permissions.enqueue(e,t,n,r,i,a),askUser:(e,t)=>this.askUser(e,t),dismissPrompt:e=>this.dismissPromptById(e),...e.onSessionEventDeliveryError?{onDeliveryError:e.onSessionEventDeliveryError}:{}}),this.lifecycle=new Ll({start:()=>this.startRuntime(),stop:async()=>{this.eventProjector.unwire(),this.cancelAllPermissions(),this.cancelAllUserActions(),this.stopInitCheck(),this.onChange=null,this.stateManager.dispose(),await this.stopTransports()},beginShutdown:()=>{this.cancelAllUserActions(),this.cancelAllPermissions(),this.stateManager.addEntry(a(i(`Shutting down...`))),this.onChange?.()},shutdownSession:async({reason:e,message:t})=>{await this.interactiveSession.shutdown({reason:e,message:t})}},5e3)}async startRuntime(){let e=!1;try{this.eventProjector.wire(),this.syncRestoredHistory(),this.startInitCheck(),this.opts.transportRegistry&&(e=!0,await this.opts.bindTransports?.(this.interactiveSession),await this.opts.transportRegistry.startAll())}catch(t){if(this.eventProjector.unwire(),this.stopInitCheck(),e&&this.opts.transportRegistry)try{await this.stopTransports()}catch(e){throw new Il([t,...e instanceof AggregateError?e.errors:[e]],`TUI channel start failed and transport rollback also failed.`)}throw t}}async stopTransports(){if(!this.opts.transportRegistry)return;let e=await this.opts.transportRegistry.stopAll();if(e.errors.length>0)throw AggregateError(e.errors,`TUI transport teardown failed.`)}get permissionRequest(){return this.permissions.current}get pendingUserAction(){return this.userActions.current}get isShuttingDown(){return this.lifecycle.isShuttingDown}get isActiveForPeerStatus(){return this.lifecycle.isActiveForPeerStatus}createSession(){return y(Wl(this.opts))}createRegistry(){let e=new te;for(let t of this.opts.commandModules??[])e.addModule(t);return this.opts.reloadPluginCommandSource?.(e),e}onSubmit(e){this.submitHandler=e}setAvailableCommands(e){this.availableCommands=e,this.onChange?.()}setBusy(e){this.stateManager.onThinking(e)}async start(){await this.lifecycle.start()}async stop(){await this.lifecycle.stop()}getSession(){return this.interactiveSession}getRegistry(){return this.registry}subscribe(e){return this.onChange=e,()=>{this.onChange===e&&(this.onChange=null)}}getSnapshot(){let e=this.stateManager;return{history:e.history,streamingText:e.streamingText,activeTools:e.activeTools,isThinking:e.isThinking,isAborting:e.isAborting,lastErrorMessage:e.lastErrorMessage,isStalled:e.isStalled,sessionEventNotices:e.sessionEventNotices,isShuttingDown:this.isShuttingDown,pendingPrompt:e.pendingPrompt,pendingCount:this.interactiveSession.getPendingCount(),executionWorkspaceSnapshot:e.executionWorkspaceSnapshot,...e.selectedExecutionEntryId===void 0?{}:{selectedExecutionEntryId:e.selectedExecutionEntryId},permissionRequest:this.permissionRequest,pendingUserAction:this.pendingUserAction,contextState:e.contextState}}getCommandQueryPort(){return this.registry}getSessionUiEventPort(){return this.interactiveSession}getRuntimeStatusSnapshot(e){try{let e=this.interactiveSession.getSession(),t=e.getActivePresetId?.(),n=e.getModelEffort();return{permissionMode:e.getPermissionMode(),sessionId:e.getSessionId(),...t===void 0?{}:{activePresetId:t},...n===void 0?{}:{effort:n}}}catch{return{permissionMode:e,sessionId:``}}}addEntry(e){this.stateManager.addEntry(e)}abort(){this.stateManager.setAborting(!0),this.cancelAllUserActions(),this.cancelAllPermissions(),this.interactiveSession.abort()}cancelQueue(){this.interactiveSession.cancelQueue(),this.cancelAllUserActions(),this.cancelAllPermissions(),this.stateManager.setPendingPrompt(null)}async stopWaitingSelfPacedLoop(){let e=Yl(await this.interactiveSession.stopWaitingSelfPacedLoop(`Loop stopped by Esc`));e!==void 0&&this.addEntry(a(i(e)))}async shutdown(e){await this.lifecycle.shutdown(e)}selectExecutionWorkspaceEntry(e){this.stateManager.selectExecutionWorkspaceEntry(e)}async readExecutionWorkspaceDetail(e){return this.interactiveSession.readExecutionWorkspaceDetail(e)}async sendAgentJob(e,t){await this.interactiveSession.sendAgentJob(e,t)}setSessionName(e){this.sessionName=e,this.interactiveSession.setName(e),this.onChange?.()}async askUser(e,t){return this.userActions.enqueue(e,t)}resolveUserAction(e,t){this.userActions.resolveCurrent(e,t)}cancelAllUserActions(){this.userActions.cancelAll()}async handleInput(e){if(!e.startsWith(`/`)){await this.interactiveSession.submit(e),this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}await this.handleSlashCommand(e)}async handleSlashCommand(e){let{name:t,args:n}=Fl(e),r=await this.interactiveSession.executeCommand(t,n);if(r){if(r.data?.sessionExecution===!0){this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}Pl(r,this.interactiveSession,this.registry,this.stateManager,this.opts.reloadPluginCommandSource);return}this.stateManager.addEntry(a(i(`Unknown command "/${t}". Type /help for help.`)))}handlePermissionRequest(e,t,n){return this.permissions.enqueue(e,t,n)}dismissPromptById(e){this.userActions.dismissById(e),this.permissions.dismissById(e)}cancelAllPermissions(){this.permissions.cancelAll()}syncRestoredHistory(){if(this.stateManager.history.length===0){let e=this.interactiveSession.getFullHistory();e.length>0&&this.stateManager.syncHistory(e)}}startInitCheck(){this.stopInitCheck(),this.initPoller=Nl({check:()=>this.runInitCheck(),intervalMs:200,timeoutMs:Xl,onReady:()=>void 0,onFailure:e=>this.onInitFailure(e)}),this.initPoller.start()}runInitCheck(){let e=this.interactiveSession.getContextState(),t=this.interactiveSession.getName();t&&t!==this.sessionName&&(this.sessionName=t,this.onChange?.()),this.stateManager.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens});let n=this.interactiveSession.getFullHistory();n.length>0&&this.stateManager.syncHistory(n),this.syncExecutionWorkspace()}createAttention(e){if(e)return new jl({source:e,onRecap:e=>this.stateManager.addAttentionRecap(e)})}onInitFailure(e){let t=e.kind===`timeout`?`Session initialization timed out after ${Xl/on}s${e.lastError?` (last error: ${e.lastError.message})`:``}`:`Session initialization failed: ${e.error.message}`;this.stateManager.onError(),this.stateManager.addEntry({id:`session-init-error-${Date.now()}`,timestamp:new Date,category:`event`,type:`session-init-error`,data:{message:t}})}stopInitCheck(){this.initPoller?.stop(),this.initPoller=null}syncExecutionWorkspace(){try{this.stateManager.syncExecutionWorkspaceSnapshot(this.interactiveSession.getExecutionWorkspaceSnapshot({selectedEntryId:this.stateManager.selectedExecutionEntryId}))}catch{}}};function Ql(e,t){if(e.category!==`chat`||e.type!==`user`)return!1;let n=e.data;return typeof n==`object`&&!!n&&`content`in n&&n.content===t}var $l=class{options;known=[];read;followUp;echoes=[];constructor(e){this.options=e}get behind(){return this.read!==void 0||this.followUp!==void 0}readTail(){if(this.read!==void 0){this.followUp??=`tail`;return}this.start(!1)}reload(){if(this.read!==void 0){this.followUp=`reload`;return}this.start(!0)}restart(){this.read=void 0,this.followUp=void 0,this.start(!0)}reset(){this.known=[],this.read=void 0,this.followUp=void 0,this.echoes=[]}onPage(e){let t=this.read;if(t===void 0)return;if(e.startIndex!==t.next){e.total<t.next&&this.restart();return}if(t.entries.push(...this.options.revive(e.entries)),t.next+=e.entries.length,t.next<e.total&&e.entries.length>0){this.options.request(t.next)||(this.read=void 0);return}this.read=void 0,this.known=t.reload?t.entries:[...this.known,...t.entries];let n=this.followUp;this.followUp=void 0,n!==void 0&&this.start(n===`reload`),this.show()}echo(e,t){this.echoes.push({entry:e,content:t,after:this.known.length,shown:!1}),this.show()}start(e){let t=e?0:this.known.length;this.read={reload:e,entries:[],next:t},this.options.request(t)||(this.read=void 0)}show(){if(this.echoes=this.unrecordedEchoes(),!this.behind)for(let e of this.echoes)e.shown=!0;this.options.show(this.known,this.echoes.filter(e=>e.shown).map(e=>e.entry))}unrecordedEchoes(){let e=0;return this.echoes.filter(t=>{let n=Math.max(e,t.after),r=this.known.findIndex((e,r)=>r>=n&&Ql(e,t.content));return r===-1?!0:(e=r+1,!1)})}};const eu=`appearance-settings-patch`;function tu(e){return e instanceof Error?e.message:String(e)}function nu(e){return{result:{success:!1,message:e},uiIntents:[]}}function ru(e,t){return e?.commands.find(e=>e.name===t)}async function iu(e,t,n,r){let i=await e.execute(n,t);if(!i.success)return{result:i,uiIntents:[]};let a=[];for(let e of i.hostActions??[]){if(e.type!==eu)return nu(`Cannot apply '${e.type}' on this terminal.`);if(!u(e.patch))return nu(`Failed to apply '${eu}': invalid appearance settings patch`);a.push(e.patch)}for(let e of a)try{await r.writeAppearanceSettings(e)}catch(e){return nu(`Failed to apply '${eu}': ${tu(e)}`)}return{result:{message:i.message,success:i.success,...i.data===void 0?{}:{data:i.data}},uiIntents:i.uiIntents??[]}}function au(e){let t=new _(e.terminalHandoff),{cwd:n}=e;return{canHandoffTerminal:()=>t.canHandoffTerminal(),runWithTerminal:e=>t.runWithTerminal(e),getCwd:()=>n,getCommandInvocationSource:()=>`user`}}function ou(e,t){return e!==void 0&&e===t?T:e}function su(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cu(e,t){if(!su(e))return e;let n=e;typeof e.timestamp==`string`&&(n={...n,timestamp:new Date(e.timestamp)});let r=e.metadata;return t!==void 0&&su(r)&&r.driverId===t&&(n={...n,metadata:{...r,driverId:T}}),n}function lu(e,t){return e.map(e=>{let n=new Date(e.timestamp);if(e.category!==`chat`||e.data===void 0)return{...e,timestamp:n};let r=t!==void 0&&n.getTime()>=t.since?t.driverId:void 0;return{...e,timestamp:n,data:cu(e.data,r)}})}function uu(e){return{name:e.name,description:e.description,source:`builtin`,...e.displayName===void 0?{}:{displayName:e.displayName},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint}}}function du(e,t){return[...e.map(e=>({name:e.name,description:e.description,source:`builtin`,modelInvocable:e.modelInvocable,...e.displayName===void 0?{}:{displayName:e.displayName},...e.example===void 0?{}:{example:e.example},...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.subcommands!==void 0&&e.subcommands.length>0?{subcommands:e.subcommands.map(uu)}:{}})),...t.filter(e=>e.userInvocable).map(e=>({name:e.name,description:e.description,source:e.source,modelInvocable:e.modelInvocable,userInvocable:e.userInvocable,...e.argumentHint===void 0?{}:{argumentHint:e.argumentHint},...e.context===void 0?{}:{context:e.context},...e.agent===void 0?{}:{agent:e.agent}}))]}function fu(e,t){let n=t.toLowerCase();return e.find(e=>e.name.toLowerCase()===n&&e.subcommands!==void 0)?.subcommands??[]}function pu(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>e.name.toLowerCase().startsWith(n))}const mu=[`get-context`,`get-commands`,`get-status`,`get-executing`,`get-pending`,`get-execution-workspace`],hu=[...mu,`get-prompts`],gu=[`get-context`,`get-status`,`get-commands`],_u=new Set([`exit`,`quit`]),vu=new Set([`show-plugin-manager`,`show-settings`]);function yu(e){return e instanceof Error?e.message:String(e)}var bu=class{handlers={ui_intent:new Set,session_renamed:new Set};on(e,t){this.handlers[e].add(t)}off(e,t){this.handlers[e].delete(t)}emitUiIntent(e){for(let t of[...this.handlers.ui_intent])t(e)}emitSessionRenamed(e){for(let t of[...this.handlers.session_renamed])t(e)}},xu=class{options;sessionName;manager;userActions;permissions;attention;lifecycle;uiEvents=new bu;clientCommands;commandQueryPort={getCommands:e=>pu(this.commandCatalog,e),getSubcommands:e=>fu(this.commandCatalog,e)};readOnly;commandCatalog=[];status;pendingCount=0;hostSessions;sessionListSequence=0;sessionListRequestId;pendingPicker;hostHistory;own;pendingCommands=new Map;commandSequence=0;pendingDetails=new Map;detailSequence=0;pendingLoopStops=new Map;loopStopSequence=0;pendingTaskSends=new Map;pendingSessionChange;sessionChangeSequence=0;promptGeneration=0;shownPromptIds=new Set;settledPromptIds=new Set;transcriptGeneration=0;unsubscribers=[];detached=!1;ended=!1;onChange=null;constructor(e){this.options=e,this.sessionName=e.sessionName,this.readOnly=e.role===`observe`,this.manager=this.createManager(),this.clientCommands=e.clientCommands===void 0?void 0:{set:e.clientCommands,host:au({terminalHandoff:e.terminalHandoff,cwd:e.cwd})},this.hostHistory=new $l({request:e=>this.send(e===0?{type:`get-history`}:{type:`get-history`,fromIndex:e}),show:(e,t)=>this.manager.syncHostHistory(e,t),revive:e=>lu(e,this.own)}),this.userActions=new Rl(()=>this.notify()),this.permissions=new zl(()=>this.notify()),this.attention=e.attention?new jl({source:e.attention,onRecap:e=>this.manager.addAttentionRecap(e)}):void 0,this.lifecycle=new Ll({start:async()=>this.attach(),stop:async()=>{this.detach(),this.attention?.unwire(),this.onChange=null,this.manager.dispose()},beginShutdown:()=>{this.detach(),this.notice(`Detached. The session keeps running.`)},shutdownSession:async()=>void 0},0)}get terminalHandoffController(){return this.options.terminalHandoff}async start(){await this.lifecycle.start()}async stop(){await this.lifecycle.stop()}async shutdown(e){await this.lifecycle.shutdown(e)}subscribe(e){return this.onChange=e,()=>{this.onChange===e&&(this.onChange=null)}}getSnapshot(){let e=this.manager;return{history:e.history,streamingText:e.streamingText,activeTools:e.activeTools,isThinking:e.isThinking,isAborting:e.isAborting,lastErrorMessage:e.lastErrorMessage,isStalled:e.isStalled,sessionEventNotices:e.sessionEventNotices,isShuttingDown:this.lifecycle.isShuttingDown,pendingPrompt:e.pendingPrompt,pendingCount:e.pendingPrompt===null?0:Math.max(this.pendingCount,1),executionWorkspaceSnapshot:e.executionWorkspaceSnapshot,...e.selectedExecutionEntryId===void 0?{}:{selectedExecutionEntryId:e.selectedExecutionEntryId},permissionRequest:this.permissions.current,pendingUserAction:this.userActions.current,contextState:e.contextState,...this.hostSessions===void 0?{}:{hostSessions:this.hostSessions},transcriptGeneration:this.transcriptGeneration,...this.readOnly?{readOnly:!0}:{},attached:!0}}getCommandQueryPort(){return this.commandQueryPort}getSessionUiEventPort(){return this.uiEvents}getRuntimeStatusSnapshot(e){let t=this.status;return t===void 0?{permissionMode:e,sessionId:``}:{permissionMode:t.permissionMode,sessionId:t.sessionId,effort:t.effort,modelId:t.model}}addEntry(e){this.manager.addEntry(e)}async handleInput(e){if(!e.startsWith(`/`)){if(this.refuseReadOnly())return;this.send({type:`submit`,prompt:e});return}let{name:t,args:n}=Fl(e);if(_u.has(t)){this.end(`user`);return}let r=ru(this.clientCommands?.set,t);if(r!==void 0){await this.runClientCommand(r,n);return}if(this.refuseReadOnly())return;this.commandSequence+=1;let i=`wire-tui-command-${this.commandSequence}`;await new Promise(e=>{this.pendingCommands.set(i,e),this.send({type:`command`,name:t,args:n,requestId:i})||this.settleCommand(i)})}async runClientCommand(e,t){let n=this.clientCommands;if(n!==void 0)try{let{result:r,uiIntents:i}=await iu(e,t,n.host,n.set);for(let e of i)this.uiEvents.emitUiIntent({intent:e,requesterDriverId:T});this.notice(r.message)}catch(t){this.notice(`/${e.name} failed: ${yu(t)}`)}}abort(){this.refuseReadOnly()||(this.manager.setAborting(!0),this.userActions.cancelAll(),this.permissions.cancelAll(),this.send({type:`abort`}))}cancelQueue(){this.refuseReadOnly()||(this.send({type:`cancel-queue`}),this.userActions.cancelAll(),this.permissions.cancelAll(),this.pendingCount=0,this.manager.setPendingPrompt(null))}async stopWaitingSelfPacedLoop(){if(this.refuseReadOnly())return;this.loopStopSequence+=1;let e=`wire-tui-loop-stop-${this.loopStopSequence}`,t=await new Promise(t=>{this.pendingLoopStops.set(e,t),this.send({type:`stop-waiting-loop`,requestId:e})||this.settleLoopStop(e)}),n=t===void 0?void 0:Yl(t);n!==void 0&&this.notice(n)}selectExecutionWorkspaceEntry(e){this.manager.selectExecutionWorkspaceEntry(e)}async readExecutionWorkspaceDetail(e){this.detailSequence+=1;let t=`wire-tui-detail-${this.detailSequence}`;return new Promise((n,r)=>{this.pendingDetails.set(t,{resolve:n,reject:r}),this.send({type:`read-execution-detail`,requestId:t,entryId:e})||this.rejectDetail(t,`Could not reach the session.`)})}async sendAgentJob(e,t){if(this.refuseReadOnly())return;let n=await new Promise(n=>{let r=this.pendingTaskSends.get(e)??[];r.push(n),this.pendingTaskSends.set(e,r),this.send({type:`send-background-task`,taskId:e,input:{prompt:t}})||this.settleTaskSend(e)});n!==void 0&&this.notice(`Could not send to background task ${e}: ${n}`)}resolveUserAction(e,t){this.userActions.resolveCurrent(e,t)}async requestSessionSwitch(e){if(this.refuseReadOnly()||e===this.status?.sessionId)return;this.settleSessionChange(),this.sessionChangeSequence+=1;let t=`wire-tui-session-change-${this.sessionChangeSequence}`;await new Promise(n=>{this.pendingSessionChange={requestId:t,settle:n},this.send({type:`switch-session`,sessionId:e,requestId:t})||this.settleSessionChange()})}attach(){let{connection:e}=this.options;this.options.driverId!==void 0&&(this.own={driverId:this.options.driverId,since:Date.now()}),this.unsubscribers.push(e.subscribe(e=>this.onFrame(e)),e.onClose(()=>this.end(`closed`))),this.attention?.wire(),this.requestSnapshot()}onFrame(e){if(!this.detached)try{this.project(e)}catch(t){this.notice(`Could not show the session's ${e.type} update: ${yu(t)}`)}}project(e){let t=this.manager;switch(e.type){case`user_message`:{let t=ou(e.driverId,this.options.driverId)??null;this.hostHistory.echo(Bl(e.content,{getActiveDriverId:()=>t}),e.content);return}case`text_delta`:t.onTextDelta(e.delta);return;case`tool_start`:t.onToolStart(e.state);return;case`tool_end`:t.onToolEnd(e.state);return;case`thinking`:t.onThinking(e.isThinking),this.send({type:`get-pending`});return;case`executing`:e.executing!==t.isThinking&&t.onThinking(e.executing);return;case`complete`:t.onComplete(e.result),this.attention?.onComplete(),this.hostHistory.readTail();return;case`interrupted`:t.onInterrupted(),this.hostHistory.readTail();return;case`error`:t.onError(Error(e.message)),this.attention?.onError(),this.hostHistory.readTail();return;case`history`:this.hostHistory.onPage(e);return;case`history_changed`:this.hostHistory.reload();return;case`history_cleared`:t.clearHistory(),this.hostHistory.reset(),this.hostHistory.reload();return;case`context`:t.onContextUpdate(e.state);return;case`turn_source`:this.attention?.onTurnSource(e.source);return;case`pending`:this.pendingCount=e.pendingCount??(e.pending===null?0:1),t.setPendingPrompt(e.pending);return;case`execution_workspace_event`:t.syncExecutionWorkspaceSnapshot(e.snapshot),this.attention?.onWorkspaceSnapshot(e.snapshot);return;case`plan_event`:t.addSessionEventNotice({event:`plan_event`,payload:e.event});return;case`context_file_refreshed`:t.addSessionEventNotice({event:`context_file_refreshed`,payload:e.event});return;case`branch_event`:t.addSessionEventNotice({event:`branch_event`,payload:e.event});return;default:this.projectSessionFrame(e)}}projectSessionFrame(e){switch(e.type){case`permission_request`:this.askPermission(e.event);return;case`ask_request`:this.askUser(e.event);return;case`prompt_resolved`:this.dismissPrompt(e.event.id);return;case`ui_intent`:this.showUiIntent(e.event);return;case`session_renamed`:this.rename(e.event.name);return;case`session_status`:this.applyStatus(e.status);return;case`commands`:this.commandCatalog=du(e.commands,e.skills),this.notify();return;case`command_result`:this.showCommandResult(e);return;case`sessions`:if(e.requestId!==this.sessionListRequestId)return;this.hostSessions=e.listing.sessions,this.notify(),this.openPendingPicker();return;case`sessions_error`:if(e.requestId!==this.sessionListRequestId)return;this.pendingPicker!==void 0&&(this.pendingPicker=void 0,this.notice(e.message));return;case`session_switched`:this.settleSessionChange(),this.followSessionSwitch(e.event.sessionId);return;case`session_change_failed`:(e.requestId===void 0||e.requestId===this.pendingSessionChange?.requestId)&&this.settleSessionChange(),this.notice(e.message);return;case`protocol_error`:e.requestId===void 0?this.settleSessionChange():this.settleCommand(e.requestId),this.notice(e.message);return;case`resume_gap`:this.hostHistory.restart(),this.requestState();return;default:this.projectReply(e)}}projectReply(e){switch(e.type){case`execution_detail`:{let t=this.pendingDetails.get(e.requestId);this.pendingDetails.delete(e.requestId),t?.resolve(e.page);return}case`execution_detail_error`:this.rejectDetail(e.requestId,e.message);return;case`waiting_loop_stop`:this.settleLoopStop(e.requestId,e.outcome);return;case`background_task_control_result`:if(e.action!==`send`)return;this.settleTaskSend(e.taskId,e.success?void 0:e.message??`refused`);return;default:return}}showsPrompt(e){return this.shownPromptIds.has(e)?!0:(this.shownPromptIds.add(e),!1)}askPermission(e){if(this.showsPrompt(e.id))return;this.attention?.onNeedsInput();let t=e.requesterDriverId?.startsWith(`peer:`)?n(e.requesterDriverId):void 0,r=this.promptGeneration;this.permissions.enqueue(e.toolName,e.toolArgs,e.id,e.canPersistProjectPermission,t,e.requester).then(t=>this.answer(r,e.id,{type:`permission-response`,id:e.id,result:t}))}askUser(e){if(this.showsPrompt(e.id))return;this.attention?.onNeedsInput();let t=this.promptGeneration;this.userActions.enqueue(e.request,e.id).then(n=>this.answer(t,e.id,{type:`ask-response`,id:e.id,response:n}))}answer(e,t,n){e===this.promptGeneration&&(this.shownPromptIds.delete(t),!this.settledPromptIds.delete(t)&&this.send(n))}dismissPrompt(e){this.settledPromptIds.add(e);let t=this.userActions.dismissById(e),n=this.permissions.dismissById(e);!t&&!n&&this.settledPromptIds.delete(e)}showUiIntent(e){if(e.requesterDriverId===void 0){this.uiEvents.emitUiIntent(e);return}if(vu.has(e.intent.type)){this.notice(`That screen is not available while attached to a daemon.`);return}let t={...e,requesterDriverId:T};if(e.intent.type===`show-session-picker`){this.pendingPicker=t,this.requestSessionList()||(this.pendingPicker=void 0);return}this.uiEvents.emitUiIntent(t)}openPendingPicker(){let e=this.pendingPicker;e!==void 0&&(this.pendingPicker=void 0,this.uiEvents.emitUiIntent(e))}rename(e){this.sessionName=e,this.uiEvents.emitSessionRenamed({name:e}),this.notify()}applyStatus(e){this.status=e,this.manager.onContextUpdate(e.context);let t=e.sessionName??(e.sessionId===``?void 0:is(e.sessionId));t!==void 0&&t!==this.sessionName&&this.rename(t)}showCommandResult(e){for(let e of gu)this.send({type:e});e.data?.sessionExecution===!0?this.send({type:`get-pending`}):this.notice(e.message),e.requestId!==void 0&&this.settleCommand(e.requestId)}settleCommand(e){let t=this.pendingCommands.get(e);this.pendingCommands.delete(e),t?.()}rejectDetail(e,t){let n=this.pendingDetails.get(e);this.pendingDetails.delete(e),n?.reject(Error(t))}settleLoopStop(e,t){let n=this.pendingLoopStops.get(e);this.pendingLoopStops.delete(e),n?.(t)}settleTaskSend(e,t){let n=this.pendingTaskSends.get(e),r=n?.shift();n!==void 0&&n.length===0&&this.pendingTaskSends.delete(e),r?.(t)}refuseReadOnly(){return this.readOnly&&this.notice(`Read only: this terminal observes the session and cannot change it. /exit detaches.`),this.readOnly}settleSessionChange(){let e=this.pendingSessionChange;this.pendingSessionChange=void 0,e?.settle()}followSessionSwitch(e){this.promptGeneration+=1,this.userActions.cancelAll(),this.permissions.cancelAll(),this.shownPromptIds.clear(),this.settledPromptIds.clear(),this.status=void 0,this.pendingCount=0,this.hostHistory.reset(),this.manager.dispose(),this.manager=this.createManager(),this.transcriptGeneration+=1,this.notice(`Switched to session ${e}.`),this.rename(is(e)),this.requestSnapshot()}requestSnapshot(){this.hostHistory.reload(),this.requestState()}requestState(){for(let e of this.readOnly?mu:hu)this.send({type:e});this.requestSessionList()}requestSessionList(){this.sessionListSequence+=1;let e=`wire-tui-sessions-${this.sessionListSequence}`;return this.sessionListRequestId=e,this.send({type:`list-sessions`,requestId:e})}send(e){if(this.detached||this.readOnly&&!Ze(e.type))return!1;try{return this.options.connection.send(e),!0}catch(e){return this.notice(`Could not reach the session: ${yu(e)}`),!1}}end(e){this.ended||(this.ended=!0,this.detach(),this.notice(e===`closed`?`The connection to the session closed.`:`Detached. The session keeps running.`),this.options.onEnd?.(e))}detach(){if(this.detached)return;this.detached=!0,this.pendingPicker=void 0;for(let e of this.unsubscribers.splice(0))e();this.userActions.cancelAll(),this.permissions.cancelAll();let e=[...this.pendingCommands.values()];this.pendingCommands.clear();for(let t of e)t();this.settleSessionChange();for(let e of[...this.pendingDetails.keys()])this.rejectDetail(e,`Detached from the session.`);for(let e of[...this.pendingLoopStops.keys()])this.settleLoopStop(e);let t=[...this.pendingTaskSends.values()].flat();this.pendingTaskSends.clear();for(let e of t)e()}createManager(){let e=new Jl;return e.onChange=()=>this.notify(),e}notice(e){this.manager.addEntry(a(i(e)))}notify(){this.onChange?.()}};function Su(e,t){return{cwd:e.cwd,...e.livePromptTrace?{livePromptTrace:e.livePromptTrace}:{},provider:e.provider,...e.providerErrorGuidance===void 0?{}:{providerErrorGuidance:e.providerErrorGuidance},...e.promptFileReferenceTag===void 0?{}:{promptFileReferenceTag:e.promptFileReferenceTag},...e.modelCommandToolPrefix===void 0?{}:{modelCommandToolPrefix:e.modelCommandToolPrefix},...e.subagentHookEnvironmentNames===void 0?{}:{subagentHookEnvironmentNames:e.subagentHookEnvironmentNames},...e.observerFailureWarningCode===void 0?{}:{observerFailureWarningCode:e.observerFailureWarningCode},...e.commandHookShell===void 0?{}:{commandHookShell:e.commandHookShell},...e.bare===!0?{bare:!0}:{},...e.skipConfiguredHooks===!0?{skipConfiguredHooks:!0}:{},...e.projectAccess===void 0?{}:{projectAccess:e.projectAccess},...e.projectSettingsPaths===void 0?{}:{projectSettingsPaths:e.projectSettingsPaths},...e.baselinePermissionAllow===void 0?{}:{baselinePermissionAllow:e.baselinePermissionAllow},...e.taskContext===void 0?{}:{taskContext:e.taskContext},...e.contributionSources===void 0?{}:{contributionSources:e.contributionSources},...e.skillRoots===void 0?{}:{skillRoots:e.skillRoots},...e.userSettingsSources===void 0?{}:{userSettingsSources:e.userSettingsSources},...e.environment===void 0?{}:{environment:e.environment},...e.resolveProviderCredential===void 0?{}:{resolveProviderCredential:e.resolveProviderCredential},...e.orgPolicy===void 0?{}:{orgPolicy:e.orgPolicy},...e.externalEventVerifierFactory===void 0?{}:{externalEventVerifierFactory:e.externalEventVerifierFactory},...e.externalEventGrantHistory===void 0?{}:{externalEventGrantHistory:e.externalEventGrantHistory},...e.providerDefinitions?{providerDefinitions:e.providerDefinitions}:{},...e.modelId===void 0?{}:{model:e.modelId},...e.effort===void 0?{}:{effort:e.effort},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt},...e.appendSystemPrompt===void 0?{}:{appendSystemPrompt:e.appendSystemPrompt},...e.responseFormat===void 0?{}:{responseFormat:e.responseFormat},...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},permissionMode:e.permissionMode,maxTurns:e.maxTurns,allowedTools:e.allowedTools,deniedTools:e.deniedTools,sessionStore:e.sessionStore,disableSessionLoops:e.disableSessionLoops,resolveDefaultLoopPrompt:e.resolveDefaultLoopPrompt,resumeSessionId:t,forkSession:e.forkSession,sessionName:e.sessionName,backgroundTaskRunners:e.backgroundTaskRunners,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.agentDefinitions===void 0?{}:{agentDefinitions:e.agentDefinitions},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.pluginDirectories===void 0?{}:{pluginDirectories:e.pluginDirectories},...e.additionalTools===void 0?{}:{additionalTools:e.additionalTools},...e.defaultTools===void 0?{}:{defaultTools:e.defaultTools},...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},...e.sandboxClient===void 0?{}:{sandboxClient:e.sandboxClient},commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,remoteCommandPolicy:e.remoteCommandPolicy,transportRegistry:e.transportRegistry,bindTransports:e.bindTransports,language:e.language,reloadPluginCommandSource:e.reloadPluginCommandSource,agentName:e.agentName,activePresetId:e.activePresetId,persona:e.persona,enableParallelSubagents:e.enableParallelSubagents,selfVerification:e.selfVerification,...e.memoryStore?{memoryStore:e.memoryStore}:{},...e.automaticMemory?{automaticMemory:e.automaticMemory}:{},...e.recallMemory?{recallMemory:e.recallMemory}:{},...e.screenReader===void 0?{}:{screenReader:e.screenReader},promptHistory:e.promptHistory}}async function Cu(e,t){let n;try{await e()}catch(e){n=e instanceof Error?e:Error(String(e))}let r;try{await t()?.stop()}catch(e){r=e instanceof Error?e:Error(String(e))}if(n!==void 0&&r!==void 0)throw AggregateError([n,r],`TUI render and teardown both failed.`);if(n!==void 0)throw n;if(r!==void 0)throw r}async function wu(e){try{await e.keybindingsSource?.start(),await Du(e,t=>({createChannel:Eu(e,t)}))}finally{e.keybindingsSource?.dispose()}}async function Tu(e){let t=`user`,n=()=>void 0,r=new Promise(e=>{n=e});try{await e.keybindingsSource?.start(),await Du(e,i=>{let a;return{createChannel:()=>a??=new xu({connection:e.connection,driverId:e.driverId,sessionName:e.sessionLabel,role:e.mode??`drive`,terminalHandoff:i.terminalHandoff,attention:i.attention,...e.clientCommands===void 0?{clientCommands:void 0}:{clientCommands:e.clientCommands,cwd:e.cwd},onEnd:e=>{t=e,n()}}),requestSessionSwitch:async e=>a?.requestSessionSwitch(e),ended:r}})}finally{e.keybindingsSource?.dispose()}return t}function Eu(e,t){let n=e.workspaceMovedFrom;return r=>{let i=n;n=void 0;let a=new Zl({...Su(e,r),...e.createEditCheckpointStore===void 0?{}:{editCheckpointStore:e.createEditCheckpointStore()},...i===void 0?{}:{workspaceMovedFrom:i},terminalHandoff:t.terminalHandoff,attention:t.attention});return e.onChannelReady?.(a),a}}async function Du(e,t){let n=e.screenReader===!0;e.announce!==!1&&pl({enabled:n,channel:e.screenReaderChannel,hint:e.screenReaderHint});let r=gl({enabled:n,overrides:e.screenReaderPacing}),i=n&&r.preparkMs>0?Sl({stdout:process.stdout,preparkMs:r.preparkMs}):void 0;ut()||(D.level=0);let a=new Tl,o=pt({override:e.focusReporting}),s=wl({supported:()=>o}),c=new ll({focusReporting:o,now:Date.now});a.setTerminalModeHooks({preSuspend:async()=>{s.disable(),await i?.drain()},postResume:()=>s.enable()});let l=t({terminalHandoff:a,attention:c}),u,d=e=>(u=l.createChannel(e),u);await vl(r.startupQuietMs,process.stdin);let f=new dl(process.stdin,{negotiated:()=>s.negotiated,onFocusIn:()=>c.focusIn(),onFocusOut:()=>c.focusOut(),onKeystroke:()=>c.keystroke()});process.stdin.resume(),s.enable(),c.start();let p=i===void 0?void 0:Cl(i),m=V(Ja,{name:e.productDisplayName,modelCommandToolPrefix:e.modelCommandToolPrefix,children:V(vr,{source:e.keybindingsSource,children:V(lt,{enabled:n,children:V(ci,{overrides:e.terminalCapabilities,children:V(cl,{cwd:e.cwd,createChannel:d,...l.requestSessionSwitch===void 0?{}:{requestSessionSwitch:l.requestSessionSwitch},providerOverride:e.providerOverride,providerType:e.providerType,modelId:e.modelId,permissionMode:e.permissionMode,version:e.version,sessionStore:e.sessionStore,resumeSessionId:e.resumeSessionId,showSessionPickerOnStart:e.showSessionPickerOnStart,initialInput:e.initialInput,initialInputOrigin:e.initialInputOrigin,startupUpdateNotice:e.startupUpdateNotice,transportRegistry:e.transportRegistry,pluginAdapter:e.commandHostAdapters?.plugin,cliAdapter:e.cliAdapter,promptHistorySource:e.promptHistorySource,promptHistoryProject:e.promptHistoryProject,themeRegistry:e.themeRegistry,reducedMotion:e.reducedMotion,reducedMotionOverride:e.reducedMotionOverride})})})})}),h=Ce(p===void 0?m:V(ai,{port:p,children:m}),{exitOnCtrlC:!1,isScreenReaderEnabled:n,stdin:f.asInkStdin(),...i===void 0?{}:{stdout:i.asInkStdout()}});a.setInkInstance(h),l.ended?.then(()=>h.unmount());try{await Cu(()=>h.waitUntilExit(),()=>u)}finally{await i?.flush(),a.setTerminalModeHooks(void 0),s.disable(),c.dispose(),f.detach(),process.stdin.pause()}}const Ou={drive:`drive (send prompts, answer its questions)`,observe:`observe (read only)`},ku=[`needs-input`,`working`,`idle`,`unknown`,`unverified`,`dead`];function Au(e,t,n){if(e.length<=t)return e;let r=Math.max(1,t-1),i=n===void 0?`check workspace trust in the terminal`:`see ${n}`;return[...e.slice(0,r),`… ${e.length-r} more — ${i}`]}function $(e){return e?.liveness===`alive`&&e.control===`available`&&e.generation!==void 0}function ju(e){return e.liveness===`dead`?`dead`:$(e)?e.activity:`unverified`}function Mu(e){return[...e].sort((e,t)=>ku.indexOf(ju(e))-ku.indexOf(ju(t))||e.id.localeCompare(t.id))}function Nu(e){return[...e].sort((e,t)=>(e.cwd===void 0)-+(t.cwd===void 0)||(e.cwd??``).localeCompare(t.cwd??``)||ku.indexOf(ju(e))-ku.indexOf(ju(t))||e.id.localeCompare(t.id))}function Pu(e,t,n){if(e===`/`)return e;let r=0;for(let n of t){if(n===e)continue;let t=0;for(;t<e.length&&t<n.length&&e[e.length-t-1]===n[n.length-t-1];)t++;r=Math.max(r,t)}let i=e.split(/[\\/]/u).filter(Boolean).at(-1)?.length??e.length,a=Math.min(e.length,Math.max(i,r+3)),o=e.length-a,s=Math.max(e.lastIndexOf(`/`,o-1),e.lastIndexOf(`\\`,o-1)),c=e.slice(s+1);return je(Iu(c))<=n?c:e.slice(o)}function Fu(e){return Array.from(e,e=>/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(e)?`\\u{${e.codePointAt(0).toString(16)}}`:e)}function Iu(e){return Fu(e).join(``)}function Lu(e,t){let n=Fu(e);if(je(n.join(``))<=t)return n.join(``);let r=Math.ceil((t-1)/2),i=t-r-1,a=``;for(let e of n){if(je(a)+je(e)>r)break;a+=e}let o=``;for(let e of[...n].reverse()){if(je(o)+je(e)>i)break;o=e+o}return`${a}…${o}`}function Ru(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r!==void 0&&e.id===r.id&&e.liveness===r.liveness&&e.control===r.control&&e.activity===r.activity&&e.problem===r.problem&&e.nextLoopAt===r.nextLoopAt&&e.name===r.name&&e.cwd===r.cwd&&e.pr?.url===r.pr?.url&&e.generation===r.generation})}function zu(e,t){let n=Date.parse(e)-t;return Number.isFinite(n)?n<=0?`loop eligible now`:n<6e4?`loop eligible in <1m`:`loop eligible in ${Math.ceil(n/6e4)}m`:``}function Bu({loadRows:e,onStop:t,onStart:n,startTrustQuestion:r,trustStatusCommand:i,onOpenPr:a,onAttach:o,filteredByCwd:s=!1,filteredByName:c=!1,filteredByPr:l=!1,stateFilter:u,refreshMs:d=2e3,initialSelectedId:f,initialGroupByDirectory:p=!1}){let{exit:m}=we(),{stdout:h}=Oe(),g=Math.max(12,h.columns??80),_=K(),[v,ee]=z([]),[y,te]=z(Date.now),[b,ne]=z(`loading`),[re,ie]=z(f),[ae,oe]=z(!1),[se,ce]=z(p),[x,le]=z(),S=x?.id,[ue,de]=z(`idle`),[C,w]=z(`idle`),[fe,T]=z(),pe=R(!1),[me,he]=z(`idle`),[ge,_e]=z(),[E,ve]=z(),ye=R(!1),[D,be]=z(`idle`),xe=R(!1),O=R(!0),Se=e=>{n!==void 0&&(ye.current=!0,he(`starting`),Promise.resolve().then(()=>n(e)).then(e=>{O.current&&(_e(e),he(`started`))}).catch(()=>{O.current&&he(`failed`)}).finally(()=>{ye.current=!1}))},A=L(()=>{let e=v.filter(e=>u===void 0||ju(e)===u);return se?Nu(e):Mu(e)},[v,u,se]),Ce=L(()=>{let e=[],t=[...new Set(A.map(e=>e.cwd).filter(e=>e!==void 0))],n,r=0;return A.forEach((i,a)=>{let o=se?i.cwd??`unverified`:ju(i);if(o!==n){let n=se?i.cwd===void 0?`Directory: unverified`:(()=>{let e=`Dir ${++r}: `,n=Math.max(4,g-e.length),a=Lu(Pu(i.cwd,t,n),n),o=`${e}${a} — ${Iu(i.cwd)}`;return _||je(o)<=g?o:`${e}${a}`})():`${o}:`;e.push({kind:`group`,label:n})}e.push({kind:`row`,row:i,index:a}),n=o}),e},[A,se,g,_]);I(()=>{let t=new AbortController,n=!0,r,i=async()=>{try{let r=Mu(await e(t.signal));if(!n||t.signal.aborted)return;let i=Date.now();ee(e=>Ru(e,r)?e:r),te(e=>r.some(t=>t.nextLoopAt!==void 0&&zu(t.nextLoopAt,e)!==zu(t.nextLoopAt,i))?i:e),ne(`ready`)}catch{n&&!t.signal.aborted&&ne(`unavailable`)}finally{n&&!t.signal.aborted&&(r=setTimeout(()=>{i()},d))}};return i(),()=>{n=!1,r!==void 0&&clearTimeout(r),t.abort()}},[e,d]),I(()=>(O.current=!0,()=>{O.current=!1}),[]);let j=re!==void 0&&A.some(e=>e.id===re)?re:A[0]?.id;I(()=>{ie(e=>A.length===0||e!==void 0&&A.some(t=>t.id===e)?e:A[0]?.id)},[A]),Ee((e,i)=>{if(!pe.current&&!(xe.current&&e!==`q`&&!(!_&&i.escape)&&!(i.ctrl&&e===`c`))&&!(ye.current&&e!==`q`&&!(!_&&i.escape)&&!(i.ctrl&&e===`c`))){if(E!==void 0){e===`y`||e===`r`?(ve(void 0),Se(e===`y`?`trust`:`restricted`)):(e===`n`||i.escape)&&ve(void 0);return}if(S!==void 0){if(e===`n`||i.escape){le(void 0);return}if(e===`y`&&x?.action===`attach`){let e=x,t=A.find(t=>t.id===e.id);if(le(void 0),b!==`ready`||!$(t)||t.generation!==e.generation||e.mode===void 0||o===void 0){de(`unavailable`);return}o({id:e.id,generation:e.generation,mode:e.mode,groupByDirectory:se}),m();return}if(e===`y`){let e=x,n=A.find(t=>t.id===e?.id);if(le(void 0),b!==`ready`||e===void 0||!$(n)||n.generation!==e.generation||t===void 0){w(`unavailable`);return}pe.current=!0,w(`stopping`),t(e.id,e.generation).then(()=>{O.current&&(T(e.id),w(`stopped`))}).catch(()=>{O.current&&w(`failed`)}).finally(()=>{pe.current=!1})}return}if(e===`q`||!_&&i.escape||i.ctrl&&e===`c`){m();return}if(e===`?`){oe(e=>!e);return}if(e===`g`){Te.clear(),ce(e=>!e);return}if(e===`n`&&n!==void 0){if(r===void 0){Se();return}ye.current=!0,r().then(e=>{ye.current=!1,O.current&&(e===void 0?Se():ve(e))}).catch(()=>{ye.current=!1,O.current&&he(`failed`)});return}if((e===`a`||e===`p`)&&o!==void 0){let t=A.find(e=>e.id===j);b!==`ready`||!$(t)?de(`unavailable`):(de(`idle`),w(`idle`),le({id:t.id,generation:t.generation,action:`attach`,mode:e===`a`?`drive`:`observe`}));return}if(e===`o`&&a!==void 0){let e=A.find(e=>e.id===j);if(b!==`ready`||!$(e)||!e.pr){be(`unavailable`);return}xe.current=!0,be(`opening`),a(e.id,e.pr.url,e.generation).then(()=>{O.current&&be(`opened`)}).catch(()=>{O.current&&be(`failed`)}).finally(()=>{xe.current=!1});return}if(e===`s`&&t!==void 0){let e=A.find(e=>e.id===j);b!==`ready`||!$(e)?w(`unavailable`):(w(`idle`),de(`idle`),le({id:e.id,generation:e.generation,action:`stop`}));return}if(!(_||A.length===0)&&(i.upArrow||i.downArrow)){let e=Math.max(0,A.findIndex(e=>e.id===j)),t=Math.max(0,Math.min(A.length-1,e+(i.downArrow?1:-1)));ie(A[t]?.id)}}});let Te=Gn({enabled:_&&S===void 0&&E===void 0&&C!==`stopping`,itemCount:A.length,cancellable:!0,repeatable:!0,onSelect:e=>{ie(A[e]?.id),w(`idle`)},onCancel:()=>{pe.current||m()}}),De=A.find(e=>e.id===j),ke=b===`ready`&&$(De)?De.name:void 0,M=b===`ready`&&$(De)&&De.activity===`idle`&&De.nextLoopAt?zu(De.nextLoopAt,y):``,N=b===`ready`&&$(De)?De.pr:void 0,P=Math.max(8,h.rows??24),F=[`Keys:`,_?`Number+Enter Select`:`↑/↓ Select`,`s Request stop`,`g Group state/dir`,...n===void 0?[]:[`n New session`],...o===void 0?[]:[`a Attach (drive)`,`p Peek (read only)`],...a===void 0?[]:[`o Open linked PR`],`y Confirm`,`n/Esc Cancel`,`q/Esc/Ctrl+C Close`,`? Toggle help`,`Activity ≠ liveness`,`Idle ≠ attach-ready`,`Close keeps sessions`],Ae=ae&&S===void 0&&C!==`stopping`,Me=2+(u===void 0?0:1)+ +(b===`loading`||b===`unavailable`||b===`ready`&&A.length===0)+(j===void 0?0:1)+(ke===void 0?0:1)+(N===void 0?0:2)+ +!!M+(D===`idle`?0:1)+(me===`idle`?0:1)+(E===void 0?0:1)+(S===void 0?C===`idle`?0:1:_?1:2)+ +(S===void 0&&ue!==`idle`)+1+(Ae?F.length:0)+2,Ne=Math.max(1,P-Me),Pe=Math.max(0,Ce.findIndex(e=>e.kind===`row`&&e.row.id===j)),Fe=Math.min(Math.max(0,Pe-Math.floor(Ne/2)),Math.max(0,Ce.length-Ne)),Ie=_?Ce:Ce.slice(Fe,Fe+Ne),Le=E===void 0?[]:Au([`Not trusted: ${E.folder}`,`Trusting it loads the project's own settings, hooks, plugins, skills and MCP servers:`,...E.loads],_?1/0:Ne,i),U=_?{}:{wrap:`truncate-end`},Re=o!==void 0&&b===`ready`&&$(De),ze=C===`stopping`?`Stop in progress; wait for result.`:E===void 0?S===void 0?_?`Type a number and Enter to select; s Stop;${Re?` a Attach; p Peek;`:``}${n?` n New;`:``}${a?` o Open PR;`:``} g Group; Escape to close; ? Help.`:`↑↓ Navigate s Stop${Re?` a Attach p Peek`:``}${n?` n New`:``}${a?` o Open PR`:``} g Group ? Help q/Esc Close`:`Confirm ${x?.action===`attach`?`attach`:`stop`} or cancel before closing.`:`Answer the trust question or cancel before closing.`,Be=e=>x?.action===`attach`&&x.mode!==void 0?`${x.mode===`drive`?`Attach to`:`Peek at`} ${e} to ${Ou[x.mode]}?`:`Stop ${e}?`;return H(k,{flexDirection:`column`,..._?{}:{height:P},children:[H(G,{...U,children:[s?`Background sessions in selected directory`:`Background sessions across projects`,c?` · name filter active`:``,l?` · PR filter active`:``]}),H(G,{...U,children:[A.length,` supervised session(s). Foreground peers and saved records are separate.`]}),u!==void 0&&H(G,{...U,children:[`State: `,u]}),b===`loading`&&V(G,{...U,children:`Loading supervised sessions...`}),b===`unavailable`&&V(G,{...U,children:`Supervised session discovery unavailable; last verified rows remain below.`}),b===`ready`&&A.length===0&&V(G,{...U,children:`No supervised sessions.`}),Le.map((e,t)=>V(G,{...U,children:e},`trust-${t}`)),E===void 0&&Fe>0&&!_&&H(G,{children:[Fe,` more above`]}),(E===void 0?Ie:[]).map(e=>e.kind===`group`?V(G,{...U,children:e.label},`group-${e.label}`):H(G,{..._?{}:{wrap:`truncate-end`},children:[_?xr(e.index):e.row.id===j?`> `:` `,e.row.name&&$(e.row)?_?`${e.row.name} (${e.row.id})`:`${Array.from(e.row.name).slice(0,24).join(``)}${Array.from(e.row.name).length>24?`…`:``} [${e.row.id.slice(-8)}]`:e.row.id,` `,`activity `,e.row.activity,` liveness `,e.row.liveness,` control `,e.row.control,b===`ready`&&$(e.row)&&e.row.activity===`idle`&&e.row.nextLoopAt?` ${zu(e.row.nextLoopAt,y)}`:``,e.row.problem?` ${e.row.problem}`:``,b===`ready`&&$(e.row)&&e.row.pr?` ${e.row.pr.host} ${e.row.pr.kind===`pull`?`#`:`!`}${e.row.pr.number}`:``]},`row-${e.row.id}`)),E===void 0&&!_&&Fe+Ie.length<Ce.length&&H(G,{children:[Ce.length-Fe-Ie.length,` more below`]}),j!==void 0&&H(G,{...U,children:[`Selected `,j]}),ke!==void 0&&H(G,{...U,children:[`Name: `,ke]}),N!==void 0&&H(G,{...U,children:[`PR: `,N.host,` `,N.kind===`pull`?`#`:`!`,N.number]}),N!==void 0&&H(G,{...U,children:[`URL: `,N.url]}),M&&V(G,{...U,children:M}),D===`opening`&&V(G,{...U,children:`Opening linked PR...`}),D===`opened`&&V(G,{...U,children:`Opened linked PR.`}),D===`failed`&&V(G,{...U,children:`PR link changed or could not be opened.`}),D===`unavailable`&&V(G,{...U,children:`No verified PR link is available.`}),me===`starting`&&V(G,{...U,children:`Starting a background session...`}),me===`started`&&H(G,{...U,children:[`Started `,ge,c||u!==void 0?` (may be hidden by filter)`:``]}),me===`failed`&&V(G,{...U,children:`Start failed; check workspace trust or run session start --background for details.`}),E!==void 0&&V(G,{...U,children:`y Trust and start / r Start Restricted / n Cancel`}),S!==void 0&&(_?H(G,{children:[Be(S),` y Yes / n No`]}):H(B,{children:[V(G,{...U,children:Be(`…${S.slice(-8)}`)}),V(G,{...U,children:`y Yes / n No`})]})),S===void 0&&C===`unavailable`&&V(G,{...U,children:`This session cannot be stopped from the view.`}),S===void 0&&ue===`unavailable`&&V(G,{...U,children:`This session cannot be attached to from the view.`}),C===`stopping`&&V(G,{...U,children:`Stopping selected session; wait for confirmation.`}),C===`stopped`&&H(G,{...U,children:[`Stopped `,fe]}),C===`failed`&&V(G,{...U,children:`Stop failed; session remains listed until verified otherwise.`}),_&&A.length>0&&S===void 0&&C!==`stopping`&&H(G,{children:[br(A.length,!0),Te.buffer?` ${Te.buffer}`:``]}),_&&Te.invalid&&V(G,{children:`Selection out of range.`}),V(G,{...U,children:ze}),Ae&&F.map(e=>V(G,{...U,children:e},e))]})}async function Vu(e){e.announce!==!1&&pl({enabled:e.screenReader,channel:e.screenReaderChannel,hint:e.screenReaderHint});let t;process.stdin.resume();let n=Ce(V(lt,{enabled:e.screenReader,children:V(Bu,{loadRows:e.loadRows,onStop:e.onStop,onStart:e.onStart,startTrustQuestion:e.startTrustQuestion,onOpenPr:e.onOpenPr,onAttach:e=>{t=e},filteredByCwd:e.filteredByCwd,filteredByName:e.filteredByName,filteredByPr:e.filteredByPr,stateFilter:e.stateFilter,refreshMs:e.refreshMs,...e.initialSelectedId===void 0?{}:{initialSelectedId:e.initialSelectedId},...e.initialGroupByDirectory===void 0?{}:{initialGroupByDirectory:e.initialGroupByDirectory}})}),{isScreenReaderEnabled:e.screenReader,exitOnCtrlC:!1});try{await n.waitUntilExit()}finally{n.unmount()}return t===void 0?{kind:`closed`}:{kind:`attach`,...t}}function Hu({providerDefinitions:t,reloadPluginCommandSource:n,userSettingsPath:r,settingsSources:i,formatResumeCommand:a}){return{getUserSettingsPath:()=>r,readSettings:e=>g(e),reloadPluginCommandSource:e=>{n(e)},applyActiveModelChange:(e,t,n)=>(c(i,[ee(`user`,r)],t,n),{applied:!0}),getGitBranch:e=>w(e),getProviderDisplayName:n=>e(t,n)?.displayName??n,...a===void 0?{}:{formatResumeCommand:a}}}function Uu(e){return{...e===void 0?{}:{$schema:e},version:1,bindings:{}}}function Wu(e,t){let n=ur(JSON.stringify(Uu(t)),e);if(!n.ok)throw Error(n.diagnostic.message);return n.snapshot}var Gu=class{filePath;#e;#t;#n=new Set;#r;#i;#a;#o;#s=!1;constructor(e){if(e.filePath.trim()===``)throw Error(`Keybindings file path must not be empty.`);if(e.schemaUrl?.trim()===``)throw Error(`Keybindings schema URL must not be empty.`);this.filePath=e.filePath,this.#e=e.schemaUrl,this.#t=e.onDiagnostic,this.#r=Wu(this.filePath,this.#e)}start(){return this.#s?Promise.reject(Error(`Keybindings source is disposed.`)):(this.#o===void 0&&(this.#o=this.#c().catch(e=>{throw this.#i?.close(),this.#i=void 0,this.#o=void 0,e})),this.#o)}async#c(){let e=he(this.filePath);if(await _e(e,{recursive:!0}),await this.#u(),this.#s)throw Error(`Keybindings source is disposed.`);this.#i=pe(e,{persistent:!1},(e,t)=>{(t===null||t.toString()===me(this.filePath))&&this.#l()})}isStarted(){return this.#i!==void 0&&!this.#s}getSnapshot(){return this.#r}subscribe(e){return this.#n.add(e),()=>this.#n.delete(e)}async ensureFile(){await _e(he(this.filePath),{recursive:!0});try{await ve(this.filePath,`${JSON.stringify(Uu(this.#e),null,2)}\n`,{encoding:`utf8`,flag:`wx`,mode:384})}catch(e){if(!qu(e))throw e}return this.filePath}dispose(){this.#s=!0,this.#a!==void 0&&clearTimeout(this.#a),this.#a=void 0,this.#i?.close(),this.#i=void 0,this.#n.clear()}#l(){this.#s||(this.#a!==void 0&&clearTimeout(this.#a),this.#a=setTimeout(()=>{this.#a=void 0,this.#u()},10))}async#u(){let e;try{e=await E(this.filePath,`utf8`)}catch(e){if(Ku(e))return;this.#d({file:this.filePath,path:`$`,message:Yu(e)});return}let t=ur(e,this.filePath);if(!t.ok){this.#d(t.diagnostic);return}this.#f(Object.freeze({...t.snapshot,generation:this.#r.generation+1}))}#d(e){this.#t?.(e),this.#f(Object.freeze({...this.#r,generation:this.#r.generation+1,diagnostic:e}))}#f(e){if(!this.#s){this.#r=e;for(let t of this.#n)t(e)}}};function Ku(e){return Ju(e)&&e.code===`ENOENT`}function qu(e){return Ju(e)&&e.code===`EEXIST`}function Ju(e){return e instanceof Error&&`code`in e}function Yu(e){return e instanceof Error?e.message:String(e)}function Xu(e){return new Gu(e)}function Zu(e){if(e===`1`)return!0;if(e===`0`)return!1}function Qu(e){if(e.flag!==void 0)return{reducedMotion:e.flag,override:`flag`};let t=Zu(e.env);return t===void 0?{reducedMotion:e.settings}:{reducedMotion:t,override:`environment`}}function $u(e,t,n){let r=ce(e??{}),i=Qu({settings:r.reducedMotion,flag:t,env:n.PRODUCT_REDUCED_MOTION});return{appearance:r,reducedMotion:i.reducedMotion,...i.override===void 0?{}:{reducedMotionOverride:i.override}}}const ed=RegExp(`^[A-Za-z0-9._-]{1,24}$`,`u`);function td(e,t,n){return e.listDirectory(t,n).filter(e=>e.kind===`file`&&e.name.endsWith(`.json`)).map(r=>({fileName:r.name,text:e.readText(ge(t,r.name),n)}))}function nd(e,t){let n=`load ${t.source} themes`,r=l(t.root);for(let i of td(r,t.directory,n)){let n=i.fileName.slice(0,-5);if(!ed.test(n)){let n=Ut(i.fileName);e.skipped.push({id:`${t.idPrefix}${n}`,fileName:Wt(i.fileName),reason:`$: the file name ${n} cannot be a theme id — use at most 24 characters from letters, digits, dot, dash and underscore`});continue}let r=`${t.idPrefix}${n}`;if(e.claimed.has(r)){e.skipped.push({id:r,fileName:i.fileName,reason:`$: the id "${r}" is already taken by a theme loaded earlier`});continue}if(i.text===void 0){e.skipped.push({id:r,fileName:i.fileName,reason:`$: the file could not be read`});continue}let a=rn({id:r,fileName:i.fileName,source:t.source,text:i.text});a.ok?(e.claimed.add(r),e.themes.push(a.theme)):e.skipped.push({id:r,fileName:i.fileName,reason:a.error})}}function rd(e,t,n,r){let i=oe(e,t,r);try{return f(i,{settingsPath:ae(t)}).map(e=>({name:e.manifest.name,pluginDir:e.pluginDir}))}catch(e){let t=Gt(i.join(`, `)),r=Gt(e instanceof Error?e.message:String(e));return n.skipped.push({id:`custom:<plugins>`,fileName:t,reason:`$: the plugin scopes could not be read — ${r}`}),[]}}function id(e){let t={themes:[],skipped:[],claimed:new Set};nd(t,{root:e.productRuntime.layout.userRoot,directory:`themes`,source:`user`,idPrefix:`custom:`});let n=e.plugins??rd(e.cwd,e.productRuntime,t,e.projectAccess);for(let e of n){if(!ed.test(e.name)){let n=Ut(e.name);t.skipped.push({id:`custom:${n}`,fileName:Wt(e.name),reason:`$: the plugin name ${n} cannot be part of a theme id — its themes are not loaded`});continue}nd(t,{root:e.pluginDir,directory:`themes`,source:`plugin`,idPrefix:`custom:${e.name}:`})}return{themes:t.themes,skipped:t.skipped}}function ad(e){let t=$u(e.settings,e.reducedMotionFlag,e.env),n={reducedMotion:t.reducedMotion,...t.reducedMotionOverride===void 0?{}:{reducedMotionOverride:t.reducedMotionOverride}};if(!e.enabled)return{registry:void 0,cataloguePort:void 0,skipped:[],...n};let r=id({cwd:e.cwd,productRuntime:e.productRuntime,userHome:e.userHome,...e.projectAccess===void 0?{}:{projectAccess:e.projectAccess}}),i=Gc([...ot(),...r.themes],r.skipped);return{registry:i,cataloguePort:Jc({registry:i,readAppearance:()=>$u(g(ae(e.productRuntime)),void 0,{}).appearance,...t.reducedMotionOverride===void 0?{}:{reducedMotionPin:{tier:t.reducedMotionOverride,reducedMotion:t.reducedMotion}}}),skipped:r.skipped,...n}}async function od(e={}){let t=x(e);ne(t);let n={...e,productRuntime:t};return fe(ie(process.argv))?(le(t.environment),re(ue(t)),new Promise(()=>void 0)):S(n,p,{renderApp:wu,renderSupervisedSessionView:Vu,renderAttachedApp:Tu,createDefaultTuiCliAdapter:Hu,createNodeKeybindingsSource:Xu,createThemeSurface:ad,installTuiProcessGuards:Ve,setLiveChannel:ze})}async function sd(e={}){try{let t=x(e);de(t.config.identity.cliName),Ge(t.config.identity.cliName),await od({...e,productRuntime:t})}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),fe(ie(process.argv))?process.exitCode=1:process.exit(1)}}sd();export{};
|