@robota-sdk/agent-cli 3.0.0-beta.86 → 3.0.0-beta.88

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +103 -48
  2. package/README.md +289 -39
  3. package/bin/{robota.cjs → agent.cjs} +1 -1
  4. package/dist/node/bin.js +23 -23
  5. package/dist/node/{bounded-output-Bgx2Cgkx-28em7iHq.js → bounded-output-BdWv9SX3-28em7iHq.js} +1 -1
  6. package/dist/node/{bounded-output-Bgx2Cgkx-28em7iHq.js.map → bounded-output-BdWv9SX3-28em7iHq.js.map} +1 -1
  7. package/dist/node/cli-core-CEWWF4d6.js +2917 -0
  8. package/dist/node/{command-executor-d6DdfUTD-DhFSDHvb.js → command-executor-D_UBZHxh-CVZipoOV.js} +2 -2
  9. package/dist/node/{command-executor-d6DdfUTD-DhFSDHvb.js.map → command-executor-D_UBZHxh-CVZipoOV.js.map} +1 -1
  10. package/dist/node/{command-executor-d6DdfUTD-3KEnsTnN.js → command-executor-D_UBZHxh-D7UrdAlN.js} +1 -1
  11. package/dist/node/headless.js +2 -2
  12. package/dist/node/index.d.ts +2423 -166
  13. package/dist/node/index.d.ts.map +1 -1
  14. package/dist/node/index.js +610 -580
  15. package/dist/node/index.js.map +1 -1
  16. package/dist/node/{node-BfqR16CD.js → node-BIdvEvlf.js} +1 -1
  17. package/dist/node/node-BUERQysz.js +15 -0
  18. package/dist/node/node-BWNobqRD.js +15 -0
  19. package/dist/node/node-BWNobqRD.js.map +1 -0
  20. package/dist/node/node-C4_FOvnk.js.map +1 -1
  21. package/dist/node/node-CEI_VczS.js +165 -0
  22. package/dist/node/node-CrspydTR.js +165 -0
  23. package/dist/node/node-CrspydTR.js.map +1 -0
  24. package/dist/node/node-DENLEmMT.js.map +1 -1
  25. package/dist/web/assets/index-BSxTg2Py.css +1 -0
  26. package/dist/web/assets/index-BpCxNRj_.js +309 -0
  27. package/dist/web/index.html +3 -3
  28. package/package.json +49 -44
  29. package/dist/node/cli-core-DOdGt9XE.js +0 -2891
  30. package/dist/node/node-B48couEE.js +0 -14
  31. package/dist/node/node-B48couEE.js.map +0 -1
  32. package/dist/node/node-CgLYctGm.js +0 -67
  33. package/dist/node/node-CgLYctGm.js.map +0 -1
  34. package/dist/node/node-DAOCaE6N.js +0 -67
  35. package/dist/node/node-DlLm_kxn.js +0 -14
  36. package/dist/web/assets/index-DSLs7oij.js +0 -309
  37. package/dist/web/assets/index-OqCBtMJ2.css +0 -1
  38. /package/dist/node/{bounded-output-Bgx2Cgkx-C4ucXwLR.js → bounded-output-BdWv9SX3-C4ucXwLR.js} +0 -0
package/dist/node/bin.js CHANGED
@@ -1,40 +1,40 @@
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{B as e,Et as t,F as n,Q as r,dt as i,nt as a,x as o,yt as s}from"./node-DlLm_kxn.js";import{A as c,C as l,D as u,E as d,F as f,O as p,P as m,S as h,T as g,_,b as ee,d as te,f as v,g as y,h as b,j as ne,k as re,l as ie,m as ae,o as oe,p as se,s as x,t as ce,u as S,v as le,w as ue,x as C,y as de}from"./cli-core-DOdGt9XE.js";import{watch as fe}from"node:fs";import{basename as pe,dirname as w,join as me}from"node:path";import{mkdir as he,readFile as ge,writeFile as _e}from"node:fs/promises";import T,{Chalk as ve,backgroundColorNames as E,foregroundColorNames as ye}from"chalk";import{Box as D,Static as be,Text as xe,render as O,useApp as Se,useBoxMetrics as Ce,useCursor as k,useInput as we,usePaste as Te,useStdout as Ee,useWindowSize as A}from"ink";import j,{createContext as M,useCallback as N,useContext as P,useEffect as F,useLayoutEffect as De,useMemo as I,useRef as L,useState as R}from"react";import{Fragment as z,jsx as B,jsxs as V}from"react/jsx-runtime";import Oe from"string-width";import{marked as ke}from"marked";import Ae from"marked-terminal";import{Readable as je}from"node:stream";const Me=e=>typeof e==`string`,Ne=e=>t=>t===void 0||e(t),Pe={user:!0,"agent-wakeup":!0,peer:!0,external:!0},H={driverId:Ne(Me)};({...H}),{...H},{...H},{...H},{...H},{...H},{...H},{...H},{...H},Object.keys(Pe);const Fe=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 Ie(e){return Fe.has(e)}const U=new Set([` `,`
4
- `]),Le=/\r\n/g,Re=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?|\x9d[^\x07\x1b\x9c]*(?:\x07|\x9c|\x1b\\)?|\x1b[P^_X][\s\S]*?(?:\x1b\\|\x07)|\x1b[P^_X][\s\S]*$|[\x90\x98\x9e\x9f][\s\S]*?(?:\x9c|\x1b\\|\x07)|[\x90\x98\x9e\x9f][\s\S]*$|\x1b\[[0-?]*[ -/]*[@-~]|\x9b[0-?]*[ -/]*[@-~]|\x1b[@-Z\\-_]|[\x00-\x1f\x7f]|[\x80-\x9f]/g;function W(e){return e.replace(Le,`
5
- `).replace(Re,e=>U.has(e)?e:``)}function ze(e){return typeof e==`string`?W(e):typeof e==`number`||typeof e==`boolean`||e==null?e:Array.isArray(e)?e.map(e=>ze(e)):e}function G(e){let{children:t,...n}=e;return B(xe,{...n,children:ze(t)})}function Be(e){return B(xe,{...e})}const Ve={id:`dark`,name:`Dark`,appearance:`dark`,source:`built-in`,colors:{text:{accent:`cyan`,emphasis:`white`,success:`green`,warning:`yellow`,error:`red`,session:`magenta`,muted:`gray`,onAccent:`black`},border:{attention:`yellow`,focused:`cyan`,active:`green`,muted:`gray`,error:`red`},status:{running:`yellow`,success:`green`,error:`red`,denied:`yellowBright`,waiting:`yellow`,cancelled:`yellow`,idle:`gray`}},markdown:{heading:`green`,firstHeading:`magenta`,code:`yellow`,codespan:`yellow`,link:`blue`,href:`blue`,blockquote:`gray`,del:`gray`,html:`gray`,diffAdded:`ansi256(120)`,diffRemoved:`ansi256(210)`,diffAddedBackground:`ansi256(22)`,diffRemovedBackground:`ansi256(52)`,diffHunk:`cyan`},syntax:{keyword:`blue`,built_in:`cyan`,type:`cyan`,literal:`blue`,number:`green`,regexp:`red`,string:`red`,class:`blue`,function:`yellow`,comment:`green`,doctag:`green`,meta:`gray`,tag:`gray`,name:`blue`,attr:`cyan`,addition:`green`,deletion:`red`},motion:{wave:[`#555555`,`#777777`,`#999999`,`#bbbbbb`]}},He=[Ve,{id:`light`,name:`Light`,appearance:`light`,source:`built-in`,colors:{text:{accent:`ansi256(24)`,emphasis:`black`,success:`ansi256(28)`,warning:`ansi256(130)`,error:`ansi256(124)`,session:`ansi256(90)`,muted:`ansi256(243)`,onAccent:`white`},border:{attention:`ansi256(130)`,focused:`ansi256(24)`,active:`ansi256(28)`,muted:`ansi256(249)`,error:`ansi256(124)`},status:{running:`ansi256(130)`,success:`ansi256(28)`,error:`ansi256(124)`,denied:`ansi256(166)`,waiting:`ansi256(130)`,cancelled:`ansi256(130)`,idle:`ansi256(243)`}},markdown:{heading:`ansi256(28)`,firstHeading:`ansi256(90)`,code:`ansi256(94)`,codespan:`ansi256(94)`,link:`ansi256(26)`,href:`ansi256(26)`,blockquote:`ansi256(243)`,del:`ansi256(243)`,html:`ansi256(243)`,diffAdded:`ansi256(22)`,diffRemoved:`ansi256(52)`,diffAddedBackground:`ansi256(194)`,diffRemovedBackground:`ansi256(224)`,diffHunk:`ansi256(24)`},syntax:{keyword:`ansi256(26)`,built_in:`ansi256(24)`,type:`ansi256(24)`,literal:`ansi256(26)`,number:`ansi256(28)`,regexp:`ansi256(124)`,string:`ansi256(124)`,class:`ansi256(26)`,function:`ansi256(94)`,comment:`ansi256(28)`,doctag:`ansi256(28)`,meta:`ansi256(243)`,tag:`ansi256(243)`,name:`ansi256(26)`,attr:`ansi256(24)`,addition:`ansi256(22)`,deletion:`ansi256(52)`},motion:{wave:[`#bbbbbb`,`#999999`,`#777777`,`#555555`]}},{id:`dark-daltonized`,name:`Dark (daltonized)`,appearance:`dark`,source:`built-in`,colors:{text:{accent:`#56b4e9`,emphasis:`#ffffff`,success:`#56b4e9`,warning:`#e69f00`,error:`#d55e00`,session:`#cc79a7`,muted:`#999999`,onAccent:`#000000`},border:{attention:`#e69f00`,focused:`#56b4e9`,active:`#56b4e9`,muted:`#999999`,error:`#d55e00`},status:{running:`#e69f00`,success:`#56b4e9`,error:`#d55e00`,denied:`#f0e442`,waiting:`#e69f00`,cancelled:`#cc79a7`,idle:`#999999`}},markdown:{heading:`#56b4e9`,firstHeading:`#cc79a7`,code:`#e69f00`,codespan:`#e69f00`,link:`#56b4e9`,href:`#56b4e9`,blockquote:`#999999`,del:`#999999`,html:`#999999`,diffAdded:`#8ecdf5`,diffRemoved:`#ffb066`,diffAddedBackground:`#00335c`,diffRemovedBackground:`#5c3000`,diffHunk:`#56b4e9`},syntax:{keyword:`#56b4e9`,built_in:`#8ecdf5`,type:`#8ecdf5`,literal:`#56b4e9`,number:`#e69f00`,regexp:`#d55e00`,string:`#d55e00`,class:`#56b4e9`,function:`#f0e442`,comment:`#999999`,doctag:`#999999`,meta:`#999999`,tag:`#999999`,name:`#56b4e9`,attr:`#8ecdf5`,addition:`#8ecdf5`,deletion:`#ffb066`},motion:{wave:[`#3d3d3d`,`#5c5c5c`,`#7a7a7a`,`#999999`]}},{id:`light-daltonized`,name:`Light (daltonized)`,appearance:`light`,source:`built-in`,colors:{text:{accent:`#0072b2`,emphasis:`#000000`,success:`#0072b2`,warning:`#b35900`,error:`#8c3d00`,session:`#a8477f`,muted:`#5c5c5c`,onAccent:`#ffffff`},border:{attention:`#b35900`,focused:`#0072b2`,active:`#0072b2`,muted:`#a3a3a3`,error:`#8c3d00`},status:{running:`#b35900`,success:`#0072b2`,error:`#8c3d00`,denied:`#8a7500`,waiting:`#b35900`,cancelled:`#a8477f`,idle:`#5c5c5c`}},markdown:{heading:`#0072b2`,firstHeading:`#a8477f`,code:`#8a5a00`,codespan:`#8a5a00`,link:`#0072b2`,href:`#0072b2`,blockquote:`#5c5c5c`,del:`#5c5c5c`,html:`#5c5c5c`,diffAdded:`#004c77`,diffRemoved:`#7a3300`,diffAddedBackground:`#d6ecf9`,diffRemovedBackground:`#fbe5cd`,diffHunk:`#0072b2`},syntax:{keyword:`#0072b2`,built_in:`#004c77`,type:`#004c77`,literal:`#0072b2`,number:`#b35900`,regexp:`#8c3d00`,string:`#8c3d00`,class:`#0072b2`,function:`#8a7500`,comment:`#5c5c5c`,doctag:`#5c5c5c`,meta:`#5c5c5c`,tag:`#5c5c5c`,name:`#0072b2`,attr:`#004c77`,addition:`#004c77`,deletion:`#7a3300`},motion:{wave:[`#c7c7c7`,`#a3a3a3`,`#7a7a7a`,`#5c5c5c`]}}],Ue=Ve.id;function We(){return He}function Ge(e){return e??Ve}const Ke=M(!1);function qe({enabled:e,children:t}){return B(Ke.Provider,{value:e,children:t})}function K(){return P(Ke)}function Je(){if(`NO_COLOR`in process.env)return!1;let e=process.env.FORCE_COLOR;return e===`0`?!1:e!==void 0&&e!==``||!!process.stdout.isTTY}function Ye(e={}){return e.override===!0?!0:e.override===!1||process.env.TERM_PROGRAM===`Apple_Terminal`?!1:!!process.stdout.isTTY}function Xe(e={}){return e.override===!0?!0:e.override===!1||process.env.TERM_PROGRAM===`WezTerm`?!1:!!process.stdout.isTTY}function Ze(e={}){return e.override===!0||e.override!==!1&&!!process.stdin.isTTY&&!!process.stdout.isTTY}const Qe=M(Ve),$e=M(!1),et=M(!0);function tt({theme:e,reducedMotion:t=!1,syntaxHighlighting:n=!0,children:r}){return B(Qe.Provider,{value:Ge(e),children:B($e.Provider,{value:t,children:B(et.Provider,{value:n,children:r})})})}function nt(){return P(Qe)}function q(){return nt().colors}function rt(){return nt().motion}function it(){let e=K(),t=P($e);return Je()&&!e&&!t}function at(){return P(et)}const ot=[`keyword`,`built_in`,`type`,`literal`,`number`,`regexp`,`string`,`class`,`function`,`comment`,`doctag`,`meta`,`tag`,`name`,`attr`,`addition`,`deletion`],st=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/iu,ct=/^ansi256\((\d{1,3})\)$/iu,lt=/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/iu,ut=`<chalk name> | #rgb | #rrggbb | ansi256(n) | rgb(r,g,b)`,dt=new Map([...ye,...E].map(e=>[e,T[e]])),ft=new Set(ye);function pt(e){return ft.has(e)}function mt(e){if(st.test(e))return!0;let t=ct.exec(e);if(t)return Number(t[1])<=255;let n=lt.exec(e);return n?n.slice(1).every(e=>Number(e)<=255):pt(e)}function ht(e){throw Error(`Theme colour ${JSON.stringify(e)} is not in Ink's colour grammar (${ut}).`)}function J(e,t=T){if(st.test(e))return t.hex(e);let n=ct.exec(e);if(n)return t.ansi256(Number(n[1]));let r=lt.exec(e);if(r)return t.rgb(Number(r[1]),Number(r[2]),Number(r[3]));let i=pt(e)?dt.get(e):void 0;return i===void 0&&ht(e),Reflect.get(t,e)??i}function gt(e,t=T){if(st.test(e))return t.bgHex(e);let n=ct.exec(e);if(n)return t.bgAnsi256(Number(n[1]));let r=lt.exec(e);if(r)return t.bgRgb(Number(r[1]),Number(r[2]),Number(r[3]));let i=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;return Reflect.get(t,i)??ht(e)}const _t=new ve({level:3});function vt(){return T.level===0?_t:T}function yt(e){return{heading:J(e.heading).bold,firstHeading:J(e.firstHeading).underline.bold,code:J(e.code),codespan:J(e.codespan),link:J(e.link),href:J(e.href).underline,blockquote:J(e.blockquote).italic,del:J(e.del,T.dim).strikethrough,html:J(e.html)}}function bt(e){let t={};for(let n of ot)t[n]=n===`type`?J(e[n]).dim:J(e[n]);return t}function xt(e){let{markdown:t}=e,n=vt(),r=gt(t.diffAddedBackground,n),i=J(t.diffAdded,n),a=gt(t.diffRemovedBackground,n),o=J(t.diffRemoved,n);return{added:e=>r(i(e)),removed:e=>a(o(e)),hunk:J(t.diffHunk,n),meta:e=>n.dim(e)}}function St(e){return e.split(/\s+/u).map(Number)}St(`0 95 135 175 215 255`),St(`0.1121 0.8853 -0.0005`),St(`0.1127 0.8897 -0.0001`),St(`0.0045 0.0 1.0019`),St(`0.292 0.7054 -0.0003`),St(`0.2934 0.7089 0.0`),St(`-0.0209 0.4614 0.5677`),St(`0.4124 0.3576 0.1805`),St(`0.2126 0.7152 0.0722`),St(`0.0193 0.1192 0.9505`),St(`0.95047 1 1.08883`);function Ct(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const wt=new Set([`name`,`base`,`overrides`]),Tt=/[\u0000-\u001F\u007F-\u009F]/u,Et=new RegExp(Tt.source,`gu`);function Dt(e){return JSON.stringify(e).replace(Et,e=>`\\u${(e.codePointAt(0)??0).toString(16).padStart(4,`0`)}`)}function Ot(e){return Dt(e).slice(1,-1)}function kt(e){return W(e).replaceAll(`
6
- `,` `).replaceAll(` `,` `).trim()}function At(e){return Tt.test(e)?Dt(e):e}function jt(e){return{ok:!1,error:e}}function Mt(e,t){return typeof e==`string`?mt(e)?{ok:!0,value:e}:{ok:!1,error:`${t}: ${Dt(e)} is not a colour in Ink's grammar (${ut})`}:{ok:!1,error:`${t}: expected a colour string`}}function Nt(e,t,n){if(!Array.isArray(t)||t.length!==e.length)return{ok:!1,error:`${n}: expected exactly ${e.length} colours`};let r=[];for(let[i,a]of e.entries()){let e=Ft(a,t[i]??null,`${n}[${i}]`);if(!e.ok)return e;r.push(e.value)}return{ok:!0,value:r}}function Pt(e,t,n){if(!Ct(t))return{ok:!1,error:`${n}: expected an object of tokens`};let r={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(e,i))return{ok:!1,error:`${n}.${At(i)} is not a theme token`};let a=Ft(e[i]??null,t[i]??null,`${n}.${At(i)}`);if(!a.ok)return a;r[i]=a.value}return{ok:!0,value:r}}function Ft(e,t,n){return typeof e==`string`?Mt(t,n):Array.isArray(e)?Nt(e,t,n):Ct(e)?Pt(e,t,n):{ok:!1,error:`${n} is not a theme token`}}function It(e){return JSON.parse(JSON.stringify(e))}function Lt(e){return JSON.parse(JSON.stringify({colors:e.colors,markdown:e.markdown,syntax:e.syntax,motion:e.motion}))}function Rt(e){let t;try{t=JSON.parse(e)}catch(e){return{ok:!1,error:`$: ${e instanceof Error?kt(e.message):`invalid JSON`}`}}if(!Ct(t))return{ok:!1,error:`$: expected an object`};for(let e of Object.keys(t))if(!wt.has(e))return{ok:!1,error:`$.${At(e)} is not a theme token`};return{ok:!0,value:t}}function zt(e,t){let n=e.name;return n===void 0?Tt.test(t)?{ok:!1,error:`$.name: the minted id must not contain control characters`}:t.length>60?{ok:!1,error:`$.name: the minted id must be at most 60 characters`}:{ok:!0,value:t}:typeof n!=`string`||n.trim().length===0?{ok:!1,error:`$.name: expected a non-empty string`}:Tt.test(n)?{ok:!1,error:`$.name: must not contain control characters`}:n.length>60?{ok:!1,error:`$.name: must be at most 60 characters`}:{ok:!0,value:n}}function Bt(e){let t=e.base===void 0?Ue:e.base;if(typeof t!=`string`)return{ok:!1,error:`$.base: expected a built-in theme id`};let n=He.find(e=>e.id===t);return n?{ok:!0,theme:n}:{ok:!1,error:`$.base: ${Dt(t)} is not a built-in theme`}}function Vt(e){let t=Rt(e.text);if(!t.ok)return jt(t.error);let n=t.value,r=Bt(n);if(!r.ok)return jt(r.error);let i=zt(n,e.id);if(!i.ok)return jt(i.error);let a=n.overrides===void 0?{}:n.overrides,o=Ft(Lt(r.theme),a,`$.overrides`);if(!o.ok)return jt(o.error);let{colors:s,markdown:c,syntax:l,motion:u}=It(o.value);return{ok:!0,theme:{id:e.id,name:i.value,appearance:r.theme.appearance,source:e.source,colors:s,markdown:c,syntax:l,motion:u}}}function Ht({version:e}){return V(D,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[B(G,{color:q().text.accent,bold:!0,children:`
3
+ import{Bt as e,J as t,Pt as n,dt as r,f as i,ht as a,n as o,xt as s}from"./node-BUERQysz.js";import{A as c,C as l,D as u,E as d,I as f,L as p,M as m,N as h,O as g,S as _,T as ee,_ as te,b as v,d as ne,f as y,g as re,h as ie,j as ae,k as oe,l as se,m as ce,o as le,p as b,s as ue,t as x,u as de,v as fe,w as S,x as C,y as pe}from"./cli-core-CEWWF4d6.js";import{watch as me}from"node:fs";import{basename as he,dirname as ge,join as _e}from"node:path";import{mkdir as ve,readFile as ye,writeFile as w}from"node:fs/promises";import{Readable as be}from"node:stream";import T,{Chalk as xe,backgroundColorNames as Se,foregroundColorNames as Ce}from"chalk";import{Box as E,Static as D,Text as we,render as O,useApp as Te,useBoxMetrics as Ee,useCursor as k,useInput as De,usePaste as Oe,useStdout as ke,useWindowSize as A}from"ink";import j,{createContext as M,useCallback as N,useContext as P,useEffect as F,useLayoutEffect as Ae,useMemo as I,useRef as L,useState as R}from"react";import{Fragment as z,jsx as B,jsxs as V}from"react/jsx-runtime";import je from"string-width";import{marked as Me}from"marked";import Ne from"marked-terminal";const Pe=e=>typeof e==`string`,Fe=e=>t=>t===void 0||e(t),Ie={user:!0,"agent-wakeup":!0,peer:!0,external:!0},H={driverId:Fe(Pe)};({...H}),{...H},{...H},{...H},{...H},{...H},{...H},{...H},{...H},Object.keys(Ie);const Le=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 U(e){return Le.has(e)}const Re=new Set([` `,`
4
+ `]),ze=/\r\n/g,Be=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?|\x9d[^\x07\x1b\x9c]*(?:\x07|\x9c|\x1b\\)?|\x1b[P^_X][\s\S]*?(?:\x1b\\|\x07)|\x1b[P^_X][\s\S]*$|[\x90\x98\x9e\x9f][\s\S]*?(?:\x9c|\x1b\\|\x07)|[\x90\x98\x9e\x9f][\s\S]*$|\x1b\[[0-?]*[ -/]*[@-~]|\x9b[0-?]*[ -/]*[@-~]|\x1b[@-Z\\-_]|[\x00-\x1f\x7f]|[\x80-\x9f]/g;function W(e){return e.replace(ze,`
5
+ `).replace(Be,e=>Re.has(e)?e:``)}function Ve(e){return typeof e==`string`?W(e):typeof e==`number`||typeof e==`boolean`||e==null?e:Array.isArray(e)?e.map(e=>Ve(e)):e}function G(e){let{children:t,...n}=e;return B(we,{...n,children:Ve(t)})}function He(e){return B(we,{...e})}const Ue={id:`dark`,name:`Dark`,appearance:`dark`,source:`built-in`,colors:{text:{accent:`cyan`,emphasis:`white`,success:`green`,warning:`yellow`,error:`red`,session:`magenta`,muted:`gray`,onAccent:`black`},border:{attention:`yellow`,focused:`cyan`,active:`green`,muted:`gray`,error:`red`},status:{running:`yellow`,success:`green`,error:`red`,denied:`yellowBright`,waiting:`yellow`,cancelled:`yellow`,idle:`gray`}},markdown:{heading:`green`,firstHeading:`magenta`,code:`yellow`,codespan:`yellow`,link:`blue`,href:`blue`,blockquote:`gray`,del:`gray`,html:`gray`,diffAdded:`ansi256(120)`,diffRemoved:`ansi256(210)`,diffAddedBackground:`ansi256(22)`,diffRemovedBackground:`ansi256(52)`,diffHunk:`cyan`},syntax:{keyword:`blue`,built_in:`cyan`,type:`cyan`,literal:`blue`,number:`green`,regexp:`red`,string:`red`,class:`blue`,function:`yellow`,comment:`green`,doctag:`green`,meta:`gray`,tag:`gray`,name:`blue`,attr:`cyan`,addition:`green`,deletion:`red`},motion:{wave:[`#555555`,`#777777`,`#999999`,`#bbbbbb`]}},We=[Ue,{id:`light`,name:`Light`,appearance:`light`,source:`built-in`,colors:{text:{accent:`ansi256(24)`,emphasis:`black`,success:`ansi256(28)`,warning:`ansi256(130)`,error:`ansi256(124)`,session:`ansi256(90)`,muted:`ansi256(243)`,onAccent:`white`},border:{attention:`ansi256(130)`,focused:`ansi256(24)`,active:`ansi256(28)`,muted:`ansi256(249)`,error:`ansi256(124)`},status:{running:`ansi256(130)`,success:`ansi256(28)`,error:`ansi256(124)`,denied:`ansi256(166)`,waiting:`ansi256(130)`,cancelled:`ansi256(130)`,idle:`ansi256(243)`}},markdown:{heading:`ansi256(28)`,firstHeading:`ansi256(90)`,code:`ansi256(94)`,codespan:`ansi256(94)`,link:`ansi256(26)`,href:`ansi256(26)`,blockquote:`ansi256(243)`,del:`ansi256(243)`,html:`ansi256(243)`,diffAdded:`ansi256(22)`,diffRemoved:`ansi256(52)`,diffAddedBackground:`ansi256(194)`,diffRemovedBackground:`ansi256(224)`,diffHunk:`ansi256(24)`},syntax:{keyword:`ansi256(26)`,built_in:`ansi256(24)`,type:`ansi256(24)`,literal:`ansi256(26)`,number:`ansi256(28)`,regexp:`ansi256(124)`,string:`ansi256(124)`,class:`ansi256(26)`,function:`ansi256(94)`,comment:`ansi256(28)`,doctag:`ansi256(28)`,meta:`ansi256(243)`,tag:`ansi256(243)`,name:`ansi256(26)`,attr:`ansi256(24)`,addition:`ansi256(22)`,deletion:`ansi256(52)`},motion:{wave:[`#bbbbbb`,`#999999`,`#777777`,`#555555`]}},{id:`dark-daltonized`,name:`Dark (daltonized)`,appearance:`dark`,source:`built-in`,colors:{text:{accent:`#56b4e9`,emphasis:`#ffffff`,success:`#56b4e9`,warning:`#e69f00`,error:`#d55e00`,session:`#cc79a7`,muted:`#999999`,onAccent:`#000000`},border:{attention:`#e69f00`,focused:`#56b4e9`,active:`#56b4e9`,muted:`#999999`,error:`#d55e00`},status:{running:`#e69f00`,success:`#56b4e9`,error:`#d55e00`,denied:`#f0e442`,waiting:`#e69f00`,cancelled:`#cc79a7`,idle:`#999999`}},markdown:{heading:`#56b4e9`,firstHeading:`#cc79a7`,code:`#e69f00`,codespan:`#e69f00`,link:`#56b4e9`,href:`#56b4e9`,blockquote:`#999999`,del:`#999999`,html:`#999999`,diffAdded:`#8ecdf5`,diffRemoved:`#ffb066`,diffAddedBackground:`#00335c`,diffRemovedBackground:`#5c3000`,diffHunk:`#56b4e9`},syntax:{keyword:`#56b4e9`,built_in:`#8ecdf5`,type:`#8ecdf5`,literal:`#56b4e9`,number:`#e69f00`,regexp:`#d55e00`,string:`#d55e00`,class:`#56b4e9`,function:`#f0e442`,comment:`#999999`,doctag:`#999999`,meta:`#999999`,tag:`#999999`,name:`#56b4e9`,attr:`#8ecdf5`,addition:`#8ecdf5`,deletion:`#ffb066`},motion:{wave:[`#3d3d3d`,`#5c5c5c`,`#7a7a7a`,`#999999`]}},{id:`light-daltonized`,name:`Light (daltonized)`,appearance:`light`,source:`built-in`,colors:{text:{accent:`#0072b2`,emphasis:`#000000`,success:`#0072b2`,warning:`#b35900`,error:`#8c3d00`,session:`#a8477f`,muted:`#5c5c5c`,onAccent:`#ffffff`},border:{attention:`#b35900`,focused:`#0072b2`,active:`#0072b2`,muted:`#a3a3a3`,error:`#8c3d00`},status:{running:`#b35900`,success:`#0072b2`,error:`#8c3d00`,denied:`#8a7500`,waiting:`#b35900`,cancelled:`#a8477f`,idle:`#5c5c5c`}},markdown:{heading:`#0072b2`,firstHeading:`#a8477f`,code:`#8a5a00`,codespan:`#8a5a00`,link:`#0072b2`,href:`#0072b2`,blockquote:`#5c5c5c`,del:`#5c5c5c`,html:`#5c5c5c`,diffAdded:`#004c77`,diffRemoved:`#7a3300`,diffAddedBackground:`#d6ecf9`,diffRemovedBackground:`#fbe5cd`,diffHunk:`#0072b2`},syntax:{keyword:`#0072b2`,built_in:`#004c77`,type:`#004c77`,literal:`#0072b2`,number:`#b35900`,regexp:`#8c3d00`,string:`#8c3d00`,class:`#0072b2`,function:`#8a7500`,comment:`#5c5c5c`,doctag:`#5c5c5c`,meta:`#5c5c5c`,tag:`#5c5c5c`,name:`#0072b2`,attr:`#004c77`,addition:`#004c77`,deletion:`#7a3300`},motion:{wave:[`#c7c7c7`,`#a3a3a3`,`#7a7a7a`,`#5c5c5c`]}}],Ge=Ue.id;function Ke(){return We}function qe(e){return e??Ue}const Je=M(!1);function Ye({enabled:e,children:t}){return B(Je.Provider,{value:e,children:t})}function K(){return P(Je)}function Xe(){if(`NO_COLOR`in process.env)return!1;let e=process.env.FORCE_COLOR;return e===`0`?!1:e!==void 0&&e!==``||!!process.stdout.isTTY}function Ze(e={}){return e.override===!0?!0:e.override===!1||process.env.TERM_PROGRAM===`Apple_Terminal`?!1:!!process.stdout.isTTY}function Qe(e={}){return e.override===!0?!0:e.override===!1||process.env.TERM_PROGRAM===`WezTerm`?!1:!!process.stdout.isTTY}function $e(e={}){return e.override===!0||e.override!==!1&&!!process.stdin.isTTY&&!!process.stdout.isTTY}const et=M(Ue),tt=M(!1),nt=M(!0);function rt({theme:e,reducedMotion:t=!1,syntaxHighlighting:n=!0,children:r}){return B(et.Provider,{value:qe(e),children:B(tt.Provider,{value:t,children:B(nt.Provider,{value:n,children:r})})})}function it(){return P(et)}function q(){return it().colors}function at(){return it().motion}function ot(){let e=K(),t=P(tt);return Xe()&&!e&&!t}function st(){return P(nt)}const ct=[`keyword`,`built_in`,`type`,`literal`,`number`,`regexp`,`string`,`class`,`function`,`comment`,`doctag`,`meta`,`tag`,`name`,`attr`,`addition`,`deletion`],lt=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/iu,ut=/^ansi256\((\d{1,3})\)$/iu,dt=/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/iu,ft=`<chalk name> | #rgb | #rrggbb | ansi256(n) | rgb(r,g,b)`,pt=new Map([...Ce,...Se].map(e=>[e,T[e]])),mt=new Set(Ce);function ht(e){return mt.has(e)}function gt(e){if(lt.test(e))return!0;let t=ut.exec(e);if(t)return Number(t[1])<=255;let n=dt.exec(e);return n?n.slice(1).every(e=>Number(e)<=255):ht(e)}function _t(e){throw Error(`Theme colour ${JSON.stringify(e)} is not in Ink's colour grammar (${ft}).`)}function J(e,t=T){if(lt.test(e))return t.hex(e);let n=ut.exec(e);if(n)return t.ansi256(Number(n[1]));let r=dt.exec(e);if(r)return t.rgb(Number(r[1]),Number(r[2]),Number(r[3]));let i=ht(e)?pt.get(e):void 0;return i===void 0&&_t(e),Reflect.get(t,e)??i}function vt(e,t=T){if(lt.test(e))return t.bgHex(e);let n=ut.exec(e);if(n)return t.bgAnsi256(Number(n[1]));let r=dt.exec(e);if(r)return t.bgRgb(Number(r[1]),Number(r[2]),Number(r[3]));let i=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;return Reflect.get(t,i)??_t(e)}const yt=new xe({level:3});function bt(){return T.level===0?yt:T}function xt(e){return{heading:J(e.heading).bold,firstHeading:J(e.firstHeading).underline.bold,code:J(e.code),codespan:J(e.codespan),link:J(e.link),href:J(e.href).underline,blockquote:J(e.blockquote).italic,del:J(e.del,T.dim).strikethrough,html:J(e.html)}}function St(e){let t={};for(let n of ct)t[n]=n===`type`?J(e[n]).dim:J(e[n]);return t}function Ct(e){let{markdown:t}=e,n=bt(),r=vt(t.diffAddedBackground,n),i=J(t.diffAdded,n),a=vt(t.diffRemovedBackground,n),o=J(t.diffRemoved,n);return{added:e=>r(i(e)),removed:e=>a(o(e)),hunk:J(t.diffHunk,n),meta:e=>n.dim(e)}}function wt(e){return e.split(/\s+/u).map(Number)}wt(`0 95 135 175 215 255`),wt(`0.1121 0.8853 -0.0005`),wt(`0.1127 0.8897 -0.0001`),wt(`0.0045 0.0 1.0019`),wt(`0.292 0.7054 -0.0003`),wt(`0.2934 0.7089 0.0`),wt(`-0.0209 0.4614 0.5677`),wt(`0.4124 0.3576 0.1805`),wt(`0.2126 0.7152 0.0722`),wt(`0.0193 0.1192 0.9505`),wt(`0.95047 1 1.08883`);function Tt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Et=new Set([`name`,`base`,`overrides`]),Dt=/[\u0000-\u001F\u007F-\u009F]/u,Ot=new RegExp(Dt.source,`gu`);function kt(e){return JSON.stringify(e).replace(Ot,e=>`\\u${(e.codePointAt(0)??0).toString(16).padStart(4,`0`)}`)}function At(e){return kt(e).slice(1,-1)}function jt(e){return W(e).replaceAll(`
6
+ `,` `).replaceAll(` `,` `).trim()}function Mt(e){return Dt.test(e)?kt(e):e}function Nt(e){return{ok:!1,error:e}}function Pt(e,t){return typeof e==`string`?gt(e)?{ok:!0,value:e}:{ok:!1,error:`${t}: ${kt(e)} is not a colour in Ink's grammar (${ft})`}:{ok:!1,error:`${t}: expected a colour string`}}function Ft(e,t,n){if(!Array.isArray(t)||t.length!==e.length)return{ok:!1,error:`${n}: expected exactly ${e.length} colours`};let r=[];for(let[i,a]of e.entries()){let e=Lt(a,t[i]??null,`${n}[${i}]`);if(!e.ok)return e;r.push(e.value)}return{ok:!0,value:r}}function It(e,t,n){if(!Tt(t))return{ok:!1,error:`${n}: expected an object of tokens`};let r={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(e,i))return{ok:!1,error:`${n}.${Mt(i)} is not a theme token`};let a=Lt(e[i]??null,t[i]??null,`${n}.${Mt(i)}`);if(!a.ok)return a;r[i]=a.value}return{ok:!0,value:r}}function Lt(e,t,n){return typeof e==`string`?Pt(t,n):Array.isArray(e)?Ft(e,t,n):Tt(e)?It(e,t,n):{ok:!1,error:`${n} is not a theme token`}}function Rt(e){return JSON.parse(JSON.stringify(e))}function zt(e){return JSON.parse(JSON.stringify({colors:e.colors,markdown:e.markdown,syntax:e.syntax,motion:e.motion}))}function Bt(e){let t;try{t=JSON.parse(e)}catch(e){return{ok:!1,error:`$: ${e instanceof Error?jt(e.message):`invalid JSON`}`}}if(!Tt(t))return{ok:!1,error:`$: expected an object`};for(let e of Object.keys(t))if(!Et.has(e))return{ok:!1,error:`$.${Mt(e)} is not a theme token`};return{ok:!0,value:t}}function Vt(e,t){let n=e.name;return n===void 0?Dt.test(t)?{ok:!1,error:`$.name: the minted id must not contain control characters`}:t.length>60?{ok:!1,error:`$.name: the minted id must be at most 60 characters`}:{ok:!0,value:t}:typeof n!=`string`||n.trim().length===0?{ok:!1,error:`$.name: expected a non-empty string`}:Dt.test(n)?{ok:!1,error:`$.name: must not contain control characters`}:n.length>60?{ok:!1,error:`$.name: must be at most 60 characters`}:{ok:!0,value:n}}function Ht(e){let t=e.base===void 0?Ge:e.base;if(typeof t!=`string`)return{ok:!1,error:`$.base: expected a built-in theme id`};let n=We.find(e=>e.id===t);return n?{ok:!0,theme:n}:{ok:!1,error:`$.base: ${kt(t)} is not a built-in theme`}}function Ut(e){let t=Bt(e.text);if(!t.ok)return Nt(t.error);let n=t.value,r=Ht(n);if(!r.ok)return Nt(r.error);let i=Vt(n,e.id);if(!i.ok)return Nt(i.error);let a=n.overrides===void 0?{}:n.overrides,o=Lt(zt(r.theme),a,`$.overrides`);if(!o.ok)return Nt(o.error);let{colors:s,markdown:c,syntax:l,motion:u}=Rt(o.value);return{ok:!0,theme:{id:e.id,name:i.value,appearance:r.theme.appearance,source:e.source,colors:s,markdown:c,syntax:l,motion:u}}}function Wt({version:e}){return V(E,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[B(G,{color:q().text.accent,bold:!0,children:`
7
7
  ____ ___ ____ ___ _____ _
8
8
  | _ \\ / _ \\| __ ) / _ \\_ _|/ \\
9
9
  | |_) | | | | _ \\| | | || | / _ \\
10
10
  | _ <| |_| | |_) | |_| || |/ ___ \\
11
11
  |_| \\_\\\\___/|____/ \\___/ |_/_/ \\_\\
12
- `}),V(G,{dimColor:!0,children:[` v`,e]})]})}const Ut=1e3;function Wt(e,t){let n=Date.parse(e);if(Number.isNaN(n))return;let r=n-t.getTime();if(r<=0)return`now`;let i=Math.floor(r/Ut),a=Math.floor(i/3600),o=Math.floor(i/60)%60,s=i%60;return a>0?`in ${a}h ${o}m`:o>0?`in ${o}m ${s}s`:`in ${s}s`}const Gt={running:`⟳`,success:`✓`,error:`✗`,denied:`⊘`,waiting:`◴`,cancelled:`⊗`,idle:`·`};function Kt(e,t){return e.status[t]}function qt(e){return e.isRunning?`running`:e.result===`error`?`error`:e.result===`denied`?`denied`:`success`}const Jt=[`active`,`queued`,`running`,`sleeping`];function Yt(e,t){return t===`failed`||e===`failed`?`error`:t===`permission`||e===`waiting_permission`?`waiting`:e===`completed`?`success`:e===`cancelled`?`cancelled`:Jt.includes(e)?`running`:`idle`}const Xt=[`active`,`queued`,`running`,`waiting_permission`,`sleeping`],Zt=/\s+/g;function Qt(e){return(e?.entries??[]).filter(e=>e.kind===`background_task`&&e.visibility==="default")}function $t(e){return Qt(e).filter(e=>Xt.includes(e.status)).length}function en(e,t={}){let n=e.id===t.selectedEntryId,r={id:e.id,radio:n?`●`:`○`,state:e.state,title:nn(e),subtitle:rn(e),statusLabel:an(e.status),preview:sn(e.preview??e.currentAction),statusKind:on(e),isSelected:n};return{...r,accessibleText:cn(r)}}function tn(e){let t=e.text.trim().replace(Zt,` `);return t?t.length>160?`${t.slice(0,160)}...`:t:e.kind}function nn(e){return e.kind===`main_thread`?e.title:e.kind===`background_group`?`${e.title} group`:e.taskKind===`agent`?`${e.title} agent`:e.taskKind===`process`?e.title||`Process`:e.taskKind===`scheduled`?e.title||`Scheduled`:e.title}function rn(e){return e.kind===`main_thread`?e.subtitle:[e.taskKind,e.subtitle,e.attention===`none`?void 0:e.attention].filter(e=>typeof e==`string`&&e.length>0).join(` · `)||void 0}function an(e){return e.replace(/_/g,` `)}function on(e){return Yt(e.status,e.attention)}function sn(e){return e?.trim().replace(Zt,` `)||void 0}function cn(e){return[`${e.radio} ${e.state}`,e.title,e.statusLabel,e.subtitle,e.preview].filter(e=>typeof e==`string`&&e.length>0).join(` · `)}const ln={branch:`├`,last:`└`,plain:`-`};function un(e,t,n){let r=e.headline?.text;if(r!==void 0&&r.length!==0&&r!==t&&!(n!==void 0&&n.includes(r)))return e.headline?.kind===`question`?`? ${r}`:r}function dn(e){return e.screenReader===!0?ln.plain:e.isLast===!1?ln.branch:ln.last}function fn(e,t={}){let n=en(e),r=Gt[Yt(e.status,e.attention)],i=[n.statusLabel,n.subtitle].filter(e=>typeof e==`string`&&e.length>0),a=dn(t),o=un(e,n.preview,n.subtitle),s=e.nextFireAt===void 0?void 0:Wt(e.nextFireAt,t.now??new Date);return{connector:a,marker:r,state:e.state,statusKind:n.statusKind,label:n.title,segments:i,preview:n.preview,headline:o,countdown:s,accessibleText:[`${a} ${r} ${e.state} ${n.title}`,...i,o,n.preview,s].filter(e=>typeof e==`string`&&e.length>0).join(` · `)}}function pn(e,t){let n=e&&!t,[r,i]=R(()=>new Date);return F(()=>{if(!n)return;i(new Date);let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[n]),n?r:new Date}function mn({entries:e,focusedIndex:t=null}){let n=q(),r=K(),i=pn(e.some(e=>e.nextFireAt!==void 0),r);if(e.length===0)return null;let a=t===null?` · ↓ select · Ctrl+B all`:` · ↑↓ select · Enter open · Esc back`;return V(D,{flexDirection:`column`,marginBottom:1,children:[V(D,{children:[B(G,{color:n.text.accent,bold:!0,children:`Background work`}),B(G,{dimColor:!0,children:a})]}),e.map((a,o)=>{let s=fn(a,{isLast:o===e.length-1,screenReader:r,now:i});return V(G,{wrap:`truncate-end`,inverse:o===t,children:[`${s.connector} `,B(G,{color:Kt(n,s.statusKind),children:`${s.marker} ${s.state}`}),` ${s.label}`,s.segments.map((e,t)=>B(G,{dimColor:!0,children:` · ${e}`},`${e}-${t}`)),s.headline?B(G,{dimColor:!0,children:` · ${s.headline}`}):null,s.preview?B(G,{dimColor:!0,children:` · ${s.preview}`}):null,s.countdown?B(G,{color:Kt(n,s.statusKind),children:` · ${s.countdown}`}):null]},a.id)})]})}function hn({percentage:e}){let t=q(),n=K();return e>=90?B(D,{...n?{}:{borderStyle:`single`,borderColor:t.border.error},paddingX:1,children:V(G,{color:t.text.error,bold:!0,children:[`⚠ Context at `,Math.round(e),`% — window nearly full. Run /compact to summarize the conversation.`]})}):e>=70?B(D,{paddingX:1,children:V(G,{color:t.text.warning,children:[`Context at `,Math.round(e),`% — consider running /compact to free up space.`]})}):null}function gn({entry:e,page:t,loading:n,error:r}){let i=q(),a=en(e,{selectedEntryId:e.id}),o=t?.records.slice(-12)??[];return V(D,{flexDirection:`column`,marginBottom:1,children:[B(G,{color:i.text.accent,bold:!0,children:`Viewing ${a.title}`}),V(G,{dimColor:!0,children:[a.statusLabel,a.subtitle?` · ${a.subtitle}`:``,a.preview?` · ${a.preview}`:``]}),n?B(G,{dimColor:!0,children:`Loading workspace detail...`}):null,r?B(G,{color:i.text.error,children:r}):null,!n&&!r&&o.length===0?B(G,{dimColor:!0,children:`No detail yet`}):null,!n&&!r&&o.map(e=>{let{symbol:t,color:n}=_n(e.kind,i);return V(G,{color:n,children:[t?`${t} `:``,tn(e)]},e.id)}),t?.nextCursor?B(G,{dimColor:!0,children:`... more detail available`}):null]})}function _n(e,t){return e===`error`?{symbol:Gt.error,color:Kt(t,`error`)}:e===`result`?{symbol:Gt.success,color:Kt(t,`success`)}:e===`group_summary`?{symbol:`▸`,color:t.text.accent}:e===`process_output`?{symbol:`·`,color:t.text.emphasis}:{symbol:``,color:void 0}}function vn(e=0){return{selectedIndex:e,scrollOffset:0,resolved:!1}}function yn(){return{buffer:``,invalid:!1,resolved:!1}}function bn(e,t,n,r){if(e.resolved)return{state:e,effect:{type:`none`}};if(n.escape===!0&&r.cancellable===!0)return{state:{...e,resolved:!0},effect:{type:`cancel`}};if(n.backspace===!0||n.delete===!0)return{state:{...e,buffer:e.buffer.slice(0,-1)},effect:{type:`none`}};if(n.return===!0){if(r.multi===!0&&e.buffer===``)return{state:{...e,invalid:!1,resolved:!0},effect:{type:`confirm`}};let t=Number.parseInt(e.buffer,10)-1;return!Number.isInteger(t)||t<0||t>=r.itemCount?{state:{...e,buffer:``,invalid:!0},effect:{type:`none`}}:{state:{...e,buffer:``,invalid:!1,resolved:r.multi!==!0&&r.repeatable!==!0},effect:{type:`select`,index:t}}}return/^[0-9]+$/.test(t)?{state:{...e,buffer:e.buffer+t,invalid:!1},effect:{type:`none`}}:{state:e,effect:{type:`none`}}}function xn(e,t,n){if(e.resolved)return{state:e,effect:{type:`none`}};if(t===`cancel`)return{state:{...e,resolved:!0},effect:{type:`cancel`}};if(n.enabled===!1||n.itemCount===0)return{state:e,effect:{type:`none`}};if(t===`select`){let t=Tn(e.selectedIndex,n.itemCount);return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`select`,index:t}}}let r=Cn(e.selectedIndex,t,n),i=wn(r,e.scrollOffset,n);return{state:{...e,selectedIndex:r,scrollOffset:i},effect:{type:`none`}}}function Sn(e,t){if(t.itemCount===0)return{...e,selectedIndex:0,scrollOffset:0};let n=Tn(e.selectedIndex,t.itemCount),r=wn(n,e.scrollOffset,t);return n===e.selectedIndex&&r===e.scrollOffset?e:{...e,selectedIndex:n,scrollOffset:r}}function Cn(e,t,n){return t===`previous`?n.wrap===!0&&e===0?n.itemCount-1:Math.max(0,e-1):n.wrap===!0&&e===n.itemCount-1?0:Math.min(n.itemCount-1,e+1)}function wn(e,t,n){let r=n.maxVisible??n.itemCount;return r<=0?0:e<t?e:e>=t+r?e-r+1:Math.max(0,t)}function Tn(e,t){return Math.min(Math.max(e,0),t-1)}function En({entries:e,selectedEntryId:t,onSelect:n,onClose:r}){let[i,a]=R(()=>vn()),o=L(i);F(()=>{let n=On({selectedIndex:Math.max(0,e.findIndex(e=>e.id===t)),itemCount:e.length});o.current=n,a(n)},[e.length,t]);let s=On({selectedIndex:i.selectedIndex,scrollOffset:i.scrollOffset,itemCount:e.length});return s!==i&&(o.current=s),{normalized:s,visibleEntries:e.slice(s.scrollOffset,s.scrollOffset+8),applyAction:Dn({entries:e,stateRef:o,setState:a,onSelect:n,onClose:r})}}function Dn({entries:e,stateRef:t,setState:n,onSelect:r,onClose:i}){return a=>{let o=xn(t.current,a,{itemCount:e.length,maxVisible:8}),s=o.effect.type===`select`||o.effect.type===`cancel`?{...o.state,resolved:!1}:o.state;if(t.current=s,n(s),o.effect.type===`cancel`)i();else if(o.effect.type===`select`){let t=e[o.effect.index];t&&r(t.id)}}}function On(e){return Sn({selectedIndex:e.selectedIndex,scrollOffset:e.scrollOffset??0,resolved:!1},{itemCount:e.itemCount,maxVisible:8})}function kn(e){let[t,n]=R(yn),r=L(t),{enabled:i,itemCount:a,cancellable:o,multi:s,repeatable:c,onSelect:l,onCancel:u,onConfirm:d}=e,f=N(()=>{let e=yn();r.current=e,n(e)},[]),p=N((e,t)=>{let i=bn(r.current,e,t,{itemCount:a,...o===!0?{cancellable:!0}:{},...s===!0?{multi:!0}:{},...c===!0?{repeatable:!0}:{}});return r.current=i.state,n(i.state),i.effect.type===`select`?l(i.effect.index):i.effect.type===`cancel`?u?.():i.effect.type===`confirm`&&d?.(),i.effect.type!==`none`},[a,o,s,c,l,u,d]);return we((e,t)=>{if(t.return!==!0&&/[\r\n]/u.test(e)){let n={...t,return:!1};for(let t of e.split(/(\r\n|\r|\n)/u))if(t!==``&&(/^(\r\n|\r|\n)$/u.test(t)?p(``,{...n,return:!0}):p(t,n)))break;return}p(e,t)},{isActive:i}),{buffer:t.buffer,invalid:t.invalid,clear:f}}function An(e){return e.map(e=>`${e.keys} ${e.label}`).join(` · `)}function Y({hints:e}){return e.length===0?null:V(G,{dimColor:!0,children:[` `,An(e)]})}const jn={app:[`open-workspace-switcher`],thinking:[`abort`],"background-detail":[`return-to-main`],recovery:[`retry`],"chat-input":[`submit`,`history-previous`,`history-next`,`history-search`,`cursor-left`,`cursor-right`,`delete-backward`,`delete-word`,`delete-line`],"text-input":[`submit`,`cursor-left`,`cursor-right`,`cursor-up`,`cursor-down`,`delete-backward`,`delete-word`,`delete-line`],"autocomplete-menu":[`previous`,`next`,`close`,`accept`,`execute`],"queued-prompt":[`cancel`],"confirm-prompt":[`previous`,`next`,`confirm`,`choose-yes`,`choose-no`],"permission-prompt":[`previous`,`next`,`confirm`,`allow-once`,`allow-session`,`allow-project`,`deny`],"text-prompt":[`submit`,`cancel`,`delete-backward`],"list-picker":[`previous`,`next`,`select`,`cancel`],"menu-select":[`previous`,`next`,`select`,`back`],"multi-select":[`previous`,`next`,`toggle`,`confirm`,`cancel`],"workspace-switcher":[`previous`,`next`,`select`,`close`,`attach`],"background-list":[`previous`,`next`,`open`,`close`],"transport-settings":[`previous`,`next`,`toggle`,`close`],"history-search":[`previous`,`next`,`cycle-scope`,`insert`,`execute`,`cancel`],"theme-picker":[`previous`,`next`,`select`,`toggle-syntax`,`toggle-motion`,`cancel`]},Mn={app:{"open-workspace-switcher":[`ctrl+b`]},thinking:{abort:[`escape`]},"background-detail":{"return-to-main":[`escape`]},recovery:{retry:[`enter`]},"chat-input":{submit:[`enter`],"history-previous":[`up`],"history-next":[`down`],"history-search":[`ctrl+r`],"cursor-left":[`left`],"cursor-right":[`right`],"delete-backward":[`backspace`,`delete`],"delete-word":[`ctrl+w`],"delete-line":[`ctrl+u`]},"text-input":{submit:[`enter`],"cursor-left":[`left`],"cursor-right":[`right`],"cursor-up":[`up`],"cursor-down":[`down`],"delete-backward":[`backspace`,`delete`],"delete-word":[`ctrl+w`],"delete-line":[`ctrl+u`]},"autocomplete-menu":{previous:[`up`],next:[`down`],close:[`escape`],accept:[`tab`],execute:[`enter`]},"queued-prompt":{cancel:[`backspace`,`delete`]},"confirm-prompt":{previous:[`left`,`up`],next:[`right`,`down`],confirm:[`enter`],"choose-yes":[`y`],"choose-no":[`n`]},"permission-prompt":{previous:[`left`,`up`],next:[`right`,`down`],confirm:[`enter`],"allow-once":[`y`],"allow-session":[`s`,`a`],"allow-project":[`p`],deny:[`n`,`d`]},"text-prompt":{submit:[`enter`],cancel:[`escape`],"delete-backward":[`backspace`,`delete`]},"list-picker":{previous:[`up`],next:[`down`],select:[`enter`],cancel:[`escape`]},"menu-select":{previous:[`up`],next:[`down`],select:[`enter`],back:[`escape`]},"multi-select":{previous:[`up`],next:[`down`],toggle:[`space`],confirm:[`enter`],cancel:[`escape`]},"workspace-switcher":{previous:[`up`],next:[`down`],select:[`enter`],close:[`ctrl+b`,`escape`],attach:[`a`]},"background-list":{previous:[`up`],next:[`down`],open:[`enter`],close:[`escape`]},"transport-settings":{previous:[`up`],next:[`down`],toggle:[`space`],close:[`enter`,`escape`]},"history-search":{previous:[`up`],next:[`down`,`ctrl+r`],"cycle-scope":[`ctrl+s`],insert:[`enter`,`tab`],execute:[`ctrl+e`],cancel:[`escape`]},"theme-picker":{previous:[`up`],next:[`down`],select:[`enter`],"toggle-syntax":[`s`],"toggle-motion":[`m`],cancel:[`escape`]}},Nn=new Set([`chat-input`,`text-input`,`text-prompt`,`history-search`]),Pn={ctrl:`ctrl`,control:`ctrl`,alt:`alt`,option:`alt`,meta:`meta`,cmd:`meta`,command:`meta`,shift:`shift`},Fn=[`ctrl`,`alt`,`meta`,`shift`],In={return:`enter`,enter:`enter`,esc:`escape`,escape:`escape`,tab:`tab`,space:`space`,spacebar:`space`,up:`up`,down:`down`,left:`left`,right:`right`,backspace:`backspace`,delete:`delete`};function Ln(e){let t=e.trim().split(/\s+/u);if(t.length<1||t.length>2)return;let n=t.map(Rn);return n.every(e=>e!==void 0)?n.join(` `):void 0}function Rn(e){if(!e||e.includes(` `))return;let t=e.split(`+`);if(t.some(e=>e.length===0))return;let n=t.at(-1);if(n===void 0)return;let r=new Set;for(let e of t.slice(0,-1)){let t=Pn[e.toLowerCase()];if(t===void 0||r.has(t))return;r.add(t)}let i=In[n.toLowerCase()];if(i===void 0){if([...n].length!==1||/\s/u.test(n))return;i=n.toLowerCase(),t.length===1&&n!==i&&r.add(`shift`)}return[...Fn.filter(e=>r.has(e)),i].join(`+`)}function zn(e,t){if(/^[\r\n]*\n[\r\n]*$/u.test(e))return`ctrl+j`;let n=t.return?`enter`:t.escape?`escape`:t.tab?`tab`:t.upArrow?`up`:t.downArrow?`down`:t.leftArrow?`left`:t.rightArrow?`right`:t.backspace?`backspace`:t.delete?`delete`:e===` `?`space`:[...e].length===1?e.toLowerCase():void 0;if(n!==void 0)return[...t.ctrl?[`ctrl`]:[],...t.meta?[`meta`]:[],...t.shift?[`shift`]:[],n].join(`+`)}function Bn(e,t){let n=zn(e,t);return n===void 0?[]:n===`enter`?[`enter`,`ctrl+m`]:n===`tab`?[`tab`,`ctrl+i`]:n===`escape`?[`escape`,`ctrl+[`]:[n]}function Vn(e){return e.split(` `).map(e=>e===`ctrl+m`?`enter`:e===`ctrl+i`?`tab`:e===`ctrl+[`?`escape`:e).join(` `)}function Hn(e){return e.split(` `).map(e=>e.split(`+`).map(e=>({ctrl:`Ctrl`,alt:`Alt`,meta:`Meta`,shift:`Shift`,escape:`Esc`,up:`↑`,down:`↓`,left:`←`,right:`→`})[e]??(e.length===1?e.toUpperCase():`${e[0]?.toUpperCase()}${e.slice(1)}`)).join(`+`)).join(` `)}function X(e,t,n){return{ok:!1,diagnostic:{file:e,path:t,message:n}}}function Un(){return Object.fromEntries(Object.entries(Mn).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([e,t])=>[e,[...t]]))]))}function Wn(e){if(e===null)return null;if(typeof e==`string`)return[e];if(Array.isArray(e)&&e.length>0&&e.every(e=>typeof e==`string`))return e}function Gn(e,t,n){let r=new Map,i=new Map;for(let[a,o]of Object.entries(t))for(let t of o){let o=Vn(t),s=r.get(o),c=`$.bindings.${e}.${a}`;if(s!==void 0&&s!==a)return X(n,c,`Binding duplicates action ${s}.`);let l=o.split(` `);if(l.length>1&&Nn.has(e)&&Kn(l[0]??``))return X(n,c,`Printable text cannot begin a chord in a text context.`);r.set(o,a),l.length>1&&i.set(l[0]??``,a)}for(let[t,a]of r){let r=i.get(t);if(r!==void 0)return X(n,`$.bindings.${e}.${r}`,`Chord prefix collides with action ${a}.`)}}function Kn(e){return!e.includes(`+`)&&[...e].length===1}function qn(e,t){let n=[];return e.split(` `).includes(`ctrl+b`)&&n.push({code:`multiplexer-conflict`,path:t,message:`Ctrl+B may be captured by a terminal multiplexer.`}),/ctrl\+shift\+[a-z]/u.test(e)&&n.push({code:`modifier-delivery`,path:t,message:`This terminal may not distinguish Ctrl+Shift from Ctrl.`}),n}function Jn(e,t){let n;try{n=JSON.parse(e)}catch(e){return X(t,`$`,e instanceof Error?e.message:`Invalid JSON.`)}if(!Ct(n))return X(t,`$`,`Expected an object.`);if(n.version!==1)return X(t,`$.version`,`Expected version 1.`);if(!Ct(n.bindings))return X(t,`$.bindings`,`Expected an object.`);let r=Un(),i=[];for(let[e,a]of Object.entries(n.bindings)){if(!(e in jn))return X(t,`$.bindings.${e}`,`Unknown keybinding context.`);let n=e;if(!Ct(a))return X(t,`$.bindings.${n}`,`Expected an action object.`);for(let[e,o]of Object.entries(a)){if(!jn[n].includes(e))return X(t,`$.bindings.${n}.${e}`,`Unknown action.`);let a=Wn(o),s=`$.bindings.${n}.${e}`;if(a===void 0)return X(t,s,`Expected a binding, binding list, or null.`);if(a===null){r[n][e]=[];continue}let c=[];for(let e of a){let n=Ln(e);if(n===void 0)return X(t,s,`Invalid binding syntax.`);if(n.split(` `).includes(`ctrl+c`))return X(t,s,`Ctrl+C is reserved for two-stage shutdown.`);c.push(n),i.push(...qn(n,s))}r[n][e]=c}}for(let e of Object.keys(r)){let n=Gn(e,r[e],t);if(n!==void 0)return n}let a=Object.freeze(Object.fromEntries(Object.entries(r).map(([e,t])=>[e,Object.freeze(Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Object.freeze(t)])))])));return{ok:!0,snapshot:Object.freeze({generation:0,sourcePath:t,bindings:a,warnings:Object.freeze(i)})}}function Yn(){return{strokes:[]}}function Xn(e,t){return Object.entries(e.bindings[t])}function Zn(e){let t=Bn(e.input,e.key);if(t.length===0)return{state:Yn(),actions:[],consumed:!1};let n=e.state.context===e.context&&e.state.generation===e.snapshot.generation&&(e.state.deadline===void 0||e.now<=e.state.deadline)&&!e.key.escape?e.state.strokes:[],r=Xn(e.snapshot,e.context);for(let i of t){let t=[...n,i].join(` `),a=r.filter(([,e])=>e.includes(t)).map(([e])=>e);if(a.length>0)return{state:Yn(),actions:a,consumed:!0};if(r.some(([,e])=>e.some(e=>e.startsWith(`${t} `))))return{state:{context:e.context,generation:e.snapshot.generation,strokes:[...n,i],deadline:e.now+1e3},actions:[],consumed:!0}}return n.length>0?Zn({...e,state:Yn()}):{state:Yn(),actions:[],consumed:!1}}function Qn(e,t,n){return n.flatMap(([n,r])=>{let i=Array.isArray(n),a=(i?n:[n]).flatMap(n=>{let r=e.bindings[t][n]??[];return i?r.slice(0,1):r}),o=a.map(Hn),s=o.every(e=>/^[↑↓←→]$/u.test(e))?o.join(``):o.join(`/`);return a.length===0?[]:[{keys:s,label:r}]})}const $n=Jn(`{"version":1,"bindings":{}}`,`<defaults>`);if(!$n.ok)throw Error($n.diagnostic.message);const er=$n.snapshot,tr=M(er);function nr({source:e,children:t}){let[n,r]=R(()=>e?.getSnapshot()??er);return F(()=>{if(e!==void 0)return r(e.getSnapshot()),e.subscribe(r)},[e]),B(tr.Provider,{value:n,children:t})}function rr(){return P(tr)}function Z(e,t){return Qn(rr(),e,t)}function Q(e,t,n={}){let r=rr(),i=L(Yn()),a=L(Yn()),{fallbackContext:o}=n;F(()=>{i.current=Yn(),a.current=Yn()},[e,o,r.generation]),we((n,s)=>{let c=Zn({snapshot:r,state:i.current,context:e,input:n,key:s,now:Date.now()});if(i.current=c.state,o===void 0||c.consumed){a.current=Yn(),t(c.actions,n,s,c.consumed,e);return}let l=Zn({snapshot:r,state:a.current,context:o,input:n,key:s,now:Date.now()});a.current=l.state,t(l.actions,n,s,l.consumed,o)},{isActive:n.isActive??!0})}function ir(e,t){let n=`Enter selection (1-${e})`;return t?`${n} or Escape to cancel`:n}function ar(e){return`${e+1}. `}function or({itemCount:e,cancellable:t=!1,buffer:n=``,invalid:r=!1}){if(e===0)return null;let i=ir(e,t);return V(z,{children:[V(G,{children:[i,n.length>0?` ${n}`:``]}),r&&B(G,{children:i})]})}function sr({title:e,description:t,options:n,cancellable:r=!1,buffer:i=``,invalid:a=!1}){return V(D,{flexDirection:`column`,children:[e!==void 0&&e.length>0&&B(G,{children:e}),t!==void 0&&t.length>0&&B(G,{children:t}),n.map((e,t)=>V(G,{children:[ar(t),e]},`${t}-${e}`)),B(or,{itemCount:n.length,cancellable:r,buffer:i,invalid:a})]})}function cr(e){return e?.controls.includes(`attach`)===!0}function lr({snapshot:e,selectedEntryId:t,onSelect:n,onClose:r,onAttach:i}){let a=q(),o=[...e?.entries??[]],{normalized:s,visibleEntries:c,applyAction:l}=En({entries:o,selectedEntryId:t,onSelect:n,onClose:r}),u=o[s.selectedIndex],d=i!==void 0&&cr(u),f=K(),p=kn({enabled:f&&o.length>0,itemCount:o.length,cancellable:!0,onSelect:e=>{let t=o[e];t&&n(t.id)},onCancel:r});Q(`workspace-switcher`,e=>{for(let t of e)t===`attach`&&d&&u?(i(u),r()):t===`previous`||t===`next`||t===`select`?l(t):t===`close`&&l(`cancel`)},{isActive:!f});let m=Z(`workspace-switcher`,[[[`previous`,`next`],`Navigate`],[`select`,`Switch`],[`close`,`Close`]]),h=Z(`workspace-switcher`,[[`attach`,`Attach`]]);return V(D,{flexDirection:`column`,...f?{}:{borderStyle:`round`,borderColor:a.border.focused},paddingX:1,children:[B(G,{color:a.text.accent,bold:!0,children:`Execution workspace`}),B(D,{flexDirection:`column`,marginTop:1,children:c.length===0?B(G,{dimColor:!0,children:`No workspace entries`}):f?o.map((e,n)=>B(dr,{entry:e,isFocused:!1,selectedEntryId:t,rowNumber:n},e.id)):c.map((e,n)=>B(dr,{entry:e,isFocused:s.scrollOffset+n===s.selectedIndex,selectedEntryId:t},e.id))}),f?B(ur,{itemCount:o.length,buffer:p.buffer,invalid:p.invalid}):B(Y,{hints:d?[...m,...h]:m})]})}function ur({itemCount:e,buffer:t,invalid:n}){let r=ir(e,!0);return V(D,{flexDirection:`column`,children:[V(G,{children:[r,t.length>0?` ${t}`:``]}),n&&B(G,{children:r})]})}function dr({entry:e,isFocused:t,selectedEntryId:n,rowNumber:r}){let i=q(),a=en(e,{selectedEntryId:n});return V(G,{children:[B(G,{color:t?i.text.accent:void 0,bold:t,children:r===void 0?t?`> `:` `:ar(r)}),B(G,{color:Kt(i,a.statusKind),children:`${a.radio} ${a.state}`}),B(G,{color:t?i.text.accent:void 0,bold:t,children:` ${a.title}`}),B(G,{dimColor:!0,children:` · ${a.statusLabel}`}),a.subtitle?B(G,{dimColor:!0,children:` · ${a.subtitle}`}):null,a.preview?B(G,{dimColor:!0,children:` · ${a.preview}`}):null]})}function fr(e,t,n){let r=0;for(let i=0;i<t&&i<e.length;i++){let t=Oe(e[i]),a=r%n;a+t>n&&(r+=n-a),r+=t}return r}function pr(e,t,n){let r=0;for(let i=0;i<e.length;i++){if(r>=t)return i;let a=Oe(e[i]),o=r%n;o+a>n&&(r+=n-o),r+=a}return e.length}function mr(e,t,n){if(!n||n<=0)return{state:e,effect:{type:`none`}};let r=[...e.value],i=fr(r,e.cursor,n),a=t===`up`?i-n:i+n;if(a<0)return{state:e,effect:{type:`none`}};let o=pr(r,a,n);return o===e.cursor?{state:e,effect:{type:`none`}}:{state:{...e,cursor:o},effect:{type:`render`}}}function hr(e,t){return t===`left`&&e.cursor>0?{state:{...e,cursor:e.cursor-1},effect:{type:`render`}}:t===`right`&&e.cursor<e.value.length?{state:{...e,cursor:e.cursor+1},effect:{type:`render`}}:{state:e,effect:{type:`none`}}}function gr(e,t){if(!(t<=0))return{value:e.slice(0,t-1)+e.slice(t),cursor:t-1,deleted:e.slice(t-1,t)}}function _r(e,t){if(t<=0)return;let n=t;for(;n>0&&/\s/u.test(e[n-1]??``);)--n;for(;n>0&&!/\s/u.test(e[n-1]??``);)--n;if(n!==t)return{value:e.slice(0,n)+e.slice(t),cursor:n,deleted:e.slice(n,t)}}function vr(e,t){if(!(t<=0))return{value:e.slice(t),cursor:0,deleted:e.slice(0,t)}}const yr=`[200~`,br=`[201~`;function xr(e){return{value:e,cursor:e.length,isPasting:!1,pasteBuffer:``}}function Sr(e,t,n){return t===e.value?e:{...e,value:t,cursor:n==null?t.length:Math.min(n,t.length)}}function Cr(e,t,n,r){let i=Tr(e,t,r);if(i!==void 0)return i;let a=Er(e,t,n,r);if(a!==void 0)return a;let o=Dr(e,n,r);return o===void 0?Nr(e,t):o}function wr(e,t,n){let r=t.replace(/\r\n?/g,`
12
+ `}),V(G,{dimColor:!0,children:[` v`,e]})]})}const Gt=1e3;function Kt(e,t){let n=Date.parse(e);if(Number.isNaN(n))return;let r=n-t.getTime();if(r<=0)return`now`;let i=Math.floor(r/Gt),a=Math.floor(i/3600),o=Math.floor(i/60)%60,s=i%60;return a>0?`in ${a}h ${o}m`:o>0?`in ${o}m ${s}s`:`in ${s}s`}const qt={running:`⟳`,success:`✓`,error:`✗`,denied:`⊘`,waiting:`◴`,cancelled:`⊗`,idle:`·`};function Jt(e,t){return e.status[t]}function Yt(e){return e.isRunning?`running`:e.result===`error`?`error`:e.result===`denied`?`denied`:`success`}const Xt=[`active`,`queued`,`running`,`sleeping`];function Zt(e,t){return t===`failed`||e===`failed`?`error`:t===`permission`||e===`waiting_permission`?`waiting`:e===`completed`?`success`:e===`cancelled`?`cancelled`:Xt.includes(e)?`running`:`idle`}const Qt=[`active`,`queued`,`running`,`waiting_permission`,`sleeping`],$t=/\s+/g;function en(e){return(e?.entries??[]).filter(e=>e.kind===`background_task`&&e.visibility==="default")}function tn(e){return en(e).filter(e=>Qt.includes(e.status)).length}function nn(e,t={}){let n=e.id===t.selectedEntryId,r={id:e.id,radio:n?`●`:`○`,state:e.state,title:an(e),subtitle:on(e),statusLabel:sn(e.status),preview:ln(e.preview??e.currentAction),statusKind:cn(e),isSelected:n};return{...r,accessibleText:un(r)}}function rn(e){let t=e.text.trim().replace($t,` `);return t?t.length>160?`${t.slice(0,160)}...`:t:e.kind}function an(e){return e.kind===`main_thread`?e.title:e.kind===`background_group`?`${e.title} group`:e.taskKind===`agent`?`${e.title} agent`:e.taskKind===`process`?e.title||`Process`:e.taskKind===`scheduled`?e.title||`Scheduled`:e.title}function on(e){return e.kind===`main_thread`?e.subtitle:[e.taskKind,e.subtitle,e.attention===`none`?void 0:e.attention].filter(e=>typeof e==`string`&&e.length>0).join(` · `)||void 0}function sn(e){return e.replace(/_/g,` `)}function cn(e){return Zt(e.status,e.attention)}function ln(e){return e?.trim().replace($t,` `)||void 0}function un(e){return[`${e.radio} ${e.state}`,e.title,e.statusLabel,e.subtitle,e.preview].filter(e=>typeof e==`string`&&e.length>0).join(` · `)}const dn={branch:`├`,last:`└`,plain:`-`};function fn(e,t,n){let r=e.headline?.text;if(r!==void 0&&r.length!==0&&r!==t&&!(n!==void 0&&n.includes(r)))return e.headline?.kind===`question`?`? ${r}`:r}function pn(e){return e.screenReader===!0?dn.plain:e.isLast===!1?dn.branch:dn.last}function mn(e,t={}){let n=nn(e),r=qt[Zt(e.status,e.attention)],i=[n.statusLabel,n.subtitle].filter(e=>typeof e==`string`&&e.length>0),a=pn(t),o=fn(e,n.preview,n.subtitle),s=e.nextFireAt===void 0?void 0:Kt(e.nextFireAt,t.now??new Date);return{connector:a,marker:r,state:e.state,statusKind:n.statusKind,label:n.title,segments:i,preview:n.preview,headline:o,countdown:s,accessibleText:[`${a} ${r} ${e.state} ${n.title}`,...i,o,n.preview,s].filter(e=>typeof e==`string`&&e.length>0).join(` · `)}}function hn(e,t){let n=e&&!t,[r,i]=R(()=>new Date);return F(()=>{if(!n)return;i(new Date);let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[n]),n?r:new Date}function gn({entries:e,focusedIndex:t=null}){let n=q(),r=K(),i=hn(e.some(e=>e.nextFireAt!==void 0),r);if(e.length===0)return null;let a=t===null?` · ↓ select · Ctrl+B all`:` · ↑↓ select · Enter open · Esc back`;return V(E,{flexDirection:`column`,marginBottom:1,children:[V(E,{children:[B(G,{color:n.text.accent,bold:!0,children:`Background work`}),B(G,{dimColor:!0,children:a})]}),e.map((a,o)=>{let s=mn(a,{isLast:o===e.length-1,screenReader:r,now:i});return V(G,{wrap:`truncate-end`,inverse:o===t,children:[`${s.connector} `,B(G,{color:Jt(n,s.statusKind),children:`${s.marker} ${s.state}`}),` ${s.label}`,s.segments.map((e,t)=>B(G,{dimColor:!0,children:` · ${e}`},`${e}-${t}`)),s.headline?B(G,{dimColor:!0,children:` · ${s.headline}`}):null,s.preview?B(G,{dimColor:!0,children:` · ${s.preview}`}):null,s.countdown?B(G,{color:Jt(n,s.statusKind),children:` · ${s.countdown}`}):null]},a.id)})]})}function _n({percentage:e}){let t=q(),n=K();return e>=90?B(E,{...n?{}:{borderStyle:`single`,borderColor:t.border.error},paddingX:1,children:V(G,{color:t.text.error,bold:!0,children:[`⚠ Context at `,Math.round(e),`% — window nearly full. Run /compact to summarize the conversation.`]})}):e>=70?B(E,{paddingX:1,children:V(G,{color:t.text.warning,children:[`Context at `,Math.round(e),`% — consider running /compact to free up space.`]})}):null}function vn({entry:e,page:t,loading:n,error:r}){let i=q(),a=nn(e,{selectedEntryId:e.id}),o=t?.records.slice(-12)??[];return V(E,{flexDirection:`column`,marginBottom:1,children:[B(G,{color:i.text.accent,bold:!0,children:`Viewing ${a.title}`}),V(G,{dimColor:!0,children:[a.statusLabel,a.subtitle?` · ${a.subtitle}`:``,a.preview?` · ${a.preview}`:``]}),n?B(G,{dimColor:!0,children:`Loading workspace detail...`}):null,r?B(G,{color:i.text.error,children:r}):null,!n&&!r&&o.length===0?B(G,{dimColor:!0,children:`No detail yet`}):null,!n&&!r&&o.map(e=>{let{symbol:t,color:n}=yn(e.kind,i);return V(G,{color:n,children:[t?`${t} `:``,rn(e)]},e.id)}),t?.nextCursor?B(G,{dimColor:!0,children:`... more detail available`}):null]})}function yn(e,t){return e===`error`?{symbol:qt.error,color:Jt(t,`error`)}:e===`result`?{symbol:qt.success,color:Jt(t,`success`)}:e===`group_summary`?{symbol:`▸`,color:t.text.accent}:e===`process_output`?{symbol:`·`,color:t.text.emphasis}:{symbol:``,color:void 0}}function bn(e=0){return{selectedIndex:e,scrollOffset:0,resolved:!1}}function xn(){return{buffer:``,invalid:!1,resolved:!1}}function Sn(e,t,n,r){if(e.resolved)return{state:e,effect:{type:`none`}};if(n.escape===!0&&r.cancellable===!0)return{state:{...e,resolved:!0},effect:{type:`cancel`}};if(n.backspace===!0||n.delete===!0)return{state:{...e,buffer:e.buffer.slice(0,-1)},effect:{type:`none`}};if(n.return===!0){if(r.multi===!0&&e.buffer===``)return{state:{...e,invalid:!1,resolved:!0},effect:{type:`confirm`}};let t=Number.parseInt(e.buffer,10)-1;return!Number.isInteger(t)||t<0||t>=r.itemCount?{state:{...e,buffer:``,invalid:!0},effect:{type:`none`}}:{state:{...e,buffer:``,invalid:!1,resolved:r.multi!==!0&&r.repeatable!==!0},effect:{type:`select`,index:t}}}return/^[0-9]+$/.test(t)?{state:{...e,buffer:e.buffer+t,invalid:!1},effect:{type:`none`}}:{state:e,effect:{type:`none`}}}function Cn(e,t,n){if(e.resolved)return{state:e,effect:{type:`none`}};if(t===`cancel`)return{state:{...e,resolved:!0},effect:{type:`cancel`}};if(n.enabled===!1||n.itemCount===0)return{state:e,effect:{type:`none`}};if(t===`select`){let t=Dn(e.selectedIndex,n.itemCount);return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`select`,index:t}}}let r=Tn(e.selectedIndex,t,n),i=En(r,e.scrollOffset,n);return{state:{...e,selectedIndex:r,scrollOffset:i},effect:{type:`none`}}}function wn(e,t){if(t.itemCount===0)return{...e,selectedIndex:0,scrollOffset:0};let n=Dn(e.selectedIndex,t.itemCount),r=En(n,e.scrollOffset,t);return n===e.selectedIndex&&r===e.scrollOffset?e:{...e,selectedIndex:n,scrollOffset:r}}function Tn(e,t,n){return t===`previous`?n.wrap===!0&&e===0?n.itemCount-1:Math.max(0,e-1):n.wrap===!0&&e===n.itemCount-1?0:Math.min(n.itemCount-1,e+1)}function En(e,t,n){let r=n.maxVisible??n.itemCount;return r<=0?0:e<t?e:e>=t+r?e-r+1:Math.max(0,t)}function Dn(e,t){return Math.min(Math.max(e,0),t-1)}function On({entries:e,selectedEntryId:t,onSelect:n,onClose:r}){let[i,a]=R(()=>bn()),o=L(i);F(()=>{let n=An({selectedIndex:Math.max(0,e.findIndex(e=>e.id===t)),itemCount:e.length});o.current=n,a(n)},[e.length,t]);let s=An({selectedIndex:i.selectedIndex,scrollOffset:i.scrollOffset,itemCount:e.length});return s!==i&&(o.current=s),{normalized:s,visibleEntries:e.slice(s.scrollOffset,s.scrollOffset+8),applyAction:kn({entries:e,stateRef:o,setState:a,onSelect:n,onClose:r})}}function kn({entries:e,stateRef:t,setState:n,onSelect:r,onClose:i}){return a=>{let o=Cn(t.current,a,{itemCount:e.length,maxVisible:8}),s=o.effect.type===`select`||o.effect.type===`cancel`?{...o.state,resolved:!1}:o.state;if(t.current=s,n(s),o.effect.type===`cancel`)i();else if(o.effect.type===`select`){let t=e[o.effect.index];t&&r(t.id)}}}function An(e){return wn({selectedIndex:e.selectedIndex,scrollOffset:e.scrollOffset??0,resolved:!1},{itemCount:e.itemCount,maxVisible:8})}function jn(e){let[t,n]=R(xn),r=L(t),{enabled:i,itemCount:a,cancellable:o,multi:s,repeatable:c,onSelect:l,onCancel:u,onConfirm:d}=e,f=N(()=>{let e=xn();r.current=e,n(e)},[]),p=N((e,t)=>{let i=Sn(r.current,e,t,{itemCount:a,...o===!0?{cancellable:!0}:{},...s===!0?{multi:!0}:{},...c===!0?{repeatable:!0}:{}});return r.current=i.state,n(i.state),i.effect.type===`select`?l(i.effect.index):i.effect.type===`cancel`?u?.():i.effect.type===`confirm`&&d?.(),i.effect.type!==`none`},[a,o,s,c,l,u,d]);return De((e,t)=>{if(t.return!==!0&&/[\r\n]/u.test(e)){let n={...t,return:!1};for(let t of e.split(/(\r\n|\r|\n)/u))if(t!==``&&(/^(\r\n|\r|\n)$/u.test(t)?p(``,{...n,return:!0}):p(t,n)))break;return}p(e,t)},{isActive:i}),{buffer:t.buffer,invalid:t.invalid,clear:f}}function Mn(e){return e.map(e=>`${e.keys} ${e.label}`).join(` · `)}function Y({hints:e}){return e.length===0?null:V(G,{dimColor:!0,children:[` `,Mn(e)]})}const Nn={app:[`open-workspace-switcher`],thinking:[`abort`],"background-detail":[`return-to-main`],recovery:[`retry`],"chat-input":[`submit`,`history-previous`,`history-next`,`history-search`,`cursor-left`,`cursor-right`,`delete-backward`,`delete-word`,`delete-line`],"text-input":[`submit`,`cursor-left`,`cursor-right`,`cursor-up`,`cursor-down`,`delete-backward`,`delete-word`,`delete-line`],"autocomplete-menu":[`previous`,`next`,`close`,`accept`,`execute`],"queued-prompt":[`cancel`],"confirm-prompt":[`previous`,`next`,`confirm`,`choose-yes`,`choose-no`],"permission-prompt":[`previous`,`next`,`confirm`,`allow-once`,`allow-session`,`allow-project`,`deny`],"text-prompt":[`submit`,`cancel`,`delete-backward`],"list-picker":[`previous`,`next`,`select`,`cancel`],"menu-select":[`previous`,`next`,`select`,`back`],"multi-select":[`previous`,`next`,`toggle`,`confirm`,`cancel`],"workspace-switcher":[`previous`,`next`,`select`,`close`,`attach`],"background-list":[`previous`,`next`,`open`,`close`],"transport-settings":[`previous`,`next`,`toggle`,`close`],"history-search":[`previous`,`next`,`cycle-scope`,`insert`,`execute`,`cancel`],"theme-picker":[`previous`,`next`,`select`,`toggle-syntax`,`toggle-motion`,`cancel`]},Pn={app:{"open-workspace-switcher":[`ctrl+b`]},thinking:{abort:[`escape`]},"background-detail":{"return-to-main":[`escape`]},recovery:{retry:[`enter`]},"chat-input":{submit:[`enter`],"history-previous":[`up`],"history-next":[`down`],"history-search":[`ctrl+r`],"cursor-left":[`left`],"cursor-right":[`right`],"delete-backward":[`backspace`,`delete`],"delete-word":[`ctrl+w`],"delete-line":[`ctrl+u`]},"text-input":{submit:[`enter`],"cursor-left":[`left`],"cursor-right":[`right`],"cursor-up":[`up`],"cursor-down":[`down`],"delete-backward":[`backspace`,`delete`],"delete-word":[`ctrl+w`],"delete-line":[`ctrl+u`]},"autocomplete-menu":{previous:[`up`],next:[`down`],close:[`escape`],accept:[`tab`],execute:[`enter`]},"queued-prompt":{cancel:[`backspace`,`delete`]},"confirm-prompt":{previous:[`left`,`up`],next:[`right`,`down`],confirm:[`enter`],"choose-yes":[`y`],"choose-no":[`n`]},"permission-prompt":{previous:[`left`,`up`],next:[`right`,`down`],confirm:[`enter`],"allow-once":[`y`],"allow-session":[`s`,`a`],"allow-project":[`p`],deny:[`n`,`d`]},"text-prompt":{submit:[`enter`],cancel:[`escape`],"delete-backward":[`backspace`,`delete`]},"list-picker":{previous:[`up`],next:[`down`],select:[`enter`],cancel:[`escape`]},"menu-select":{previous:[`up`],next:[`down`],select:[`enter`],back:[`escape`]},"multi-select":{previous:[`up`],next:[`down`],toggle:[`space`],confirm:[`enter`],cancel:[`escape`]},"workspace-switcher":{previous:[`up`],next:[`down`],select:[`enter`],close:[`ctrl+b`,`escape`],attach:[`a`]},"background-list":{previous:[`up`],next:[`down`],open:[`enter`],close:[`escape`]},"transport-settings":{previous:[`up`],next:[`down`],toggle:[`space`],close:[`enter`,`escape`]},"history-search":{previous:[`up`],next:[`down`,`ctrl+r`],"cycle-scope":[`ctrl+s`],insert:[`enter`,`tab`],execute:[`ctrl+e`],cancel:[`escape`]},"theme-picker":{previous:[`up`],next:[`down`],select:[`enter`],"toggle-syntax":[`s`],"toggle-motion":[`m`],cancel:[`escape`]}},Fn=new Set([`chat-input`,`text-input`,`text-prompt`,`history-search`]),In={ctrl:`ctrl`,control:`ctrl`,alt:`alt`,option:`alt`,meta:`meta`,cmd:`meta`,command:`meta`,shift:`shift`},Ln=[`ctrl`,`alt`,`meta`,`shift`],Rn={return:`enter`,enter:`enter`,esc:`escape`,escape:`escape`,tab:`tab`,space:`space`,spacebar:`space`,up:`up`,down:`down`,left:`left`,right:`right`,backspace:`backspace`,delete:`delete`};function zn(e){let t=e.trim().split(/\s+/u);if(t.length<1||t.length>2)return;let n=t.map(Bn);return n.every(e=>e!==void 0)?n.join(` `):void 0}function Bn(e){if(!e||e.includes(` `))return;let t=e.split(`+`);if(t.some(e=>e.length===0))return;let n=t.at(-1);if(n===void 0)return;let r=new Set;for(let e of t.slice(0,-1)){let t=In[e.toLowerCase()];if(t===void 0||r.has(t))return;r.add(t)}let i=Rn[n.toLowerCase()];if(i===void 0){if([...n].length!==1||/\s/u.test(n))return;i=n.toLowerCase(),t.length===1&&n!==i&&r.add(`shift`)}return[...Ln.filter(e=>r.has(e)),i].join(`+`)}function Vn(e,t){if(/^[\r\n]*\n[\r\n]*$/u.test(e))return`ctrl+j`;let n=t.return?`enter`:t.escape?`escape`:t.tab?`tab`:t.upArrow?`up`:t.downArrow?`down`:t.leftArrow?`left`:t.rightArrow?`right`:t.backspace?`backspace`:t.delete?`delete`:e===` `?`space`:[...e].length===1?e.toLowerCase():void 0;if(n!==void 0)return[...t.ctrl?[`ctrl`]:[],...t.meta?[`meta`]:[],...t.shift?[`shift`]:[],n].join(`+`)}function Hn(e,t){let n=Vn(e,t);return n===void 0?[]:n===`enter`?[`enter`,`ctrl+m`]:n===`tab`?[`tab`,`ctrl+i`]:n===`escape`?[`escape`,`ctrl+[`]:[n]}function Un(e){return e.split(` `).map(e=>e===`ctrl+m`?`enter`:e===`ctrl+i`?`tab`:e===`ctrl+[`?`escape`:e).join(` `)}function Wn(e){return e.split(` `).map(e=>e.split(`+`).map(e=>({ctrl:`Ctrl`,alt:`Alt`,meta:`Meta`,shift:`Shift`,escape:`Esc`,up:`↑`,down:`↓`,left:`←`,right:`→`})[e]??(e.length===1?e.toUpperCase():`${e[0]?.toUpperCase()}${e.slice(1)}`)).join(`+`)).join(` `)}function X(e,t,n){return{ok:!1,diagnostic:{file:e,path:t,message:n}}}function Gn(){return Object.fromEntries(Object.entries(Pn).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([e,t])=>[e,[...t]]))]))}function Kn(e){if(e===null)return null;if(typeof e==`string`)return[e];if(Array.isArray(e)&&e.length>0&&e.every(e=>typeof e==`string`))return e}function qn(e,t,n){let r=new Map,i=new Map;for(let[a,o]of Object.entries(t))for(let t of o){let o=Un(t),s=r.get(o),c=`$.bindings.${e}.${a}`;if(s!==void 0&&s!==a)return X(n,c,`Binding duplicates action ${s}.`);let l=o.split(` `);if(l.length>1&&Fn.has(e)&&Jn(l[0]??``))return X(n,c,`Printable text cannot begin a chord in a text context.`);r.set(o,a),l.length>1&&i.set(l[0]??``,a)}for(let[t,a]of r){let r=i.get(t);if(r!==void 0)return X(n,`$.bindings.${e}.${r}`,`Chord prefix collides with action ${a}.`)}}function Jn(e){return!e.includes(`+`)&&[...e].length===1}function Yn(e,t){let n=[];return e.split(` `).includes(`ctrl+b`)&&n.push({code:`multiplexer-conflict`,path:t,message:`Ctrl+B may be captured by a terminal multiplexer.`}),/ctrl\+shift\+[a-z]/u.test(e)&&n.push({code:`modifier-delivery`,path:t,message:`This terminal may not distinguish Ctrl+Shift from Ctrl.`}),n}function Xn(e,t){let n;try{n=JSON.parse(e)}catch(e){return X(t,`$`,e instanceof Error?e.message:`Invalid JSON.`)}if(!Tt(n))return X(t,`$`,`Expected an object.`);if(n.version!==1)return X(t,`$.version`,`Expected version 1.`);if(!Tt(n.bindings))return X(t,`$.bindings`,`Expected an object.`);let r=Gn(),i=[];for(let[e,a]of Object.entries(n.bindings)){if(!(e in Nn))return X(t,`$.bindings.${e}`,`Unknown keybinding context.`);let n=e;if(!Tt(a))return X(t,`$.bindings.${n}`,`Expected an action object.`);for(let[e,o]of Object.entries(a)){if(!Nn[n].includes(e))return X(t,`$.bindings.${n}.${e}`,`Unknown action.`);let a=Kn(o),s=`$.bindings.${n}.${e}`;if(a===void 0)return X(t,s,`Expected a binding, binding list, or null.`);if(a===null){r[n][e]=[];continue}let c=[];for(let e of a){let n=zn(e);if(n===void 0)return X(t,s,`Invalid binding syntax.`);if(n.split(` `).includes(`ctrl+c`))return X(t,s,`Ctrl+C is reserved for two-stage shutdown.`);c.push(n),i.push(...Yn(n,s))}r[n][e]=c}}for(let e of Object.keys(r)){let n=qn(e,r[e],t);if(n!==void 0)return n}let a=Object.freeze(Object.fromEntries(Object.entries(r).map(([e,t])=>[e,Object.freeze(Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Object.freeze(t)])))])));return{ok:!0,snapshot:Object.freeze({generation:0,sourcePath:t,bindings:a,warnings:Object.freeze(i)})}}function Zn(){return{strokes:[]}}function Qn(e,t){return Object.entries(e.bindings[t])}function $n(e){let t=Hn(e.input,e.key);if(t.length===0)return{state:Zn(),actions:[],consumed:!1};let n=e.state.context===e.context&&e.state.generation===e.snapshot.generation&&(e.state.deadline===void 0||e.now<=e.state.deadline)&&!e.key.escape?e.state.strokes:[],r=Qn(e.snapshot,e.context);for(let i of t){let t=[...n,i].join(` `),a=r.filter(([,e])=>e.includes(t)).map(([e])=>e);if(a.length>0)return{state:Zn(),actions:a,consumed:!0};if(r.some(([,e])=>e.some(e=>e.startsWith(`${t} `))))return{state:{context:e.context,generation:e.snapshot.generation,strokes:[...n,i],deadline:e.now+1e3},actions:[],consumed:!0}}return n.length>0?$n({...e,state:Zn()}):{state:Zn(),actions:[],consumed:!1}}function er(e,t,n){return n.flatMap(([n,r])=>{let i=Array.isArray(n),a=(i?n:[n]).flatMap(n=>{let r=e.bindings[t][n]??[];return i?r.slice(0,1):r}),o=a.map(Wn),s=o.every(e=>/^[↑↓←→]$/u.test(e))?o.join(``):o.join(`/`);return a.length===0?[]:[{keys:s,label:r}]})}const tr=Xn(`{"version":1,"bindings":{}}`,`<defaults>`);if(!tr.ok)throw Error(tr.diagnostic.message);const nr=tr.snapshot,rr=M(nr);function ir({source:e,children:t}){let[n,r]=R(()=>e?.getSnapshot()??nr);return F(()=>{if(e!==void 0)return r(e.getSnapshot()),e.subscribe(r)},[e]),B(rr.Provider,{value:n,children:t})}function ar(){return P(rr)}function Z(e,t){return er(ar(),e,t)}function Q(e,t,n={}){let r=ar(),i=L(Zn()),a=L(Zn()),{fallbackContext:o}=n;F(()=>{i.current=Zn(),a.current=Zn()},[e,o,r.generation]),De((n,s)=>{let c=$n({snapshot:r,state:i.current,context:e,input:n,key:s,now:Date.now()});if(i.current=c.state,o===void 0||c.consumed){a.current=Zn(),t(c.actions,n,s,c.consumed,e);return}let l=$n({snapshot:r,state:a.current,context:o,input:n,key:s,now:Date.now()});a.current=l.state,t(l.actions,n,s,l.consumed,o)},{isActive:n.isActive??!0})}function or(e,t){let n=`Enter selection (1-${e})`;return t?`${n} or Escape to cancel`:n}function sr(e){return`${e+1}. `}function cr({itemCount:e,cancellable:t=!1,buffer:n=``,invalid:r=!1}){if(e===0)return null;let i=or(e,t);return V(z,{children:[V(G,{children:[i,n.length>0?` ${n}`:``]}),r&&B(G,{children:i})]})}function lr({title:e,description:t,options:n,cancellable:r=!1,buffer:i=``,invalid:a=!1}){return V(E,{flexDirection:`column`,children:[e!==void 0&&e.length>0&&B(G,{children:e}),t!==void 0&&t.length>0&&B(G,{children:t}),n.map((e,t)=>V(G,{children:[sr(t),e]},`${t}-${e}`)),B(cr,{itemCount:n.length,cancellable:r,buffer:i,invalid:a})]})}function ur(e){return e?.controls.includes(`attach`)===!0}function dr({snapshot:e,selectedEntryId:t,onSelect:n,onClose:r,onAttach:i}){let a=q(),o=[...e?.entries??[]],{normalized:s,visibleEntries:c,applyAction:l}=On({entries:o,selectedEntryId:t,onSelect:n,onClose:r}),u=o[s.selectedIndex],d=i!==void 0&&ur(u),f=K(),p=jn({enabled:f&&o.length>0,itemCount:o.length,cancellable:!0,onSelect:e=>{let t=o[e];t&&n(t.id)},onCancel:r});Q(`workspace-switcher`,e=>{for(let t of e)t===`attach`&&d&&u?(i(u),r()):t===`previous`||t===`next`||t===`select`?l(t):t===`close`&&l(`cancel`)},{isActive:!f});let m=Z(`workspace-switcher`,[[[`previous`,`next`],`Navigate`],[`select`,`Switch`],[`close`,`Close`]]),h=Z(`workspace-switcher`,[[`attach`,`Attach`]]);return V(E,{flexDirection:`column`,...f?{}:{borderStyle:`round`,borderColor:a.border.focused},paddingX:1,children:[B(G,{color:a.text.accent,bold:!0,children:`Execution workspace`}),B(E,{flexDirection:`column`,marginTop:1,children:c.length===0?B(G,{dimColor:!0,children:`No workspace entries`}):f?o.map((e,n)=>B(pr,{entry:e,isFocused:!1,selectedEntryId:t,rowNumber:n},e.id)):c.map((e,n)=>B(pr,{entry:e,isFocused:s.scrollOffset+n===s.selectedIndex,selectedEntryId:t},e.id))}),f?B(fr,{itemCount:o.length,buffer:p.buffer,invalid:p.invalid}):B(Y,{hints:d?[...m,...h]:m})]})}function fr({itemCount:e,buffer:t,invalid:n}){let r=or(e,!0);return V(E,{flexDirection:`column`,children:[V(G,{children:[r,t.length>0?` ${t}`:``]}),n&&B(G,{children:r})]})}function pr({entry:e,isFocused:t,selectedEntryId:n,rowNumber:r}){let i=q(),a=nn(e,{selectedEntryId:n});return V(G,{children:[B(G,{color:t?i.text.accent:void 0,bold:t,children:r===void 0?t?`> `:` `:sr(r)}),B(G,{color:Jt(i,a.statusKind),children:`${a.radio} ${a.state}`}),B(G,{color:t?i.text.accent:void 0,bold:t,children:` ${a.title}`}),B(G,{dimColor:!0,children:` · ${a.statusLabel}`}),a.subtitle?B(G,{dimColor:!0,children:` · ${a.subtitle}`}):null,a.preview?B(G,{dimColor:!0,children:` · ${a.preview}`}):null]})}function mr(e,t,n){let r=0;for(let i=0;i<t&&i<e.length;i++){let t=je(e[i]),a=r%n;a+t>n&&(r+=n-a),r+=t}return r}function hr(e,t,n){let r=0;for(let i=0;i<e.length;i++){if(r>=t)return i;let a=je(e[i]),o=r%n;o+a>n&&(r+=n-o),r+=a}return e.length}function gr(e,t,n){if(!n||n<=0)return{state:e,effect:{type:`none`}};let r=[...e.value],i=mr(r,e.cursor,n),a=t===`up`?i-n:i+n;if(a<0)return{state:e,effect:{type:`none`}};let o=hr(r,a,n);return o===e.cursor?{state:e,effect:{type:`none`}}:{state:{...e,cursor:o},effect:{type:`render`}}}function _r(e,t){return t===`left`&&e.cursor>0?{state:{...e,cursor:e.cursor-1},effect:{type:`render`}}:t===`right`&&e.cursor<e.value.length?{state:{...e,cursor:e.cursor+1},effect:{type:`render`}}:{state:e,effect:{type:`none`}}}function vr(e,t){if(!(t<=0))return{value:e.slice(0,t-1)+e.slice(t),cursor:t-1,deleted:e.slice(t-1,t)}}function yr(e,t){if(t<=0)return;let n=t;for(;n>0&&/\s/u.test(e[n-1]??``);)--n;for(;n>0&&!/\s/u.test(e[n-1]??``);)--n;if(n!==t)return{value:e.slice(0,n)+e.slice(t),cursor:n,deleted:e.slice(n,t)}}function br(e,t){if(!(t<=0))return{value:e.slice(t),cursor:0,deleted:e.slice(0,t)}}const xr=`[200~`,Sr=`[201~`;function Cr(e){return{value:e,cursor:e.length,isPasting:!1,pasteBuffer:``}}function wr(e,t,n){return t===e.value?e:{...e,value:t,cursor:n==null?t.length:Math.min(n,t.length)}}function Tr(e,t,n,r){let i=Dr(e,t,r);if(i!==void 0)return i;let a=Or(e,t,n,r);if(a!==void 0)return a;let o=kr(e,n,r);return o===void 0?Fr(e,t):o}function Er(e,t,n){let r=t.replace(/\r\n?/g,`
13
13
  `);return r.length===0?{state:e,effect:{type:`none`}}:r.includes(`
14
- `)&&n.canPaste?{state:e,effect:{type:`paste`,text:r,cursor:e.cursor}}:Nr(e,r)}function Tr(e,t,n){if(t===yr||t.startsWith(yr))return Ar(e,t);if(e.isPasting)return jr(e,t,n)}function Er(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 Mr(e,(n===`word`?_r:vr)(e.value,e.cursor),n)}if(n.return===!0)return{state:e,effect:{type:`submit`,value:e.value}};if(t.length>1&&(t.includes(`
14
+ `)&&n.canPaste?{state:e,effect:{type:`paste`,text:r,cursor:e.cursor}}:Fr(e,r)}function Dr(e,t,n){if(t===xr||t.startsWith(xr))return Mr(e,t);if(e.isPasting)return Nr(e,t,n)}function Or(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 Pr(e,(n===`word`?yr:br)(e.value,e.cursor),n)}if(n.return===!0)return{state:e,effect:{type:`submit`,value:e.value}};if(t.length>1&&(t.includes(`
15
15
  `)||t.includes(`\r`))&&r.canPaste)return{state:e,effect:{type:`paste`,text:t.replace(/\r\n?/g,`
16
- `),cursor:e.cursor}}}function Dr(e,t,n){if(t.upArrow===!0||t.downArrow===!0)return n.enableVerticalNavigation===!1?{state:e,effect:{type:`none`}}:mr(e,t.upArrow===!0?`up`:`down`,n.availableWidth);if(t.leftArrow===!0)return hr(e,`left`);if(t.rightArrow===!0)return hr(e,`right`);if(t.backspace===!0||t.delete===!0)return Mr(e,gr(e.value,e.cursor))}function Or(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 kr(e,t,n){return{value:e.slice(0,t)+n+e.slice(t),cursor:t+n.length}}function Ar(e,t){return{state:{...e,isPasting:!0,pasteBuffer:t.slice(5)},effect:{type:`none`}}}function jr(e,t,n){if(t!==br&&!t.includes(br))return{state:{...e,pasteBuffer:e.pasteBuffer+t},effect:{type:`none`}};let r=t.split(br)[0]??``;return wr({...e,isPasting:!1,pasteBuffer:``},e.pasteBuffer+r,n)}function Mr(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 Nr(e,t){let n=Or(t);if(n.length===0)return{state:e,effect:{type:`none`}};let r=kr(e.value,e.cursor,n);return{state:{...e,value:r.value,cursor:r.cursor},effect:{type:`change`,value:r.value}}}function Pr(){return{timer:null,isSubmitting:!1}}function Fr(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 Ir(e,t=clearTimeout){e.timer!==null&&(t(e.timer),e.timer=null),e.isSubmitting=!1}function Lr(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=fr(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 Rr(e){return!(!e.capability||!e.hasMeasured||e.viewportRows<=0||e.frameHeight<=0||e.frameHeight>=e.viewportRows||e.y<0||e.y>=e.frameHeight)}function zr(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 Br(e,t){return e===void 0||t===void 0?e===t:e.x===t.x&&e.y===t.y&&e.frameHeight===t.frameHeight}function Vr(e){let{setCursorPosition:t}=k(),n=Ce(e.boxRef),{rows:r}=A(),[i,a]=R(void 0);F(()=>{let t=e.boxRef.current,n=t===null?void 0:zr(t);a(e=>Br(e,n)?e:n)});let o=i!==void 0&&e.enabled?Lr({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&&Rr({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 Hr=M({armEchoRelease(){},write(e){process.stdout.write(e)}});function Ur({port:e,children:t}){return B(Hr.Provider,{value:e,children:t})}function Wr(){return P(Hr)}const Gr=M({});function Kr({overrides:e,children:t}){return B(Gr.Provider,{value:e??{},children:t})}function qr(){return P(Gr)}function Jr({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=L(xr(e)),[,p]=R(0),m=L(Pr());F(()=>()=>Ir(m.current),[]),f.current=Sr(f.current,e,c),Xr({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=I(()=>J(h.text.muted),[h.text.muted]),_=L(null),ee=qr(),{realCursorActive:te}=Vr({boxRef:_,enabled:a&&o&&Ye({override:ee.imeCursorPositioning}),value:f.current.value,cursor:f.current.cursor,...s===void 0?{}:{availableWidth:s}});return B(D,{ref:_,children:B(Be,{children:ti(f.current.value,f.current.cursor,i,o&&a&&!te,g)})})}function Yr(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 Xr(e){let t=Wr();Te(n=>{t.armEchoRelease(),$r(e,()=>wr(e.stateRef.current,n,Qr(e)))},{isActive:e.focus}),Q(e.keybindingContext,(n,r,i,a,o)=>{let s=Zr(o,n,r,i,a);s!==void 0&&(Yr(n[0],s)&&t.armEchoRelease(),$r(e,()=>Cr(e.stateRef.current,s.input,s.key,Qr(e))))},{isActive:e.focus,...e.keybindingContext===`autocomplete-menu`?{fallbackContext:`chat-input`}:{}})}function Zr(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 Qr(e){return{availableWidth:e.availableWidth,canPaste:e.onPaste!==void 0,enableVerticalNavigation:e.enableVerticalNavigation}}function $r(e,t){try{let n=t();e.stateRef.current=n.state,ei(e,n.effect)}catch{}}function ei(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&&Fr(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 ti(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?T.inverse(o[0])+i(o.slice(1)):T.inverse(` `);let s=[...a],c=``;for(let e=0;e<s.length;e++){let n=s[e]??``;c+=e===t?T.inverse(n):n}return t>=s.length&&(c+=T.inverse(` `)),c}const ni=`Prompt from an external link`;function ri(e){if(e.length!==0)return e.length>1e3?`${ni} — ${e.length} characters; scroll and review the full text before sending`:ni}function ii({value:e}){let t=ri(e);return t===void 0?null:B(G,{dimColor:!0,children:t})}function ai(){return{selectedIndex:null,draft:``}}function oi(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:ai()}}function si(e,t){let n=t.trim();return n.length===0||e[e.length-1]===n?[...e]:[...e,n]}function ci(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=si(t,e.content))}return t}function li(e,t,n){return t===0?0:n===`previous`?e>0?e-1:t-1:e<t-1?e+1:0}function ui(e,t){if(le(e)&&e.slice(1).includes(` `)){let{name:n}=l(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(le(e)&&e.slice(1).includes(` `)){let{name:n}=l(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 fi(e,t,n,r){let i=r.split(`
17
- `).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 pi(e){return e.trim().length>0}const mi=[`all`,`session`,`project`];function hi(e){let t=mi.indexOf(e);return mi[(t+1)%mi.length]??`all`}function gi(e,t,n){switch(t){case`all`:return!0;case`session`:return e.sessionId===n.sessionId;case`project`:return e.project===n.project}}function _i(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 vi(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 yi(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 bi(e,t){return t<=8||e<8?0:Math.min(e-8+1,t-8)}function xi(e){return`${e} unreadable ${e===1?`line`:`lines`} skipped`}function Si(e){let t=q(),{match:n,selected:r,rowNumber:i,color:a}=e,o=i===void 0?r?`> `:` `:ar(i),s=yi(n.entry.text.replace(/\r\n|[\r\n]/gu,e=>e.length===2?` ↵`:`↵`),n.ranges);return V(G,{color:r?t.text.accent:void 0,dimColor:!r,wrap:`truncate-end`,children:[o,s.map((e,t)=>e.matched?B(G,{bold:!0,inverse:a,children:a?e.text:`[${e.text}]`},t):B(G,{children:e.text},t))]})}function Ci({view:e}){let t=q();if(e.error!==void 0)return V(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(xi(e.skippedLines)),B(G,{dimColor:!0,children:n.join(` · `)})}function wi({view:e}){let t=q(),n=K(),r=Je(),i=Z(`history-search`,[[[`previous`,`next`],`Navigate`],[`cycle-scope`,`Scope`],[`insert`,`Insert`],[`execute`,`Run`],[`cancel`,`Close`]]);if(!e.open)return null;let a=bi(e.selectedIndex,e.matches.length),o=e.matches.slice(a,a+8);return V(D,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.muted},paddingX:1,children:[V(G,{children:[B(G,{color:t.text.accent,children:`(reverse-i-search)`}),` scope: `,e.scope,` · query:`,` `,e.query]}),o.map((t,i)=>B(Si,{match:t,selected:a+i===e.selectedIndex,rowNumber:n?a+i:void 0,color:r},`${t.entry.at}:${a+i}`)),B(Ci,{view:e}),B(Y,{hints:i})]})}function Ti(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 Ei(e,t){let[n,r]=R(0),[i,a]=R(!1),o=j.useRef(e);o.current!==e&&(o.current=e,i&&a(!1));let s=Ti(e),c=s.isSlash&&s.parentCommand.length>0,l=j.useRef(s.parentCommand);F(()=>{l.current!==s.parentCommand&&(l.current=s.parentCommand,r(0))},[s.parentCommand]);let u=I(()=>{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 Di={entries:[],skippedLines:0};function Oi(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 ki(e,t){return[...e].reverse().map(e=>({at:``,sessionId:t.sessionId,project:t.project,text:e}))}const Ai=()=>new Promise(e=>setImmediate(e));async function ji(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 Ai())}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 Mi(e,t){let[n,r]=R(Di),[i,a]=R(!1),[o,s]=R(void 0),c=L(void 0),l=L(Di),u=N(()=>r(l.current),[]),d=N(()=>{c.current?.abort(),c.current=void 0,a(!1)},[]),f=N(()=>{if(d(),l.current=Di,r(Di),s(void 0),e===void 0)return;let n=new AbortController;c.current=n,a(!0),ji({source:e.source,signal:n.signal,pending:l,publishEachBlock:!t,publish:u,setError:s,setLoading:a})},[u,t,d,e]);return F(()=>d,[d]),{loaded:n,loading:i,error:o,start:f,stop:d,publish:u}}function Ni(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(hi(e.scope)),e.setSelectedIndex(0)):!s&&(o.backspace||o.delete)?t(e=>e.slice(0,-1)):!s&&Oi(a,o)&&t(e=>e+a)},{isActive:e.open})}function Pi(e,t,n,r,i){let a=t?.sessionId,o=t?.project;return I(()=>{if(!e||a===void 0||o===void 0)return[];let t={sessionId:a,project:o};return _i(n===`session`?ki(r,t):i.filter(e=>gi(e,n,t)))},[i,e,o,n,a,r])}const Fi={query:``,scope:`all`,selectedIndex:0};function Ii(){let[e,t]=R(Fi);return{state:e,reset:N(()=>t(Fi),[]),setters:I(()=>({setScope:e=>t(t=>({...t,scope:e})),setSelectedIndex:e=>t(t=>({...t,selectedIndex:e})),setQuery:e=>t(t=>({...t,query:e(t.query)}))}),[])}}function Li(e,t,n,r){let[i,a]=R(!1);return{open:i,openSearch:N(()=>{!t||i||(n(),a(!0),r?.(!0),e.start())},[t,e,r,i,n]),closeSearch:N(()=>{e.stop(),a(!1),r?.(!1)},[e,r])}}function Ri(e){let t=K(),n=Mi(e.surface,t),{state:r,reset:i,setters:a}=Ii(),{query:o,scope:s}=r,{surface:c,onInsert:l,onExecute:u}=e,{open:d,openSearch:f,closeSearch:p}=Li(n,c!==void 0,i,e.onOpenChange),m=Pi(d,c,s,e.sessionPrompts,n.loaded.entries),h=I(()=>vi(m,o),[m,o]),g=Math.min(r.selectedIndex,Math.max(0,h.length-1));Ni({open:d,matches:h,selected:g,scope:s,screenReader:t,loader:n,close:p,onInsert:l,onExecute:u,...a});let{loading:_,error:ee,loaded:te}=n;return{view:{...r,open:d,selectedIndex:g,matches:h,loading:_,error:ee,skippedLines:te.skippedLines},openSearch:f,closeSearch:p}}function zi(e){let{historySearch:t,setValue:n,setCursorHint:r,submitPrompt:i,composerActive:a}=e,o=N(e=>{n(e),r(null)},[r,n]),s=N(e=>{n(``),i(e)},[n,i]),{view:c,openSearch:l,closeSearch:u}=Ri({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}),F(()=>{c.open&&!a&&u()},[u,a,c.open]),c}function Bi(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=>li(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 Vi(e){let{showPopup:t,isDisabled:n,isQueueCancellationDisabled:r,pendingPrompt:i,searchOpen:a}=e;Bi(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=oi(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 Hi(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 Ui(e){return`[deleted: ${e}]`}function Wi({screenReader:e,innerWidth:t,borderColor:n,sessionName:r}){let i=q();if(e)return null;let a=Hi(t,r);return V(G,{color:n,children:[a.left,a.label?B(G,{backgroundColor:n,color:i.text.onAccent,bold:!0,children:a.label}):null,a.right]})}function Gi({screenReader:e,innerWidth:t,borderColor:n}){return e?null:B(G,{color:n,children:`─`.repeat(t)})}function Ki({deleted:e}){return e===null?null:B(G,{children:Ui(e)})}function qi(){let{stdout:e}=Ee(),t=()=>Math.max(40,(e.columns??80)-4),[n,r]=R(t);return F(()=>{let n=()=>r(t());return e.on(`resize`,n),()=>{e.off(`resize`,n)}},[e]),n}function Ji(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e.padEnd(t)}function Yi(e){let t=q(),{cmd:n,isSelected:r,showSlash:i,rowWidth:a,nameColWidth:o,rowNumber:s}=e,c=s===void 0?r?`> `:` `:ar(s),l=r?t.text.accent:void 0,u=!r,d=Ji(n.name,o);return B(D,{width:a,children:B(G,{color:l,dimColor:u,wrap:`truncate-end`,children:i?`${c}/${d} ${n.description??``}`:`${c}${d} ${n.description??``}`})})}function Xi({commands:e,selectedIndex:t,visible:n,isSubcommandMode:r}){let i=q(),a=qi(),o=K(),s=Z(`autocomplete-menu`,[[[`previous`,`next`],`Navigate`],[`accept`,`Complete`],[`execute`,`Select`],[`close`,`Close`]]);if(!n||e.length===0)return null;let c=Zi(t,e.length),l=e.slice(c,c+8),u=Math.min(20,Math.max(...l.map(e=>e.name.length)));return V(D,{flexDirection:`column`,...o?{}:{borderStyle:`round`,borderColor:i.border.muted},paddingX:1,children:[l.map((e,n)=>B(Yi,{cmd:e,isSelected:c+n===t,showSlash:!r,rowWidth:a,nameColWidth:u,...o?{rowNumber:c+n}:{}},e.name)),B(Y,{hints:s})]})}function Zi(e,t){if(t<=8||e<8)return 0;let n=t-8;return Math.min(e-8+1,n)}const Qi=/\[Pasted text #(\d+)(?: \+\d+ lines)?\]/g;function $i(e,t){return e.replace(Qi,(e,n)=>t.get(Number(n))??``)}function ea({text:e}){let t=K(),n=q(),r=rt(),i=it(),[a,o]=R(0);return F(()=>{if(!i)return;let e=setInterval(()=>{o(e=>e+1)},400);return()=>clearInterval(e)},[i]),t?B(G,{children:e}):i?B(G,{children:[...e].map((e,t)=>{let n=Math.floor(t/4),i=(a+n)%r.wave.length;return B(G,{color:r.wave[i],children:e},t)})}):B(G,{color:n.text.muted,children:e})}function ta({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,_]=R(f??``),[ee]=R(m===!0?f??``:``);F(()=>{f!==void 0&&f.length!==0&&p?.()},[f,p]);let[te,v]=R(null),y=K(),[b,ne]=R(null),[re,ie]=R(ai),[ae,oe]=R([]),se=I(()=>ci(l??[]),[l]),x=I(()=>ae.reduce((e,t)=>si(e,t),se),[se,ae]),ce=L(new Map),{columns:S}=A(),le=S>0?S:80,ue=Math.max(1,le-3),C=L(0),de=Z(`chat-input`,[[`submit`,`Submit`]]),{showPopup:fe,filteredCommands:pe,selectedIndex:w,setSelectedIndex:me,isSubcommandMode:he,setShowPopup:ge}=Ei(g,s),_e=N((e,t)=>{C.current+=1;let n=C.current;ce.current.set(n,e),_(r=>{let i=fi(r,t,n,e);return v(i.cursorHint),i.value})},[]),T=N(()=>{ie(ai())},[]),ve=N(e=>{oe(t=>si(t,e))},[]),E=N(t=>{ve(t),T(),e(t)},[e,ve,T]),ye=N(e=>{let t=ui(g,e);t.type===`insert`&&(_(t.value),t.selectedIndex!==void 0&&me(t.selectedIndex))},[g,me]),be=N(e=>{let t=di(g,e);if(t.type===`insert`){_(t.value),t.selectedIndex!==void 0&&me(t.selectedIndex);return}t.type===`submit`&&(_(``),E(t.value))},[g,E,me]),xe=N(e=>{if(!pi(e))return;if(fe&&pe[w]){be(pe[w]);return}let t=$i(e.trim(),ce.current);_(``),ce.current.clear(),C.current=0,E(t)},[fe,pe,w,be,E]),O=zi({historySearch:d,sessionPrompts:x,composerActive:!fe&&!n&&!a,setValue:_,setCursorHint:v,submitPrompt:E});Vi({value:g,isDisabled:n,searchOpen:O.open,isQueueCancellationDisabled:r??n,pendingPrompt:a,showPopup:fe,setShowPopup:ge,filteredCommands:pe,selectedIndex:w,setSelectedIndex:me,tabCompleteCommand:ye,promptHistory:x,historyState:re,setValue:_,setCursorHint:v,setHistoryState:ie,onRequestFocusBackgroundList:u,onCancelQueue:t});let Se=i?h.border.attention:a?h.border.focused:n?h.border.muted:h.border.active,Ce=Math.max(1,le-0);return V(D,{flexDirection:`column`,children:[fe&&B(Xi,{commands:pe,selectedIndex:w,visible:fe,isSubcommandMode:he}),B(wi,{view:O}),B(Ki,{deleted:y?b:null}),B(Wi,{screenReader:y,innerWidth:Ce,borderColor:Se,...c===void 0?{}:{sessionName:c}}),B(D,{paddingLeft:1,children:i?B(G,{color:h.text.warning,children:` Interrupting...`}):a?V(G,{color:h.text.accent,children:[` `,`Queued:`,` `,a.length>50?a.slice(0,47)+`...`:a,` `,typeof o==`number`&&o>1&&V(G,{dimColor:!0,children:[`(+`,o-1,` co-driver queued) `]}),B(G,{dimColor:!0,children:`(Backspace to cancel)`})]}):n?B(ea,{text:` Waiting for response... (ESC to interrupt)`}):V(D,{children:[B(G,{color:h.text.success,bold:!0,children:`> `}),B(Jr,{value:g,onChange:e=>{_(e),T(),v(null)},onDeletedText:ne,onSubmit:xe,onPaste:_e,placeholder:`Type a message or /help`,availableWidth:ue,cursorHint:te,enableVerticalNavigation:!1,keybindingContext:fe?`autocomplete-menu`:`chat-input`,focus:!O.open})]})}),!y&&!n&&!a&&!O.open&&B(Y,{hints:de}),B(Gi,{screenReader:y,innerWidth:Ce,borderColor:Se}),ee.length>0&&g===ee&&B(ii,{value:g})]})}const na=new Set([`Shell`,`Bash`,`BackgroundProcess`]);function ra(e){if(!na.has(e.toolName)||!e.toolResultData)return;let t=ia(e.toolResultData),n=fa(t,`exitCode`),r=pa(t,`success`),i=ca(sa(aa(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:oa(s,n),previewLines:a,omittedLineCount:o,transcriptHint:o>0?`... +${o} lines (full output in session transcript)`:void 0}}function ia(e){try{return JSON.parse(e)}catch{return e}}function aa(e,t){if(!ua(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(la(i,`[stderr] `)),!r&&!i&&a&&o.push(a),o.join(`
18
- `)}function oa(e,t){return t!==void 0&&t!==0?`exit ${t}`:e?`error`:`ok`}function sa(e){return e?e.replace(/\r\n/g,`
16
+ `),cursor:e.cursor}}}function kr(e,t,n){if(t.upArrow===!0||t.downArrow===!0)return n.enableVerticalNavigation===!1?{state:e,effect:{type:`none`}}:gr(e,t.upArrow===!0?`up`:`down`,n.availableWidth);if(t.leftArrow===!0)return _r(e,`left`);if(t.rightArrow===!0)return _r(e,`right`);if(t.backspace===!0||t.delete===!0)return Pr(e,vr(e.value,e.cursor))}function Ar(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 jr(e,t,n){return{value:e.slice(0,t)+n+e.slice(t),cursor:t+n.length}}function Mr(e,t){return{state:{...e,isPasting:!0,pasteBuffer:t.slice(5)},effect:{type:`none`}}}function Nr(e,t,n){if(t!==Sr&&!t.includes(Sr))return{state:{...e,pasteBuffer:e.pasteBuffer+t},effect:{type:`none`}};let r=t.split(Sr)[0]??``;return Er({...e,isPasting:!1,pasteBuffer:``},e.pasteBuffer+r,n)}function Pr(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 Fr(e,t){let n=Ar(t);if(n.length===0)return{state:e,effect:{type:`none`}};let r=jr(e.value,e.cursor,n);return{state:{...e,value:r.value,cursor:r.cursor},effect:{type:`change`,value:r.value}}}function Ir(){return{timer:null,isSubmitting:!1}}function Lr(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 Rr(e,t=clearTimeout){e.timer!==null&&(t(e.timer),e.timer=null),e.isSubmitting=!1}function zr(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=mr(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 Br(e){return!(!e.capability||!e.hasMeasured||e.viewportRows<=0||e.frameHeight<=0||e.frameHeight>=e.viewportRows||e.y<0||e.y>=e.frameHeight)}function Vr(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 Hr(e,t){return e===void 0||t===void 0?e===t:e.x===t.x&&e.y===t.y&&e.frameHeight===t.frameHeight}function Ur(e){let{setCursorPosition:t}=k(),n=Ee(e.boxRef),{rows:r}=A(),[i,a]=R(void 0);F(()=>{let t=e.boxRef.current,n=t===null?void 0:Vr(t);a(e=>Hr(e,n)?e:n)});let o=i!==void 0&&e.enabled?zr({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&&Br({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 Wr=M({armEchoRelease(){},write(e){process.stdout.write(e)}});function Gr({port:e,children:t}){return B(Wr.Provider,{value:e,children:t})}function Kr(){return P(Wr)}const qr=M({});function Jr({overrides:e,children:t}){return B(qr.Provider,{value:e??{},children:t})}function Yr(){return P(qr)}function Xr({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=L(Cr(e)),[,p]=R(0),m=L(Ir());F(()=>()=>Rr(m.current),[]),f.current=wr(f.current,e,c),Qr({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=I(()=>J(h.text.muted),[h.text.muted]),_=L(null),ee=Yr(),{realCursorActive:te}=Ur({boxRef:_,enabled:a&&o&&Ze({override:ee.imeCursorPositioning}),value:f.current.value,cursor:f.current.cursor,...s===void 0?{}:{availableWidth:s}});return B(E,{ref:_,children:B(He,{children:ri(f.current.value,f.current.cursor,i,o&&a&&!te,g)})})}function Zr(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 Qr(e){let t=Kr();Oe(n=>{t.armEchoRelease(),ti(e,()=>Er(e.stateRef.current,n,ei(e)))},{isActive:e.focus}),Q(e.keybindingContext,(n,r,i,a,o)=>{let s=$r(o,n,r,i,a);s!==void 0&&(Zr(n[0],s)&&t.armEchoRelease(),ti(e,()=>Tr(e.stateRef.current,s.input,s.key,ei(e))))},{isActive:e.focus,...e.keybindingContext===`autocomplete-menu`?{fallbackContext:`chat-input`}:{}})}function $r(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 ei(e){return{availableWidth:e.availableWidth,canPaste:e.onPaste!==void 0,enableVerticalNavigation:e.enableVerticalNavigation}}function ti(e,t){try{let n=t();e.stateRef.current=n.state,ni(e,n.effect)}catch{}}function ni(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&&Lr(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 ri(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?T.inverse(o[0])+i(o.slice(1)):T.inverse(` `);let s=[...a],c=``;for(let e=0;e<s.length;e++){let n=s[e]??``;c+=e===t?T.inverse(n):n}return t>=s.length&&(c+=T.inverse(` `)),c}const ii=`Prompt from an external link`;function ai(e){if(e.length!==0)return e.length>1e3?`${ii} — ${e.length} characters; scroll and review the full text before sending`:ii}function oi({value:e}){let t=ai(e);return t===void 0?null:B(G,{dimColor:!0,children:t})}function si(){return{selectedIndex:null,draft:``}}function ci(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:si()}}function li(e,t){let n=t.trim();return n.length===0||e[e.length-1]===n?[...e]:[...e,n]}function ui(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=li(t,e.content))}return t}function di(e,t,n){return t===0?0:n===`previous`?e>0?e-1:t-1:e<t-1?e+1:0}function fi(e,t){if(g(e)&&e.slice(1).includes(` `)){let{name:n}=u(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 pi(e,t){if(g(e)&&e.slice(1).includes(` `)){let{name:n}=u(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 mi(e,t,n,r){let i=r.split(`
17
+ `).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 hi(e){return e.trim().length>0}const gi=[`all`,`session`,`project`];function _i(e){let t=gi.indexOf(e);return gi[(t+1)%gi.length]??`all`}function vi(e,t,n){switch(t){case`all`:return!0;case`session`:return e.sessionId===n.sessionId;case`project`:return e.project===n.project}}function yi(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 bi(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 xi(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 Si(e,t){return t<=8||e<8?0:Math.min(e-8+1,t-8)}function Ci(e){return`${e} unreadable ${e===1?`line`:`lines`} skipped`}function wi(e){let t=q(),{match:n,selected:r,rowNumber:i,color:a}=e,o=i===void 0?r?`> `:` `:sr(i),s=xi(n.entry.text.replace(/\r\n|[\r\n]/gu,e=>e.length===2?` ↵`:`↵`),n.ranges);return V(G,{color:r?t.text.accent:void 0,dimColor:!r,wrap:`truncate-end`,children:[o,s.map((e,t)=>e.matched?B(G,{bold:!0,inverse:a,children:a?e.text:`[${e.text}]`},t):B(G,{children:e.text},t))]})}function Ti({view:e}){let t=q();if(e.error!==void 0)return V(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(Ci(e.skippedLines)),B(G,{dimColor:!0,children:n.join(` · `)})}function Ei({view:e}){let t=q(),n=K(),r=Xe(),i=Z(`history-search`,[[[`previous`,`next`],`Navigate`],[`cycle-scope`,`Scope`],[`insert`,`Insert`],[`execute`,`Run`],[`cancel`,`Close`]]);if(!e.open)return null;let a=Si(e.selectedIndex,e.matches.length),o=e.matches.slice(a,a+8);return V(E,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.muted},paddingX:1,children:[V(G,{children:[B(G,{color:t.text.accent,children:`(reverse-i-search)`}),` scope: `,e.scope,` · query:`,` `,e.query]}),o.map((t,i)=>B(wi,{match:t,selected:a+i===e.selectedIndex,rowNumber:n?a+i:void 0,color:r},`${t.entry.at}:${a+i}`)),B(Ti,{view:e}),B(Y,{hints:i})]})}function Di(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 Oi(e,t){let[n,r]=R(0),[i,a]=R(!1),o=j.useRef(e);o.current!==e&&(o.current=e,i&&a(!1));let s=Di(e),c=s.isSlash&&s.parentCommand.length>0,l=j.useRef(s.parentCommand);F(()=>{l.current!==s.parentCommand&&(l.current=s.parentCommand,r(0))},[s.parentCommand]);let u=I(()=>{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 ki={entries:[],skippedLines:0};function Ai(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 ji(e,t){return[...e].reverse().map(e=>({at:``,sessionId:t.sessionId,project:t.project,text:e}))}const Mi=()=>new Promise(e=>setImmediate(e));async function Ni(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 Mi())}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 Pi(e,t){let[n,r]=R(ki),[i,a]=R(!1),[o,s]=R(void 0),c=L(void 0),l=L(ki),u=N(()=>r(l.current),[]),d=N(()=>{c.current?.abort(),c.current=void 0,a(!1)},[]),f=N(()=>{if(d(),l.current=ki,r(ki),s(void 0),e===void 0)return;let n=new AbortController;c.current=n,a(!0),Ni({source:e.source,signal:n.signal,pending:l,publishEachBlock:!t,publish:u,setError:s,setLoading:a})},[u,t,d,e]);return F(()=>d,[d]),{loaded:n,loading:i,error:o,start:f,stop:d,publish:u}}function Fi(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(_i(e.scope)),e.setSelectedIndex(0)):!s&&(o.backspace||o.delete)?t(e=>e.slice(0,-1)):!s&&Ai(a,o)&&t(e=>e+a)},{isActive:e.open})}function Ii(e,t,n,r,i){let a=t?.sessionId,o=t?.project;return I(()=>{if(!e||a===void 0||o===void 0)return[];let t={sessionId:a,project:o};return yi(n===`session`?ji(r,t):i.filter(e=>vi(e,n,t)))},[i,e,o,n,a,r])}const Li={query:``,scope:`all`,selectedIndex:0};function Ri(){let[e,t]=R(Li);return{state:e,reset:N(()=>t(Li),[]),setters:I(()=>({setScope:e=>t(t=>({...t,scope:e})),setSelectedIndex:e=>t(t=>({...t,selectedIndex:e})),setQuery:e=>t(t=>({...t,query:e(t.query)}))}),[])}}function zi(e,t,n,r){let[i,a]=R(!1);return{open:i,openSearch:N(()=>{!t||i||(n(),a(!0),r?.(!0),e.start())},[t,e,r,i,n]),closeSearch:N(()=>{e.stop(),a(!1),r?.(!1)},[e,r])}}function Bi(e){let t=K(),n=Pi(e.surface,t),{state:r,reset:i,setters:a}=Ri(),{query:o,scope:s}=r,{surface:c,onInsert:l,onExecute:u}=e,{open:d,openSearch:f,closeSearch:p}=zi(n,c!==void 0,i,e.onOpenChange),m=Ii(d,c,s,e.sessionPrompts,n.loaded.entries),h=I(()=>bi(m,o),[m,o]),g=Math.min(r.selectedIndex,Math.max(0,h.length-1));Fi({open:d,matches:h,selected:g,scope:s,screenReader:t,loader:n,close:p,onInsert:l,onExecute:u,...a});let{loading:_,error:ee,loaded:te}=n;return{view:{...r,open:d,selectedIndex:g,matches:h,loading:_,error:ee,skippedLines:te.skippedLines},openSearch:f,closeSearch:p}}function Vi(e){let{historySearch:t,setValue:n,setCursorHint:r,submitPrompt:i,composerActive:a}=e,o=N(e=>{n(e),r(null)},[r,n]),s=N(e=>{n(``),i(e)},[n,i]),{view:c,openSearch:l,closeSearch:u}=Bi({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}),F(()=>{c.open&&!a&&u()},[u,a,c.open]),c}function Hi(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=>di(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 Ui(e){let{showPopup:t,isDisabled:n,isQueueCancellationDisabled:r,pendingPrompt:i,searchOpen:a}=e;Hi(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=ci(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 Wi(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 Gi(e){return`[deleted: ${e}]`}function Ki({screenReader:e,innerWidth:t,borderColor:n,sessionName:r}){let i=q();if(e)return null;let a=Wi(t,r);return V(G,{color:n,children:[a.left,a.label?B(G,{backgroundColor:n,color:i.text.onAccent,bold:!0,children:a.label}):null,a.right]})}function qi({screenReader:e,innerWidth:t,borderColor:n}){return e?null:B(G,{color:n,children:`─`.repeat(t)})}function Ji({deleted:e}){return e===null?null:B(G,{children:Gi(e)})}function Yi(){let{stdout:e}=ke(),t=()=>Math.max(40,(e.columns??80)-4),[n,r]=R(t);return F(()=>{let n=()=>r(t());return e.on(`resize`,n),()=>{e.off(`resize`,n)}},[e]),n}function Xi(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e.padEnd(t)}function Zi(e){let t=q(),{cmd:n,isSelected:r,showSlash:i,rowWidth:a,nameColWidth:o,rowNumber:s}=e,c=s===void 0?r?`> `:` `:sr(s),l=r?t.text.accent:void 0,u=!r,d=Xi(n.name,o);return B(E,{width:a,children:B(G,{color:l,dimColor:u,wrap:`truncate-end`,children:i?`${c}/${d} ${n.description??``}`:`${c}${d} ${n.description??``}`})})}function Qi({commands:e,selectedIndex:t,visible:n,isSubcommandMode:r}){let i=q(),a=Yi(),o=K(),s=Z(`autocomplete-menu`,[[[`previous`,`next`],`Navigate`],[`accept`,`Complete`],[`execute`,`Select`],[`close`,`Close`]]);if(!n||e.length===0)return null;let c=$i(t,e.length),l=e.slice(c,c+8),u=Math.min(20,Math.max(...l.map(e=>e.name.length)));return V(E,{flexDirection:`column`,...o?{}:{borderStyle:`round`,borderColor:i.border.muted},paddingX:1,children:[l.map((e,n)=>B(Zi,{cmd:e,isSelected:c+n===t,showSlash:!r,rowWidth:a,nameColWidth:u,...o?{rowNumber:c+n}:{}},e.name)),B(Y,{hints:s})]})}function $i(e,t){if(t<=8||e<8)return 0;let n=t-8;return Math.min(e-8+1,n)}const ea=/\[Pasted text #(\d+)(?: \+\d+ lines)?\]/g;function ta(e,t){return e.replace(ea,(e,n)=>t.get(Number(n))??``)}function na({text:e}){let t=K(),n=q(),r=at(),i=ot(),[a,o]=R(0);return F(()=>{if(!i)return;let e=setInterval(()=>{o(e=>e+1)},400);return()=>clearInterval(e)},[i]),t?B(G,{children:e}):i?B(G,{children:[...e].map((e,t)=>{let n=Math.floor(t/4),i=(a+n)%r.wave.length;return B(G,{color:r.wave[i],children:e},t)})}):B(G,{color:n.text.muted,children:e})}function ra({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,_]=R(f??``),[ee]=R(m===!0?f??``:``);F(()=>{f!==void 0&&f.length!==0&&p?.()},[f,p]);let[te,v]=R(null),ne=K(),[y,re]=R(null),[ie,ae]=R(si),[oe,se]=R([]),ce=I(()=>ui(l??[]),[l]),le=I(()=>oe.reduce((e,t)=>li(e,t),ce),[ce,oe]),b=L(new Map),{columns:ue}=A(),x=ue>0?ue:80,de=Math.max(1,x-3),fe=L(0),S=Z(`chat-input`,[[`submit`,`Submit`]]),{showPopup:C,filteredCommands:pe,selectedIndex:me,setSelectedIndex:he,isSubcommandMode:ge,setShowPopup:_e}=Oi(g,s),ve=N((e,t)=>{fe.current+=1;let n=fe.current;b.current.set(n,e),_(r=>{let i=mi(r,t,n,e);return v(i.cursorHint),i.value})},[]),ye=N(()=>{ae(si())},[]),w=N(e=>{se(t=>li(t,e))},[]),be=N(t=>{w(t),ye(),e(t)},[e,w,ye]),T=N(e=>{let t=fi(g,e);t.type===`insert`&&(_(t.value),t.selectedIndex!==void 0&&he(t.selectedIndex))},[g,he]),xe=N(e=>{let t=pi(g,e);if(t.type===`insert`){_(t.value),t.selectedIndex!==void 0&&he(t.selectedIndex);return}t.type===`submit`&&(_(``),be(t.value))},[g,be,he]),Se=N(e=>{if(!hi(e))return;if(C&&pe[me]){xe(pe[me]);return}let t=ta(e.trim(),b.current);_(``),b.current.clear(),fe.current=0,be(t)},[C,pe,me,xe,be]),Ce=Vi({historySearch:d,sessionPrompts:le,composerActive:!C&&!n&&!a,setValue:_,setCursorHint:v,submitPrompt:be});Ui({value:g,isDisabled:n,searchOpen:Ce.open,isQueueCancellationDisabled:r??n,pendingPrompt:a,showPopup:C,setShowPopup:_e,filteredCommands:pe,selectedIndex:me,setSelectedIndex:he,tabCompleteCommand:T,promptHistory:le,historyState:ie,setValue:_,setCursorHint:v,setHistoryState:ae,onRequestFocusBackgroundList:u,onCancelQueue:t});let D=i?h.border.attention:a?h.border.focused:n?h.border.muted:h.border.active,we=Math.max(1,x-0);return V(E,{flexDirection:`column`,children:[C&&B(Qi,{commands:pe,selectedIndex:me,visible:C,isSubcommandMode:ge}),B(Ei,{view:Ce}),B(Ji,{deleted:ne?y:null}),B(Ki,{screenReader:ne,innerWidth:we,borderColor:D,...c===void 0?{}:{sessionName:c}}),B(E,{paddingLeft:1,children:i?B(G,{color:h.text.warning,children:` Interrupting...`}):a?V(G,{color:h.text.accent,children:[` `,`Queued:`,` `,a.length>50?a.slice(0,47)+`...`:a,` `,typeof o==`number`&&o>1&&V(G,{dimColor:!0,children:[`(+`,o-1,` co-driver queued) `]}),B(G,{dimColor:!0,children:`(Backspace to cancel)`})]}):n?B(na,{text:` Waiting for response... (ESC to interrupt)`}):V(E,{children:[B(G,{color:h.text.success,bold:!0,children:`> `}),B(Xr,{value:g,onChange:e=>{_(e),ye(),v(null)},onDeletedText:re,onSubmit:Se,onPaste:ve,placeholder:`Type a message or /help`,availableWidth:de,cursorHint:te,enableVerticalNavigation:!1,keybindingContext:C?`autocomplete-menu`:`chat-input`,focus:!Ce.open})]})}),!ne&&!n&&!a&&!Ce.open&&B(Y,{hints:S}),B(qi,{screenReader:ne,innerWidth:we,borderColor:D}),ee.length>0&&g===ee&&B(oi,{value:g})]})}const ia=new Set([`Shell`,`Bash`,`BackgroundProcess`]);function aa(e){if(!ia.has(e.toolName)||!e.toolResultData)return;let t=oa(e.toolResultData),n=ma(t,`exitCode`),r=ha(t,`success`),i=ua(la(sa(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:ca(s,n),previewLines:a,omittedLineCount:o,transcriptHint:o>0?`... +${o} lines (full output in session transcript)`:void 0}}function oa(e){try{return JSON.parse(e)}catch{return e}}function sa(e,t){if(!fa(t))return e;let n=pa(t,`output`);if(n!==void 0)return n;let r=pa(t,`stdout`),i=pa(t,`stderr`),a=pa(t,`error`),o=[];return r&&o.push(r),i&&o.push(da(i,`[stderr] `)),!r&&!i&&a&&o.push(a),o.join(`
18
+ `)}function ca(e,t){return t!==void 0&&t!==0?`exit ${t}`:e?`error`:`ok`}function la(e){return e?e.replace(/\r\n/g,`
19
19
  `).split(`
20
- `):[]}function ca(e){let t=e.length;for(;t>0&&e[t-1].trim().length===0;)--t;return e.slice(0,t)}function la(e,t){return sa(e).map(e=>`${t}${e}`).join(`
21
- `)}function ua(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function da(e,t){if(!ua(e))return;let n=e[t];return typeof n==`string`?n:void 0}function fa(e,t){if(!ua(e))return;let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function pa(e,t){if(!ua(e))return;let n=e[t];return typeof n==`boolean`?n:void 0}const ma=` `,ha=Ae;function ga(e){return e===void 0?Je():e}function _a(e){return e?.trim().toLowerCase()===`diff`}function va(e,t,n,r){let i=`${ma}${e}`.padEnd(t);return n?e.startsWith(`+`)?r.added(i):e.startsWith(`-`)?r.removed(i):i.trimEnd():i.trimEnd()}function ya(e,t,n,r){if(e.startsWith(`+`)||e.startsWith(`-`))return va(e,n,t,r);let i=`${ma}${e}`;return t?e.startsWith(`@@`)?r.hunk(i):e.startsWith(`diff `)||e.startsWith(`index `)?r.meta(i):i:i}function ba(e,t){let n=e.reduce((e,t)=>Math.max(e,4+t.length),0);return t===void 0?n:Math.max(n,t)}function xa(e,t,n,r){let i=e.split(`
22
- `),a=ba(i,n);return`${i.map(e=>ya(e,t,a,r)).join(`
23
- `)}\n\n`}function Sa(e){return e.split(``).join(``).split(`\0`).slice(0,-1)}function Ca(e){e.tablecell=e=>`${e}`,e.tablerow=e=>`${e}`,e.table=(e,t)=>{let n=Sa(e),r=t.split(``).filter(e=>e.length>0).map(e=>Sa(`${e}`));return n.length===0||r.length===0?``:`${r.map(e=>n.map((t,n)=>`${t}: ${e[n]??``}`).join(`
20
+ `):[]}function ua(e){let t=e.length;for(;t>0&&e[t-1].trim().length===0;)--t;return e.slice(0,t)}function da(e,t){return la(e).map(e=>`${t}${e}`).join(`
21
+ `)}function fa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function pa(e,t){if(!fa(e))return;let n=e[t];return typeof n==`string`?n:void 0}function ma(e,t){if(!fa(e))return;let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function ha(e,t){if(!fa(e))return;let n=e[t];return typeof n==`boolean`?n:void 0}const ga=` `,_a=Ne;function va(e){return e===void 0?Xe():e}function ya(e){return e?.trim().toLowerCase()===`diff`}function ba(e,t,n,r){let i=`${ga}${e}`.padEnd(t);return n?e.startsWith(`+`)?r.added(i):e.startsWith(`-`)?r.removed(i):i.trimEnd():i.trimEnd()}function xa(e,t,n,r){if(e.startsWith(`+`)||e.startsWith(`-`))return ba(e,n,t,r);let i=`${ga}${e}`;return t?e.startsWith(`@@`)?r.hunk(i):e.startsWith(`diff `)||e.startsWith(`index `)?r.meta(i):i:i}function Sa(e,t){let n=e.reduce((e,t)=>Math.max(e,4+t.length),0);return t===void 0?n:Math.max(n,t)}function Ca(e,t,n,r){let i=e.split(`
22
+ `),a=Sa(i,n);return`${i.map(e=>xa(e,t,a,r)).join(`
23
+ `)}\n\n`}function wa(e){return e.split(``).join(``).split(`\0`).slice(0,-1)}function Ta(e){e.tablecell=e=>`${e}`,e.tablerow=e=>`${e}`,e.table=(e,t)=>{let n=wa(e),r=t.split(``).filter(e=>e.length>0).map(e=>wa(`${e}`));return n.length===0||r.length===0?``:`${r.map(e=>n.map((t,n)=>`${t}: ${e[n]??``}`).join(`
24
24
  `)).join(`
25
25
 
26
- `)}\n\n`}}function wa(e,t,n,r,i){let a=new ha(yt(r.markdown),{ignoreIllegals:!0,theme:bt(r.syntax)}),o=a.code.bind(a),s=xt(r);return a.code=(n,r,a)=>_a(r)?xa(n,e,t,s):i?o(n,r,a):`${n.split(`
27
- `).map(e=>`${ma}${e}`).join(`
28
- `)}\n\n`,n&&Ca(a),a}function Ta(e,t={}){let n=W(e),r=ke.parse(n,{renderer:wa(ga(t.color),t.codeBlockWidth,t.screenReader===!0,Ge(t.theme),t.syntaxHighlighting!==!1)});return typeof r==`string`?r.trimEnd():n}function Ea(){let e=nt(),t=at(),n=K();return(r,i={})=>Ta(r,{...i,theme:e,syntaxHighlighting:t,screenReader:n})}const Da=/_[0-9a-f]{8}$/;function Oa(e,t=re){if(!e.startsWith(t))return W(e);let n=e.slice(t.length).replace(Da,``);return W(n.length>0?n:e)}function ka(e){return e===void 0?``:W(e)}const Aa=M(`Assistant`),ja=M(void 0);function Ma({name:e,modelCommandToolPrefix:t,children:n}){return B(Aa.Provider,{value:e?.trim()||`Assistant`,children:B(ja.Provider,{value:t,children:n})})}function Na(){return P(Aa)}function Pa(){return P(ja)}const Fa={user:`you:`,assistant:`assistant:`,thinking:`thinking:`,tool:`tool:`,toolError:`tool error:`,error:`error:`,warning:`warning:`,permissionRequired:`permission required:`,cost:`cost:`};function Ia(e){switch(e){case`user`:return Fa.user;case`assistant`:return Fa.assistant;case`tool`:return Fa.tool;case`system`:return Fa.warning}}function La(e){return e===ne?`You`:e}function Ra({role:e,driverId:t}){let n=q(),r=K(),i=Na();if(r)return V(G,{children:[e===`user`&&t!==void 0&&t!==ne?`${t}:`:Ia(e),` `]});switch(e){case`user`:return V(G,{color:n.text.success,bold:!0,children:[t===void 0?`You`:La(t),`:`,` `]});case`assistant`:return V(G,{color:n.text.accent,bold:!0,children:[i,`:`,` `]});case`system`:return V(G,{color:n.text.warning,bold:!0,children:[`System:`,` `]});case`tool`:return V(G,{color:n.text.emphasis,bold:!0,children:[`Tool:`,` `]})}}function za(e,t){if(t)return`error`;let n=e.result===`success`||e.result===`error`||e.result===`denied`?e.result:void 0;return qt({toolName:e.toolName,firstArg:e.firstArg??``,isRunning:e.isRunning??!1,result:n})}function Ba(e,t,n){let r=ka(e.firstArg);return`${Gt[t]} ${Oa(e.toolName,n)}${r?`(${r})`:``}`}function Va({tool:e}){let t=q(),n=ra(e);if(!n||n.statusLabel===`ok`&&n.previewLines.length===0&&!n.transcriptHint)return null;let r=n.status===`error`?Kt(t,`error`):t.text.emphasis;return V(D,{flexDirection:`column`,marginLeft:4,children:[n.statusLabel!==`ok`&&B(G,{color:r,dimColor:!0,children:n.statusLabel}),n.previewLines.map((e,t)=>B(G,{color:r,dimColor:!0,children:e},`${e}-${t}`)),n.transcriptHint&&B(G,{dimColor:!0,children:n.transcriptHint})]})}function Ha(e){let t=e.lines.length>12?Wa(e.lines):e.lines,n=Math.max(...t.map(e=>e.lineNumber),0).toString().length,r=t.map(e=>Ua(e,n)),i=e.lines.length>12;return{file:e.file,markdown:["```diff",...r,"```"].join(`
29
- `),truncated:i,remainingLineCount:i?e.lines.length-t.length:0}}function Ua(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 Wa(e){let t=Ga(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 Ga(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 Ka({file:e,lines:t}){let n=q(),r=Ea(),i=Ha({file:e,lines:t}),a=K()?``:`│ `;return V(D,{flexDirection:`column`,marginLeft:4,children:[i.file&&V(G,{color:n.text.emphasis,dimColor:!0,children:[a,W(i.file)]}),B(Be,{children:r(i.markdown)}),i.truncated&&V(G,{color:n.text.emphasis,dimColor:!0,children:[a,`... and `,i.remainingLineCount,` more lines`]})]})}function qa({entry:e}){let t=q(),n=e.data;if(!n)return B(z,{});let r=n.promptTokens===void 0?`?`:Ja(n.promptTokens),i=n.completionTokens===void 0?`?`:Ja(n.completionTokens),a=Ja(n.totalTokens),s=n.source!==void 0&&n.source.scope!==`main`?n.source:void 0,c=s?s.label??s.id??s.scope:void 0,l=s?``:` · Context ${Math.round(n.contextUsedPercentage)}% (${o(n.contextUsedTokens)}/${o(n.contextMaxTokens)})`,u=n.costStatus===`unknown`?`cost unknown`:`cost ${n.costStatus}`;return B(D,{flexDirection:`column`,marginBottom:1,children:V(D,{children:[V(G,{color:t.text.emphasis,bold:!0,children:[c?`Usage (${c}):`:`Usage:`,` `]}),V(G,{dimColor:!0,children:[n.kind,` `,a,` tokens (in `,r,` / out `,i,`)`,l,` · `,u]})]})})}function Ja(e){return e<1e3?e.toLocaleString():o(e)}function Ya({kind:e,text:t,color:n}){return K()?V(G,{children:[Fa[e],` `]}):B(G,{color:n,bold:!0,children:t})}function Xa({message:e}){let t=q(),n=Pa();if(!r(e))return B(z,{});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 V(D,{flexDirection:`column`,marginBottom:1,children:[V(D,{children:[B(Ya,{kind:`tool`,text:`Tool: `,color:t.text.emphasis}),i&&V(G,{color:t.text.emphasis,dimColor:!0,children:[`[`,Oa(i,n),`]`]})]}),B(G,{children:` `}),o.map((e,n)=>V(D,{flexDirection:`column`,children:[V(G,{color:t.text.success,children:[` `,`✓`,` `,W(e.line)]}),e.diffLines&&e.diffLines.length>0&&B(Ka,{file:e.diffFile,lines:e.diffLines})]},n))]});let s=a.split(`
30
- `).filter(e=>e.trim());return V(D,{flexDirection:`column`,marginBottom:1,children:[V(D,{children:[B(Ya,{kind:`tool`,text:`Tool: `,color:t.text.emphasis}),i&&V(G,{color:t.text.emphasis,dimColor:!0,children:[`[`,W(i),`]`]})]}),B(G,{children:` `}),s.map((e,n)=>V(G,{color:t.text.success,children:[` `,`✓`,` `,W(e)]},n))]})}function Za({message:e}){let t=q(),n=W((e.content??``).replace(/^Error:\s*/,``));return V(D,{flexDirection:`column`,marginBottom:1,children:[B(D,{children:B(Ya,{kind:`error`,text:`✖ Error: `,color:t.text.error})}),V(D,{marginLeft:2,flexDirection:`column`,children:[B(G,{color:t.text.error,wrap:`wrap`,children:n}),B(G,{dimColor:!0,wrap:`wrap`,children:`The session is still alive — type your next prompt when ready.`})]})]})}const Qa=j.memo(function({message:e}){let t=Ea();if(r(e))return B(Xa,{message:e});if(e.role===`system`&&e.metadata?.kind===`error`)return B(Za,{message:e});let n=e.content??``,i=e.state===`interrupted`;return V(D,{flexDirection:`column`,marginBottom:1,children:[B(D,{children:B(Ra,{role:e.role,...typeof e.metadata?.driverId==`string`?{driverId:e.metadata.driverId}:{}})}),B(G,{children:` `}),B(D,{marginLeft:2,children:s(e)?B(Be,{wrap:`wrap`,children:t(n+(i?`
26
+ `)}\n\n`}}function Ea(e,t,n,r,i){let a=new _a(xt(r.markdown),{ignoreIllegals:!0,theme:St(r.syntax)}),o=a.code.bind(a),s=Ct(r);return a.code=(n,r,a)=>ya(r)?Ca(n,e,t,s):i?o(n,r,a):`${n.split(`
27
+ `).map(e=>`${ga}${e}`).join(`
28
+ `)}\n\n`,n&&Ta(a),a}function Da(e,t={}){let n=W(e),r=Me.parse(n,{renderer:Ea(va(t.color),t.codeBlockWidth,t.screenReader===!0,qe(t.theme),t.syntaxHighlighting!==!1)});return typeof r==`string`?r.trimEnd():n}function Oa(){let e=it(),t=st(),n=K();return(r,i={})=>Da(r,{...i,theme:e,syntaxHighlighting:t,screenReader:n})}const ka=/_[0-9a-f]{8}$/;function Aa(e,t=S){if(!e.startsWith(t))return W(e);let n=e.slice(t.length).replace(ka,``);return W(n.length>0?n:e)}function ja(e){return e===void 0?``:W(e)}const Ma=M(`Assistant`),Na=M(void 0);function Pa({name:e,modelCommandToolPrefix:t,children:n}){return B(Ma.Provider,{value:e?.trim()||`Assistant`,children:B(Na.Provider,{value:t,children:n})})}function Fa(){return P(Ma)}function Ia(){return P(Na)}const La={user:`you:`,assistant:`assistant:`,thinking:`thinking:`,tool:`tool:`,toolError:`tool error:`,error:`error:`,warning:`warning:`,permissionRequired:`permission required:`,cost:`cost:`};function Ra(e){switch(e){case`user`:return La.user;case`assistant`:return La.assistant;case`tool`:return La.tool;case`system`:return La.warning}}function za(e){return e===h?`You`:e}function Ba({role:e,driverId:t}){let n=q(),r=K(),i=Fa();if(r)return V(G,{children:[e===`user`&&t!==void 0&&t!==h?`${t}:`:Ra(e),` `]});switch(e){case`user`:return V(G,{color:n.text.success,bold:!0,children:[t===void 0?`You`:za(t),`:`,` `]});case`assistant`:return V(G,{color:n.text.accent,bold:!0,children:[i,`:`,` `]});case`system`:return V(G,{color:n.text.warning,bold:!0,children:[`System:`,` `]});case`tool`:return V(G,{color:n.text.emphasis,bold:!0,children:[`Tool:`,` `]})}}function Va(e,t){if(t)return`error`;let n=e.result===`success`||e.result===`error`||e.result===`denied`?e.result:void 0;return Yt({toolName:e.toolName,firstArg:e.firstArg??``,isRunning:e.isRunning??!1,result:n})}function Ha(e,t,n){let r=ja(e.firstArg);return`${qt[t]} ${Aa(e.toolName,n)}${r?`(${r})`:``}`}function Ua({tool:e}){let t=q(),n=aa(e);if(!n||n.statusLabel===`ok`&&n.previewLines.length===0&&!n.transcriptHint)return null;let r=n.status===`error`?Jt(t,`error`):t.text.emphasis;return V(E,{flexDirection:`column`,marginLeft:4,children:[n.statusLabel!==`ok`&&B(G,{color:r,dimColor:!0,children:n.statusLabel}),n.previewLines.map((e,t)=>B(G,{color:r,dimColor:!0,children:e},`${e}-${t}`)),n.transcriptHint&&B(G,{dimColor:!0,children:n.transcriptHint})]})}function Wa(e){let t=e.lines.length>12?Ka(e.lines):e.lines,n=Math.max(...t.map(e=>e.lineNumber),0).toString().length,r=t.map(e=>Ga(e,n)),i=e.lines.length>12;return{file:e.file,markdown:["```diff",...r,"```"].join(`
29
+ `),truncated:i,remainingLineCount:i?e.lines.length-t.length:0}}function Ga(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 Ka(e){let t=qa(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 qa(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 Ja({file:e,lines:t}){let n=q(),r=Oa(),i=Wa({file:e,lines:t}),a=K()?``:`│ `;return V(E,{flexDirection:`column`,marginLeft:4,children:[i.file&&V(G,{color:n.text.emphasis,dimColor:!0,children:[a,W(i.file)]}),B(He,{children:r(i.markdown)}),i.truncated&&V(G,{color:n.text.emphasis,dimColor:!0,children:[a,`... and `,i.remainingLineCount,` more lines`]})]})}function Ya({entry:e}){let t=q(),n=e.data;if(!n)return B(z,{});let r=n.promptTokens===void 0?`?`:Xa(n.promptTokens),a=n.completionTokens===void 0?`?`:Xa(n.completionTokens),o=Xa(n.totalTokens),s=n.source!==void 0&&n.source.scope!==`main`?n.source:void 0,c=s?s.label??s.id??s.scope:void 0,l=s?``:` · Context ${Math.round(n.contextUsedPercentage)}% (${i(n.contextUsedTokens)}/${i(n.contextMaxTokens)})`,u=n.costStatus===`unknown`?`cost unknown`:`cost ${n.costStatus}`;return B(E,{flexDirection:`column`,marginBottom:1,children:V(E,{children:[V(G,{color:t.text.emphasis,bold:!0,children:[c?`Usage (${c}):`:`Usage:`,` `]}),V(G,{dimColor:!0,children:[n.kind,` `,o,` tokens (in `,r,` / out `,a,`)`,l,` · `,u]})]})})}function Xa(e){return e<1e3?e.toLocaleString():i(e)}function Za({kind:e,text:t,color:n}){return K()?V(G,{children:[La[e],` `]}):B(G,{color:n,bold:!0,children:t})}function Qa({message:e}){let t=q(),n=Ia();if(!s(e))return B(z,{});let r=e.name,i=e.content,a=null;try{let e=JSON.parse(i);Array.isArray(e)&&e.length>0&&typeof e[0].line==`string`&&(a=e)}catch{}if(a)return V(E,{flexDirection:`column`,marginBottom:1,children:[V(E,{children:[B(Za,{kind:`tool`,text:`Tool: `,color:t.text.emphasis}),r&&V(G,{color:t.text.emphasis,dimColor:!0,children:[`[`,Aa(r,n),`]`]})]}),B(G,{children:` `}),a.map((e,n)=>V(E,{flexDirection:`column`,children:[V(G,{color:t.text.success,children:[` `,`✓`,` `,W(e.line)]}),e.diffLines&&e.diffLines.length>0&&B(Ja,{file:e.diffFile,lines:e.diffLines})]},n))]});let o=i.split(`
30
+ `).filter(e=>e.trim());return V(E,{flexDirection:`column`,marginBottom:1,children:[V(E,{children:[B(Za,{kind:`tool`,text:`Tool: `,color:t.text.emphasis}),r&&V(G,{color:t.text.emphasis,dimColor:!0,children:[`[`,W(r),`]`]})]}),B(G,{children:` `}),o.map((e,n)=>V(G,{color:t.text.success,children:[` `,`✓`,` `,W(e)]},n))]})}function $a({message:e}){let t=q(),n=W((e.content??``).replace(/^Error:\s*/,``));return V(E,{flexDirection:`column`,marginBottom:1,children:[B(E,{children:B(Za,{kind:`error`,text:`✖ Error: `,color:t.text.error})}),V(E,{marginLeft:2,flexDirection:`column`,children:[B(G,{color:t.text.error,wrap:`wrap`,children:n}),B(G,{dimColor:!0,wrap:`wrap`,children:`The session is still alive — type your next prompt when ready.`})]})]})}const eo=j.memo(function({message:e}){let t=Oa();if(s(e))return B(Qa,{message:e});if(e.role===`system`&&e.metadata?.kind===`error`)return B($a,{message:e});let r=e.content??``,i=e.state===`interrupted`;return V(E,{flexDirection:`column`,marginBottom:1,children:[B(E,{children:B(Ba,{role:e.role,...typeof e.metadata?.driverId==`string`?{driverId:e.metadata.driverId}:{}})}),B(G,{children:` `}),B(E,{marginLeft:2,children:n(e)?B(He,{wrap:`wrap`,children:t(r+(i?`
31
31
 
32
- _(interrupted)_`:``))}):B(G,{wrap:`wrap`,children:n})})]})});function $a({entry:e}){let t=q(),n=Pa(),r=e.data,i=r?.tools,a=r?.summary?.split(`
33
- `)??[];return i&&i.length>0?V(D,{flexDirection:`column`,marginBottom:1,children:[B(D,{children:B(Ya,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),B(G,{children:` `}),i.map((e,r)=>{let i=za(e,ra(e)?.status===`error`);return V(D,{flexDirection:`column`,children:[V(G,{color:Kt(t,i),children:[` `,Ba(e,i,n)]}),B(Va,{tool:e}),e.diffLines&&e.diffLines.length>0&&B(Ka,{file:e.diffFile,lines:e.diffLines})]},r)})]}):V(D,{flexDirection:`column`,marginBottom:1,children:[B(D,{children:B(Ya,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),B(G,{children:` `}),a.map((e,n)=>V(G,{color:t.text.success,children:[` `,W(e)]},n))]})}function eo({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 B(z,{});let i=W(r);return V(D,{flexDirection:`column`,marginBottom:1,children:[B(D,{children:B(Ya,{kind:`warning`,text:`System: `,color:t.text.warning})}),B(G,{children:` `}),B(D,{marginLeft:2,children:B(G,{wrap:`wrap`,children:i})})]})}function to({entry:e}){if(e.category===`chat`){let t=e.data;return B(Qa,{message:t})}return e.type===`tool-summary`?B($a,{entry:e}):e.type===`usage-summary`?B(qa,{entry:e}):e.type===`tool-start`||e.type===`tool-end`?B(z,{}):B(eo,{entry:e})}const no=[{keys:`↑↓`,label:`Navigate`},{keys:`Enter`,label:`Select`},{keys:`Esc`,label:`Cancel`}];function ro({items:e,renderItem:t,onSelect:n,onCancel:r,maxVisible:i=3,footerHints:a=no,initialIndex:o=0}){let[s,c]=R(()=>{let t=o>=0&&o<e.length?o:0;return{...vn(t),scrollOffset:Math.max(0,t-i+1)}}),l=L(s),u=N(t=>{let a=xn(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=kn({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 B(D,{});if(d){let n=ir(e.length,!0);return V(D,{flexDirection:`column`,children:[e.map((e,n)=>V(D,{children:[B(G,{children:ar(n)}),t(e,!1)]},n)),V(G,{children:[n,f.buffer.length>0?` ${f.buffer}`:``]}),f.invalid&&B(G,{children:n})]})}let m=Sn(s,{itemCount:e.length,maxVisible:i});m!==s&&(l.current=m);let{selectedIndex:h,scrollOffset:g}=m,_=e.slice(g,g+i),ee=g+i<e.length;return V(D,{flexDirection:`column`,children:[g>0&&V(G,{dimColor:!0,children:[` ↑ `,g,` more above`]}),_.map((e,n)=>B(D,{marginBottom:1,children:t(e,g+n===h)},g+n)),ee&&V(G,{dimColor:!0,children:[` ↓ `,e.length-g-i,` more below`]}),B(Y,{hints:a===no?p:a})]})}function io({label:e,index:t,isCursor:n,isChecked:r,screenReader:i}){let a=q(),o=r?`[x] `:`[ ] `;return i?V(G,{children:[ar(t),o,e]}):V(G,{color:n?a.text.accent:void 0,children:[n?`> `:` `,o,e]})}function ao(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 oo(e){let t=Z(`multi-select`,[[[`previous`,`next`],`Navigate`],[`toggle`,`Toggle`],[`confirm`,e.canConfirm?`Confirm`:`Confirm (min ${e.minSelect})`],[`cancel`,`Cancel`]]);return e.screenReader?B(or,{itemCount:e.itemCount,cancellable:!0,buffer:e.numbered.buffer,invalid:e.numbered.invalid}):B(Y,{hints:t})}function so(e){let t=q(),{title:n,description:r,options:i,cursor:a,selected:o,screenReader:s,numbered:c}=e;return V(D,{flexDirection:`column`,...s?{}:{borderStyle:`round`,borderColor:t.border.attention},paddingX:1,children:[B(G,{color:t.text.warning,bold:!0,children:n}),r!==void 0&&r.length>0&&B(G,{dimColor:!0,children:r}),i.map((e,t)=>B(io,{label:e.label,index:t,isCursor:t===a,isChecked:o.has(e.value),screenReader:s},e.value)),B(oo,{screenReader:s,itemCount:i.length,numbered:c,canConfirm:e.canConfirm,minSelect:e.minSelect})]})}function co(e){let{options:t,minSelect:n,maxSelect:r,defaultValues:i,onConfirm:a}=e,[o,s]=R(0),[c,l]=R(()=>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 lo({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}=co({options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o}),m=kn({enabled:c,itemCount:n.length,cancellable:!0,multi:!0,onSelect:f,onConfirm:p,onCancel:s});ao({active:!c,itemCount:n.length,setCursor:u,onToggleAtCursor:()=>f(l),onConfirm:p,onCancel:s});let h=d.size>=r;return B(so,{title:e,...t===void 0?{}:{description:t},options:n,cursor:l,selected:d,screenReader:c,canConfirm:h,minSelect:r,numbered:m})}function uo(){return{value:``,resolved:!1}}function fo(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`}}:po(e,n)}function po(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 mo({title:e,description:t,placeholder:n,onSubmit:r,onCancel:i,validate:a,allowEmpty:o=!1,masked:s=!1}){let c=q(),[l,u]=R(()=>uo()),d=L(l),f=N(e=>{let t=fo(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 V(D,{flexDirection:`column`,...p?{}:{borderStyle:`round`,borderColor:c.border.attention},paddingX:1,children:[B(G,{color:c.text.warning,bold:!0,children:e}),B(ho,{description:t}),V(D,{marginTop:1,children:[B(G,{color:c.text.accent,children:`> `}),l.value?B(G,{children:s?`*`.repeat(l.value.length):l.value}):n?B(G,{dimColor:!0,children:n}):null,B(G,{color:c.text.accent,children:`█`})]}),l.error&&B(G,{color:c.text.error,children:l.error}),B(Y,{hints:m})]})}function ho({description:e}){return e===void 0||e.length===0?null:B(G,{dimColor:!0,children:e})}const go={value:``,label:`Type a custom answer…`};function _o({request:e,onAnswer:t}){let n=q(),[r,i]=R(!1),a=e.options??[],o=a.length>0,s=e.maxSelect??1,c=()=>t({type:`cancelled`});if(!o||r)return B(mo,{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 B(lo,{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,go]:[...a],u=e.default?.values?.[0],d=u===void 0?0:Math.max(0,l.findIndex(e=>e.value===u));return V(D,{flexDirection:`column`,children:[B(G,{bold:!0,children:e.title}),e.description!==void 0&&e.description.length>0&&B(G,{dimColor:!0,children:e.description}),B(ro,{items:l,initialIndex:d,maxVisible:e.maxVisible,renderItem:(e,t)=>V(G,{color:t?n.text.accent:void 0,children:[t?`> `:` `,e.label]}),onSelect:e=>{e===go?i(!0):t({type:`answer`,values:[e.value]})},onCancel:c})]})}const vo=[`Allow [y]`,`Allow always (this session) [s]`,`Allow always (this project) [p]`,`Deny [n]`];function yo(e,t=!0){return[vo[0],`Allow ${e} always (this session) [s]`,t?`Allow ${e} always (this project) [p]`:`Project-wide approval unavailable`,vo[3]]}function bo(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`}}:So(e,t.index);let r=xn(e,t,{itemCount:vo.length});return r.effect.type!==`select`||r.effect.index===2&&!n?{state:r.state,effect:{type:`none`}}:{state:r.state,effect:{type:`resolve`,decision:xo(r.effect.index)}}}function xo(e){return e===0?!0:e===1?`allow-session`:e===2&&`allow-project`}function So(e,t){return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`resolve`,decision:xo(t)}}}function Co(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 wo({request:e,armDelayMs:t=450}){let n=q(),r=e.canPersistProjectPermission!==!1,[i,a]=j.useState(()=>vn()),o=j.useRef(i),s=j.useRef(e);if(s.current!==e){s.current=e;let t=vn();o.current=t,a(t)}let[c,l]=j.useState();j.useEffect(()=>{if(t<=0)return;let n=setTimeout(()=>l(e),t);return()=>clearTimeout(n)},[e,t]);let u=t<=0||c===e,d=j.useCallback(t=>{let n=bo(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=yo(y(e.toolName,e.toolArgs),r),m=kn({enabled:f&&u,itemCount:p.length,onSelect:t=>{let n=bo(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;j.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?B(sr,{title:Fa.permissionRequired,description:`${_===void 0?``:`Background agent ${_} wants to run `}${e.toolName} — ${Co(e.toolArgs)}${e.requestedByPeer===void 0?``:` (requested by another session: ${e.requestedByPeer})`}`,options:p,buffer:m.buffer,invalid:m.invalid}):V(D,{flexDirection:`column`,borderStyle:`round`,borderColor:u?n.border.attention:n.border.muted,paddingX:1,children:[V(D,{children:[B(G,{color:n.text.warning,bold:!0,children:`[Permission Required]`}),u?null:B(G,{dimColor:!0,children:` keys answer in a moment`})]}),_===void 0?V(G,{children:[`Tool:`,` `,B(G,{color:n.text.accent,bold:!0,children:e.toolName})]}):V(G,{color:n.text.warning,children:[`Background agent `,B(G,{bold:!0,children:_}),` wants to run`,` `,B(G,{color:n.text.accent,bold:!0,children:e.toolName})]}),V(G,{dimColor:!0,children:[` `,Co(e.toolArgs)]}),e.requestedByPeer===void 0?null:V(G,{color:n.text.warning,children:[`Requested by another session: `,e.requestedByPeer]}),B(D,{marginTop:1,flexDirection:`column`,children:p.map((e,t)=>{let r=u&&t===i.selectedIndex;return B(D,{children:V(G,{color:r?n.text.accent:void 0,bold:r,dimColor:!u,children:[r?`> `:` `,e]})},e)})}),B(Y,{hints:g})]})}function To(){return{buffer:``,resolved:!1}}const Eo=[`y`,`yes`],Do=[`n`,`no`];function Oo(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 Eo.includes(t)?{state:{buffer:``,resolved:!0},effect:{type:`select`,index:0}}:Do.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 ko(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:typeof t==`string`?xn(e,t,{itemCount:n}):{state:{...e,selectedIndex:t.index,resolved:!0},effect:{type:`select`,index:t.index}}}function Ao({message:e,options:t=[`Yes`,`No`],onSelect:n}){let r=q(),[i,a]=R(()=>vn()),o=L(i),s=N(e=>{let r=ko(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]=R(To),d=L(l);we((e,t)=>{let r=Oo(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?V(D,{flexDirection:`column`,children:[B(G,{children:e}),V(G,{children:[`Answer y or n and press Enter`,l.buffer.length>0?` ${l.buffer}`:``]})]}):V(D,{flexDirection:`column`,borderStyle:`round`,borderColor:r.border.attention,paddingX:1,children:[B(G,{color:r.text.warning,children:e}),B(D,{marginTop:1,children:t.map((e,t)=>B(D,{marginRight:2,children:V(G,{color:t===i.selectedIndex?r.text.accent:void 0,bold:t===i.selectedIndex,children:[t===i.selectedIndex?`> `:` `,e]})},e))}),B(Y,{hints:f})]})}function jo(e,t,n,r,i){let[a,o]=R([]),[s,c]=R(!1),[l,u]=R();return F(()=>{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 Mo({title:e,items:t,onSelect:n,onBack:r,loading:i,error:a}){let o=q(),[s,c]=R(()=>vn()),l=L(s),u=!i&&!a,d=K(),f=kn({enabled:d&&u,itemCount:t.length,cancellable:!0,onSelect:e=>{let r=t[e];r!==void 0&&n(r.value)},onCancel:r}),p=N(e=>{let i=xn(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=Sn(s,{itemCount:t.length});g!==s&&(l.current=g);let _=g.selectedIndex;return d?B(sr,{title:e,options:i||a?[]:t.map(e=>e.label),description:i?`Loading...`:a,cancellable:!0,buffer:f.buffer,invalid:f.invalid}):V(D,{flexDirection:`column`,borderStyle:`round`,borderColor:o.border.attention,paddingX:1,children:[B(G,{color:o.text.warning,bold:!0,children:e}),i&&B(D,{marginTop:1,children:B(G,{dimColor:!0,children:`Loading...`})}),a&&B(D,{marginTop:1,children:B(G,{color:o.text.error,children:a})}),!i&&!a&&B(D,{flexDirection:`column`,marginTop:1,children:t.map((e,t)=>V(D,{children:[V(G,{color:t===_?o.text.accent:void 0,bold:t===_,children:[t===_?`> `:` `,e.label]}),e.hint&&V(G,{dimColor:!0,children:[` `,e.hint]})]},e.value))}),B(Y,{hints:i?[]:a?h:m})]})}function No(e,t){e===`marketplace`?t.push({screen:`marketplace-list`}):e===`installed`&&t.push({screen:`installed-list`})}function Po(e,t){e===`__add__`?t.push({screen:`marketplace-add`}):t.push({screen:`marketplace-action`,context:{marketplace:e}})}function Fo(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 Io(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 Lo(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 Ro(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 zo(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 Bo({callbacks:e,onClose:t,addMessage:n}){let[r,i]=R([{screen:`main`}]),[a,o]=R(),[s,c]=R(0),l=r[r.length-1]??{screen:`main`},u=N(e=>{i(t=>[...t,e])},[]),d=N(()=>{i(e=>e.length<=1?(t(),e):e.slice(0,-1))},[t]),f=N(e=>{i(n=>{let r=n.slice(0,Math.max(1,n.length-e));return r.length===0?(t(),n):r})},[t]),p=N(e=>{n?.({role:`system`,content:e})},[n]),m=N(()=>{c(e=>e+1)},[]),h=N(e=>o(e),[o]),g={push:N(e=>u({screen:e.screen,context:e.context}),[u]),pop:d,popN:f,notify:p,setConfirm:h,refresh:m},{items:_,loading:ee,error:te}=jo(l.screen,l.context?.marketplace,e,s,r.length),v=N(t=>{let n=l.screen,r=l.context;n===`main`?No(t,g):n===`marketplace-list`?Po(t,g):n===`marketplace-action`?Fo(t,r?.marketplace??``,e,g):n===`marketplace-browse`?Io(t,r?.marketplace??``,_,g):n===`marketplace-install-scope`?Lo(t,r?.pluginId??``,e,g):n===`installed-list`?Ro(t,e,g):n===`installed-action`&&zo(t,r?.pluginId??``,e,g)},[l,_,e,u,d,f,p,o,m]),y=N(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 B(Ao,{message:a.message,onSelect:e=>{e===0?a.onConfirm():a.onCancel()}});let b=l.screen;return b===`marketplace-add`?B(mo,{title:`Add Marketplace Source`,placeholder:`owner/repo or git URL`,onSubmit:y,onCancel:d,validate:e=>e.includes(`/`)?void 0:`Must be owner/repo or a git URL`}):b===`marketplace-action`?B(Mo,{title:`Marketplace: ${l.context?.marketplace??``}`,items:[{label:`Browse plugins`,value:`browse`},{label:`Update`,value:`update`},{label:`Remove`,value:`remove`}],onSelect:v,onBack:d},r.length):b===`marketplace-install-scope`?B(Mo,{title:`Install scope for "${l.context?.pluginId??``}"`,items:[{label:`User scope`,value:`user`},{label:`Project scope`,value:`project`}],onSelect:v,onBack:d},r.length):b===`installed-action`?B(Mo,{title:`Plugin: ${l.context?.pluginId??``}`,items:[{label:`Uninstall`,value:`uninstall`}],onSelect:v,onBack:d},r.length):B(Mo,{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:v,onBack:d,loading:ee,error:te},`${b}-${r.length}-${s}`)}function Vo({notices:e}){let t=q();return e.length===0?null:B(D,{flexDirection:`column`,paddingX:1,children:e.map(e=>B(G,{color:t.text.muted,children:e.message},e.id))})}function Ho(e){let t=e.startsWith(`session_`)?e.slice(8):e;return t===``?e:t.slice(0,8)}function Uo(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 Wo({sessions:e,onSelect:t,onCancel:n}){let r=q();return V(D,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[B(G,{bold:!0,color:r.text.accent,children:`Select a session to resume:`}),B(ro,{items:[...e],renderItem:(e,t)=>{let n=Uo(e),i=e.preview?e.preview.slice(0,60)+(e.preview.length>60?`...`:``):``;return V(G,{children:[t?`> `:` `,B(G,{bold:!0,children:e.name??Ho(e.id)}),` `,B(G,{dimColor:!0,children:new Date(e.updatedAt).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}),` `,V(G,{dimColor:!0,children:[`msgs: `,e.messageCount]}),n===null?null:V(z,{children:[` `,B(G,{color:r.text.success,children:n})]}),i?V(z,{children:[`
34
- `,B(G,{dimColor:!0,children:i})]}):null]})},onSelect:e=>t(e.id),onCancel:n})]})}function Go(e){let t=Ko(e),n=e.hasPendingPrompt&&t.kind!==`queued`?[`queued`]:[],r=[t.label,...n].join(` · `);return{...t,segments:n,text:r}}function Ko(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 qo=` | `;function Jo(e,t){return e>=90?t.text.error:e>=70?t.text.warning:t.text.success}function Yo({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r}){let i=q(),a=Go({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r});return B(G,{color:i.text[a.tone],bold:a.kind!==`idle`,children:a.text})}function Xo({percentage:e,usedTokens:t,maxTokens:n}){return V(G,{color:Jo(e,q()),children:[`Context: `,Math.round(e),`% (`,o(t),`/`,o(n),` tokens)`]})}function Zo(){return B(G,{color:q().text.warning,bold:!0,children:`Observing — read only`})}function Qo({permissionMode:e}){return V(z,{children:[B(G,{color:q().text.accent,bold:!0,children:`Mode:`}),` `,B(G,{children:e})]})}function $o(e,t){return t||e!=="default"}function es({activePresetId:e}){return V(z,{children:[B(G,{color:q().text.accent,bold:!0,children:`Preset:`}),` `,B(G,{children:e})]})}function ts(e){return e!==void 0&&e!=="default"}function ns({modelName:e,providerDisplayName:t,effort:n}){return V(G,{dimColor:!0,children:[t===void 0?e:`${t} ${e}`,n===void 0?``:` Effort: ${n}`]})}function rs(e){let t=q(),n=e.showGitBranch&&e.gitBranch!==void 0&&e.gitBranch.length>0,r=K(),i=$o(e.permissionMode,r),a=e.activePresetId,o=ts(a);return V(G,{children:[e.readOnly&&V(z,{children:[B(Zo,{}),!r&&qo]}),!r&&B(Yo,{isThinking:e.isThinking,activeToolCount:e.activeToolCount,activeBackgroundTaskCount:e.activeBackgroundTaskCount,hasPendingPrompt:e.hasPendingPrompt}),i&&V(z,{children:[qo,B(Qo,{permissionMode:e.permissionMode})]}),o&&V(z,{children:[qo,B(es,{activePresetId:a})]}),e.sessionName&&V(z,{children:[qo,B(G,{color:t.text.session,children:e.sessionName})]}),n&&V(z,{children:[qo,V(G,{dimColor:!0,children:[`git: `,e.gitBranch]})]}),qo,B(ns,{modelName:e.modelName,providerDisplayName:e.providerDisplayName,effort:e.effort}),!r&&V(z,{children:[qo,B(Xo,{percentage:e.contextPercentage,usedTokens:e.contextUsedTokens,maxTokens:e.contextMaxTokens})]})]})}function is({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 ee=q();return V(D,{paddingLeft:1,paddingRight:1,justifyContent:`space-between`,children:[B(rs,{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&&V(G,{color:ee.text.warning,bold:!0,children:[`[`,m,`]`]})]})}const as=M(null),os=as.Provider;function ss(){let e=P(as);if(!e)throw Error(`TuiCliAdapterContext not provided`);return e}function cs({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 _=ss(),ee=I(()=>_.getGitBranch(e),[_,e,h]),te=I(()=>r===void 0?void 0:_.getProviderDisplayName(r),[_,r]);return d.enabled?B(is,{permissionMode:t,modelName:n??``,providerDisplayName:te,sessionId:i,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextPercentage:l.percentage,contextUsedTokens:l.usedTokens,contextMaxTokens:l.maxTokens,sessionName:u,gitBranch:ee,showGitBranch:d.gitBranch,activeAgentLabel:f,activePresetId:p,effort:m,readOnly:g}):g?B(Zo,{}):null}function ls(e,t){let n=qt(e);return{color:Kt(t,n),icon:Gt[n],strikethrough:n===`error`||n===`denied`}}function us({isThinking:e}){let t=q();return e?B(D,{marginBottom:1,children:B(G,{color:t.text.warning,children:`Thinking...`})}):B(z,{})}function ds({activeTools:e}){let t=q(),n=Pa();return V(D,{flexDirection:`column`,marginBottom:1,children:[B(G,{color:t.text.emphasis,bold:!0,children:`Tools:`}),B(G,{children:` `}),e.map((e,r)=>{let{color:i,icon:a,strikethrough:o}=ls(e,t);return V(D,{flexDirection:`column`,children:[V(G,{color:i,strikethrough:o,children:[` `,a,` `,Oa(e.toolName,n),`(`,ka(e.firstArg),`)`]}),e.diffLines&&e.diffLines.length>0&&B(Ka,{file:e.diffFile,lines:e.diffLines})]},`${e.toolName}-${r}`)})]})}function fs(e,t,n,r){let i=t.map(e=>Oa(e.toolName,r)).join(`, `),a=[i.length>0?`${Fa.tool} ${i}`:void 0,e.length>0?e:n?Fa.thinking:void 0].filter(e=>e!==void 0);return a.length===0?B(z,{}):B(G,{children:a.join(` — `)})}function ps({text:e,activeTools:t,isThinking:n=!1}){let r=q(),i=Ea(),a=t.length>0,o=e.length>0,s=K(),c=Na(),l=Pa();return s?fs(e,t,n,l):!a&&!o?B(us,{isThinking:n}):V(D,{flexDirection:`column`,children:[a&&B(ds,{activeTools:t}),o&&V(D,{flexDirection:`column`,marginBottom:1,children:[V(G,{color:r.text.accent,bold:!0,children:[c,`:`]}),B(G,{children:` `}),B(D,{marginLeft:2,children:B(Be,{wrap:`wrap`,children:i(e)})})]})]})}function ms(e,t){let n=t?` (current)`:``;return`${e.name} — ${e.appearance}, ${e.source}${n}`}function hs({theme:e,isFocused:t,isActive:n,rowNumber:r}){let i=q(),a=r===void 0?t?`> `:` `:ar(r);return V(G,{...t&&r===void 0?{color:i.text.accent,bold:!0}:{},children:[a,ms(e,n)]})}function gs({itemCount:e,buffer:t,invalid:n}){let r=ir(e,!0);return V(D,{flexDirection:`column`,children:[V(G,{children:[r,t.length>0?` ${t}`:``]}),n&&B(G,{children:r})]})}function _s(e,t){let n=e.findIndex(e=>e.id===t);return n<0?0:n}function vs(e){let[t,n]=j.useState(()=>({syntaxHighlighting:e.syntaxHighlighting,reducedMotion:e.reducedMotion}));return{toggles:t,setToggles:n}}function ys(e){let{themes:t,activeThemeId:n,preview:r}=e,[i,a]=j.useState(()=>_s(t,n));return{focusedIndex:i,move:j.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 bs(e,t){let{themes:n,select:r,cancel:i}=e,{focusedIndex:a,move:o}=ys(e),{toggles:s,setToggles:c}=vs(e),l=j.useRef(s);l.current=s;let u=j.useCallback(e=>{let t=n[e];t&&r(t.id,l.current)},[r,n]),d=kn({enabled:t&&n.length>0,itemCount:n.length,cancellable:!0,onSelect:u,onCancel:i}),f=j.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 xs({themes:e,activeThemeId:t,focusedIndex:n,screenReader:r}){return e.length===0?B(G,{dimColor:!0,children:`No themes installed`}):B(z,{children:e.map((e,i)=>B(hs,{theme:e,isFocused:i===n,isActive:e.id===t,...r?{rowNumber:i}:{}},e.id))})}function Ss(){return Je()?B(z,{}):B(G,{dimColor:!0,children:`Colour is off for this terminal — themes apply, previews cannot show.`})}function Cs({skipped:e}){return e.length===0?B(z,{}):B(D,{flexDirection:`column`,marginTop:1,children:e.map((e,t)=>B(G,{dimColor:!0,children:` Skipped "${e.fileName}" — ${e.reason}`},t))})}function ws({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 V(D,{flexDirection:`column`,children:[B(G,{dimColor:!0,children:`syntax ${r(e.syntaxHighlighting)} · motion ${r(!e.reducedMotion)}${i}`}),n&&B(G,{dimColor:!0,children:`Change with /theme syntax on|off or /theme motion on|off`})]})}function Ts({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?B(gs,{itemCount:t,buffer:n.buffer,invalid:n.invalid}):B(Y,{hints:r})}function Es({picker:e}){let t=q(),n=K(),{themes:r,activeThemeId:i}=e,{focusedIndex:a,toggles:o,numbered:s}=bs(e,n);return V(D,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.focused},paddingX:1,children:[B(G,{color:t.text.accent,bold:!0,children:`Theme`}),B(Ss,{}),B(ws,{toggles:o,reducedMotionPin:e.reducedMotionPin,screenReader:n}),B(D,{flexDirection:`column`,marginTop:1,children:B(xs,{themes:r,activeThemeId:i,focusedIndex:a,screenReader:n})}),B(Cs,{skipped:e.skipped}),B(Ts,{screenReader:n,itemCount:r.length,numbered:s})]})}function Ds({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 B(D,{children:B(G,{color:t?n.text.accent:void 0,bold:t,children:`${i} ${e.transport.name.padEnd(18)} ${a} ${s}`})})}function Os(e,t,n,r,i,a,o,s,c){Q(`transport-settings`,N(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 ks({registry:e,onClose:t}){let n=q(),r=Na(),[i,a]=R(()=>e.getAll()),[o,s]=R(0),[c,l]=R(!1),[u,d]=R(void 0),f=N(()=>{a(e.getAll())},[e]),p=Z(`transport-settings`,[[[`previous`,`next`],`Select`],[`toggle`,`Toggle`],[`close`,`Close`]]);return Os(i,o,c,e,s,l,d,t,f),V(D,{flexDirection:`column`,paddingX:2,paddingY:1,children:[B(G,{bold:!0,children:`Settings › Transports`}),B(D,{marginTop:1,flexDirection:`column`,children:i.map((e,t)=>B(Ds,{entry:e,selected:t===o},e.transport.name))}),V(D,{marginTop:1,flexDirection:`column`,children:[B(Y,{hints:p}),V(G,{dimColor:!0,children:[`A toggle is saved now and applies the next time `,r,` starts.`]})]}),c&&B(D,{marginTop:1,children:B(G,{color:n.text.warning,children:`Saving…`})}),u!==void 0&&B(D,{marginTop:1,children:B(G,{color:n.text.error,children:`Not saved — ${u}`})})]})}function As({message:e}){return B(D,{paddingX:1,marginBottom:1,children:B(G,{color:q().text.warning,children:e})})}function js({model:e}){return B(be,{items:e.staticItems,children:e=>e.kind===`banner`?B(Ht,{version:e.version},`logo`):B(to,{entry:e.entry},e.entry.id)},e.transcriptKey)}function Ms({model:e}){let t=q(),{background:n,stream:r}=e;return V(D,{flexDirection:`column`,paddingX:1,flexGrow:1,children:[n.selectedEntry&&n.selectedEntry.kind!==`main_thread`&&B(gn,{entry:n.selectedEntry,page:n.detail.page,loading:n.detail.loading,error:n.detail.error}),e.isShuttingDown&&B(G,{color:t.text.warning,children:`Shutting down...`}),(r.isThinking||r.activeTools.length>0)&&V(D,{flexDirection:`column`,marginBottom:1,children:[B(ps,{text:r.text,activeTools:r.activeTools,isThinking:r.isThinking}),r.isStalled&&B(G,{color:t.text.warning,children:`⚠ Still waiting on the provider — the network may be stalled. Esc to interrupt.`})]}),!r.isThinking&&r.lastErrorMessage&&B(G,{color:t.text.error,children:`✖ Last turn failed — the session is alive; type your next prompt when ready.`}),B(mn,{entries:n.entries,focusedIndex:n.focusedIndex})]})}function Ns({model:e}){if(e.coordinationError!==void 0||e.coordinationPending)return B(z,{});let{background:t,plugin:n,sessionPicker:r,transport:i}=e,a=e.pendingUserAction;return V(z,{children:[t.switcherVisible&&B(lr,{snapshot:t.snapshot,selectedEntryId:t.selectedEntryId,onSelect:t.select,onClose:t.closeSwitcher,onAttach:t.attachToFork}),e.permissionRequest&&B(wo,{request:e.permissionRequest}),a&&B(_o,{request:a,onAnswer:t=>e.resolveUserAction(a,t)}),n.visible&&B(Bo,{callbacks:n.callbacks,onClose:n.close,addMessage:e=>n.addMessage(e.content)}),i.visible&&i.registry&&B(ks,{registry:i.registry,onClose:i.close}),r.visible&&B(Wo,{sessions:r.sessions,onSelect:r.select,onCancel:r.cancel}),e.theme.picker.visible&&B(Es,{picker:e.theme.picker})]})}function Ps({model:e}){let{input:t}=e;return V(z,{children:[B(hn,{percentage:e.contextPercentage}),B(ta,{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}),B(cs,{...e.status})]})}function Fs({viewModel:e}){let t=q(),n=rr();return V(D,{flexDirection:`column`,children:[B(js,{model:e}),!e.handoffSuspended&&V(z,{children:[e.updateNotice&&B(As,{message:e.updateNotice}),e.coordinationError&&V(G,{color:t.text.error,children:[e.coordinationError,` Press Enter to retry.`]}),n.diagnostic&&B(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=>B(G,{color:t.text.warning,children:`Keybindings ${e.path}: ${e.message}`},`${e.path}:${e.code}`)),e.theme.unknownThemeNotice!==void 0&&B(G,{color:t.text.warning,children:e.theme.unknownThemeNotice}),B(Vo,{notices:e.sessionEventNotices}),B(Ms,{model:e}),B(Ns,{model:e}),B(Ps,{model:e})]})]})}function Is(e){return[...e.screenReader?[]:[{kind:`banner`,version:e.version??`0.0.0`}],...e.history.map(e=>({kind:`entry`,entry:e}))]}function Ls(e){let t=e.forceExit??(e=>process.exit(e));if(e.isShuttingDown){t(130);return}e.graceful()}function Rs(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 zs={promptStart:`A`,promptEnd:`B`,turnStart:`C`,turnEnd:`D`};function Bs(e){return`\x1b]133;${zs[e]}\x07`}function Vs(e){let t=e.write??(e=>{process.stdout.write(e)});return{emit(n){!e.enabled||!e.supported()||t(Bs(n))}}}function Hs(e,t){return e.executionId??`${e.toolName}#${t}`}function Us(e){let t=new Set;return e.forEach((e,n)=>{e.isRunning&&t.add(Hs(e,n))}),t}function Ws(e){let{enabled:t,isThinking:n,activeTools:r,awaitingAnswer:i}=e,a=I(()=>Rs({enabled:t}),[t]),o=Wr(),s=qr(),c=I(()=>Vs({enabled:t,supported:()=>Xe({override:s.turnMarks}),write:e=>o.write(e)}),[t,o,s.turnMarks]),l=L(!1),u=L(new Set);F(()=>{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]),F(()=>{c.emit(`promptStart`)},[c]),F(()=>{i&&a.promptMounted()},[i,a]),F(()=>{let e=Us(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 Gs(e){return!!(e.permissionRequest||e.pendingUserAction||e.pluginVisible||e.transportVisible||e.sessionPickerVisible||e.workspaceSwitcherVisible||e.historySearchOpen||e.themePickerVisible||e.coordinationBlocked)}function Ks(e){Q(e.isThinking?`thinking`:`background-detail`,t=>{if(Gs(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 qs(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 Js(e){Q(`recovery`,t=>{e.recoveryError!==void 0&&!e.recoveryPending&&t.includes(`retry`)&&e.retryRecovery()})}function Ys(e,t){return e===``||t&&e===`]`}function Xs(e){let{exit:t}=Se(),n=n=>{Ls({isShuttingDown:e.isShuttingDown,graceful:()=>void e.shutdown(n).finally(()=>t())})};we((t,r)=>{(r.ctrl&&t===`c`||e.attached&&Ys(t,r.ctrl))&&n(`prompt_input_exit`)}),F(()=>{let e=()=>n(`other`);return process.on(`SIGINT`,e),process.on(`SIGTERM`,e),()=>{process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}})}function Zs(e){Ks(e),Js(e),qs(e),Xs(e);let t=K();return Ws({enabled:t,isThinking:e.isThinking,activeTools:e.activeTools,awaitingAnswer:e.permissionRequest!==null||e.pendingUserAction!==null}),t}function Qs(){return Promise.reject(Error(`Plugin management is unavailable in this host.`))}function $s(){return{listInstalled:Qs,listAvailablePlugins:Qs,install:Qs,uninstall:Qs,enable:Qs,disable:Qs,marketplaceAdd:Qs,marketplaceRemove:Qs,marketplaceUpdate:Qs,marketplaceList:Qs,reloadPlugins:Qs}}function ec(e){return e??$s()}function tc(e){return I(()=>ec(e),[e])}function nc(e){let n=tc(e.pluginAdapter),r=N(n=>e.addEntry(t(i(n))),[e.addEntry]),a=N(t=>{e.setSessionPickerVisible(!1),e.onSessionSwitch(t)},[e.onSessionSwitch,e.setSessionPickerVisible]),o=N(()=>{e.setSessionPickerVisible(!1),e.addEntry(t(i(`Session resume cancelled.`)))},[e.addEntry,e.setSessionPickerVisible]),s=e.hostSessions??ue(e.sessionStore,e.cwd),c=e.sessionPickerVisible&&s.length===0;return F(()=>{c&&(e.setSessionPickerVisible(!1),e.addEntry(t(i(`No saved sessions to resume in this workspace.`))))},[c,e.addEntry,e.setSessionPickerVisible]),{plugin:{visible:e.pluginVisible,callbacks:n,close:()=>e.setPluginVisible(!1),addMessage:r},transport:{visible:e.transportVisible,registry:e.transportRegistry,close:()=>e.setTransportVisible(!1)},sessionPicker:{visible:e.sessionPickerVisible&&!c,sessions:s,select:a,cancel:o}}}function rc(e){let[t,n]=R(0),r=N(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=N(async e=>{n(e=>e+1),await r(e)},[r]),a=L(!1);return F(()=>{a.current&&!e.isThinking&&n(e=>e+1),a.current=e.isThinking},[e.isThinking]),{submit:i,gitRefreshToken:t}}function ic(e){let{screens:t,workspace:n}=e.shell,r=rc({selectedEntry:n.background.selectedEntry,submit:t.handleSubmit,sendAgentJob:e.state.sendAgentJob,isThinking:e.state.isThinking}),i=Zs({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:nc({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 ac(e){let t=Na();F(()=>{let n=W(e??``),r=W(t),i=n?`${r} — ${n}`:r;process.stdout.write(`\x1b]0;${i}\x07`)},[e,t])}function oc(e){let[t,n]=R(!1);return F(()=>{if(e)return e.registerSuspendHooks({suspend:async()=>{n(!0),await new Promise(e=>setTimeout(e,50))},resume:()=>n(!1)})},[e]),t}function sc(e){let[t,n]=R(),[r,i]=R(!0),a=N(()=>{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 F(()=>{a()},[e,a]),{startError:t,startPending:r,retryStart:a}}function cc(e){let[t,n]=R();return F(()=>{let t=!0;return e?.then(e=>{t&&e!==void 0&&n(e)}).catch(()=>{}),()=>{t=!1}},[e]),t}function lc(e,t){let n=sc(e),[r,i]=R(e.sessionName);return F(()=>{e.sessionName!==void 0&&e.sessionName!==r&&i(e.sessionName)},[e,e.sessionName,r]),ac(r),{sessionName:r,setSessionName:i,handoffSuspended:oc(e.terminalHandoffController),updateNotice:cc(t),...n}}function uc(e){return C(e.readSettings(e.getUserSettingsPath()))}function dc(){let e=ss(),[t,n]=R(()=>uc(e));return[t,N(()=>{n(uc(e))},[e])]}function fc(e){let[t,n]=R(null),[r,i]=R(),[a,o]=R(!1),{entry:s,snapshot:c,read:l}=e;return F(()=>{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 pc(e,t){let n=d(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 mc({sessionStore:e,onSessionSwitch:n,addEntry:r}){let a=ss();return N(o=>{let s=e=>r(t(i(e)));if(e===void 0){s(`This surface has no session store, so it cannot attach to a forked session.`);return}pc(o,{hasSessionRecord:t=>e.load(t).status===`valid`,switchSession:n,notify:s,...a.formatResumeCommand===void 0?{}:{formatResumeCommand:a.formatResumeCommand}})},[r,a,n,e])}function hc(e){let{snapshot:t,selectedEntryId:n}=e,r=I(()=>t?.entries.find(e=>e.id===n),[t,n]);return{entry:r,detail:fc({entry:r,snapshot:t,read:e.read}),attachToFork:mc({sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.addEntry})}}function gc(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 _c(e,t,n,r,i){Q(`background-list`,i=>{if(e===null)return;let a=gc(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 vc(e,t,n){let[r,i]=R(null);return F(()=>{i(t=>t===null||e.length===0?null:Math.min(t,e.length-1))},[e.length]),_c(r,e,i,t,n),{focusedIndex:r,focusList:N(()=>{e.length>0&&i(0)},[e.length])}}function yc(e){return{open:N(()=>e(!0),[e]),toggle:N(()=>e(e=>!e),[e]),close:N(()=>e(!1),[e])}}function bc(e){let t=I(()=>Qt(e.snapshot),[e.snapshot]),{focusedIndex:n,focusList:r}=vc(t.map(e=>e.id),e.select,e.navigationEnabled),i=hc({selectedEntryId:e.selectedEntryId,snapshot:e.snapshot,read:e.read,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.addEntry}),a=yc(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:$t(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 xc(e,t,n){let r=e=>{if(e.requesterDriverId===ne)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 Sc(e){let t=L(e);return t.current=e,t}function Cc({uiEventPort:e,baseHandleSubmit:t,setSessionName:n,refreshStatusLineSettings:r,refreshAppearanceSettings:i,showSessionPickerOnStart:a,openAgentSwitcher:o}){let[s,c]=R(!1),[l,u]=R(a??!1),[d,f]=R(!1),[p,m]=R(!1),h=Sc({setSessionName:n,refreshStatusLineSettings:r,refreshAppearanceSettings:i,openAgentSwitcher:o});return De(()=>xc(e,{setShowPluginTUI:c,setShowTransportTUI:f,setShowSessionPicker:u,setShowThemePicker:m},h),[e]),{handleSubmit:N(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 wc(e){let t={...g},n=e.statusline;return Tc(n)?{enabled:typeof n.enabled==`boolean`?n.enabled:t.enabled,gitBranch:typeof n.gitBranch==`boolean`?n.gitBranch:t.gitBranch}:t}function Tc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Ec(e){return wc(e.readSettings(e.getUserSettingsPath()))}function Dc(){let e=ss(),[t,n]=R(()=>Ec(e));return[t,N(()=>{n(Ec(e))},[e])]}function Oc(e){let[t,n]=R(!1),[r,i]=R(!1),[a,o]=Dc(),[s,c]=dc(),l=Cc({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:bc({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 kc(e=We(),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===Ue)return{theme:Ge(n.get(Ue))};let t=n.get(e);return t?{theme:t}:{theme:Ge(n.get(Ue)),unknownId:e}}}}function Ac(e){return`Theme "${e}" is not installed — using "${Ue}".`}function jc(e){return{id:e.id,name:e.name,appearance:e.appearance,source:e.source}}function Mc(e){return{listThemes:()=>e.registry.list().map(jc),getTheme:t=>{let n=e.registry.get(t);return n?jc(n):void 0},getAppearance:()=>({settings:e.readAppearance(),...e.reducedMotionPin===void 0?{}:{reducedMotionPin:e.reducedMotionPin}})}}function Nc(e){let t=I(()=>e.registry??kc(),[e.registry]),[n,r]=R(void 0),i=I(()=>t.resolve(n??e.appearance.theme),[t,n,e.appearance.theme]),{setVisible:a,submit:o}=e,s=N(()=>{r(void 0),a(!1)},[a]),{syntaxHighlighting:c,reducedMotion:l}=e.appearance,u=N((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:Ac(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 Pc(e){let[,t]=R(0);F(()=>e.subscribe(()=>t(e=>e+1)),[e]);let n=e.getSnapshot(),r=N(t=>e.selectExecutionWorkspaceEntry(t),[e]),i=N(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 Fc(e,t){let n=e.sessionSwitchError??t.startError,r=!!(e.sessionSwitchPending||t.startPending);return{error:n,pending:r,blocked:n!==void 0||r}}function Ic(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 Lc(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:Ic(e)}}function Rc(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 zc(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:Lc(e),status:Rc(e)}}function Bc(e,t){return Nc({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 Vc(e,t){let[n,r]=R(e);return{initialValue:n,consumeInitialValue:N(()=>r(void 0),[]),externalPromptOrigin:t===`external-link`}}function Hc(e,t,n){return I(()=>Is({history:e,version:t,screenReader:n}),[e,n,t])}function Uc(e){let t=Vc(e.initialInput,e.initialInputOrigin),n=Pc(e.channel),r=lc(e.channel,e.startupUpdateNotice),i=Fc(e,r),a=Oc({state:n,setSessionName:r.setSessionName,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,showSessionPickerOnStart:e.showSessionPickerOnStart,coordinationBlocked:i.blocked}),o=ic({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=zc({props:e,state:n,lifecycle:r,shell:a,interaction:o,staticItems:Hc(n.history,e.version,o.screenReader),runtime:n.getRuntimeStatusSnapshot(e.permissionMode??`default`),coordination:i,theme:Bc(e,a)});return{...s,input:{...s.input,...t}}}function Wc(e){let t=Uc(e);return B(tt,{theme:t.theme.resolved,reducedMotion:t.theme.reducedMotion,syntaxHighlighting:t.theme.syntaxHighlighting,children:B(Fs,{viewModel:t})})}function Gc(e){let[t,n]=R(()=>({channel:e.createChannel(e.resumeSessionId),sessionId:e.resumeSessionId})),[r,i]=R(e.showSessionPickerOnStart??!1),[a,o]=R(),[s,c]=R(!1),[l,u]=R(),d=L(!1),f=L(!0);F(()=>()=>{f.current=!1},[]);let p=N(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:N(()=>{l!==void 0&&p(l)},[l,p])}}function Kc(e){let t=Gc(e);return B(os,{value:e.cliAdapter,children:B(Wc,{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 qc=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 Jc(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 Yc=class extends je{source;hooks;onData=e=>{let t=Jc(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 Xc(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 Zc(e,t=e=>{process.stdout.write(e)}){let n=Xc(e);n!==void 0&&t(`${n}\n`)}function Qc(e){return e??(e=>{process.stderr.write(`${e}\n`)})}function $c(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 el(e){if(!e.enabled)return{startupQuietMs:0,preparkMs:0};let t=Qc(e.warn);return{startupQuietMs:$c(e.overrides?.startupQuiet?.raw,e.overrides?.startupQuiet?.label??`startup quiet period`,900,6e5,t),preparkMs:$c(e.overrides?.prepark?.raw,e.overrides?.prepark?.label??`pre-write park`,50,5e3,t)}}function tl(e){return e?.isTTY!==!0||typeof e.setRawMode!=`function`?()=>{}:(e.setRawMode(!0),()=>{e.setRawMode?.(!1)})}async function nl(e,t){if(e<=0)return`elapsed`;let n=tl(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 rl(e){return typeof e==`string`?e:Buffer.from(e).toString(`utf8`)}function il(e){return W(e).trim().length>0}var al=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=rl(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&&il(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 ol(e){return new al(e)}function sl(e){return{armEchoRelease:()=>e.armEchoRelease(),write:t=>{e.write(t)}}}function cl(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 ll=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 ul=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 ml(`While away ${pl(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&&ul.has(n);if(!ul.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} ${fl(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} ${fl(this.errorCount,`error`)}`),e}reset(){this.turnsFinished=0,this.wakeTurnsFinished=0,this.needsInputCount=0,this.errorCount=0,this.reachedTerminal.clear()}};function fl(e,t){return e===1?t:`${t}s`}function pl(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 ml(e){return e.length<=120?e:`${e.slice(0,119)}…`}var hl=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 gl(e){return/not initialized/i.test(e.message)}function _l(e){let t=e.isBenignError??gl,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 vl(e,n,r,a,o){if(e.data?.pluginRegistryReloaded===!0&&o?.(r),a.addEntry(t(i(e.message))),n.isInitialized){let e=n.getContextState();a.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})}}function yl(e){let t=e.slice(1).split(/\s+/);return{name:t[0]?.toLowerCase()??``,args:t.slice(1).join(` `)}}var bl=class extends AggregateError{},xl=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 bl&&(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)}},Sl=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()}}},Cl=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 wl(e,n){let r=null;try{r=n.getActiveDriverId?.()??null}catch{r=null}return t(a(e,r?{metadata:{driverId:r}}:{}))}function Tl(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 El(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 Dl=class{options;bindings=[];constructor(e){this.options=e}wire(){if(this.bindings.length>0)return;let{session:t,manager:n,attention:r}=this.options,i=e=>{n.addUserEcho(wl(e,t))},a=()=>n.syncHistory(t.getFullHistory());this.bind(`user_message`,i),this.bind(`text_delta`,n.onTextDelta),this.bind(`tool_start`,n.onToolStart),this.bind(`tool_end`,n.onToolEnd),this.bind(`thinking`,n.onThinking),this.bind(`complete`,e=>{n.onComplete(e),r?.onComplete(),a()}),this.bind(`interrupted`,n.onInterrupted),this.bind(`error`,e=>{n.onError(e),r?.onError(),a()}),this.bind(`context_update`,n.onContextUpdate),this.bind(`compact`,a),this.bind(`skill_activation`,a),this.bind(`memory_event`,a),this.bind(`execution_workspace_event`,e=>{n.syncExecutionWorkspaceSnapshot(e.snapshot),r?.onWorkspaceSnapshot(e.snapshot)}),this.bind(`history_cleared`,()=>n.clearHistory()),this.bind(`turn_source`,e=>r?.onTurnSource(e)),Tl(this.bind.bind(this),n),this.bind(`permission_request`,({id:n,toolName:i,toolArgs:a,canPersistProjectPermission:o,requesterDriverId:s,requester:c})=>{r?.onNeedsInput();let l=s?.startsWith(`peer:`)?e(s):void 0;this.options.requestPermission(i,a,n,o,l,c).then(e=>t.resolvePermission(n,e)).catch(()=>t.resolvePermission(n,!1))}),this.bind(`ask_request`,({id:e,request:n})=>{r?.onNeedsInput(),this.options.askUser(n,e).then(n=>t.resolveAsk(e,n)).catch(()=>t.resolveAsk(e,{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){El(this.options.session,e,t,t=>{let n=this.options.onDeliveryError;n?n(t,e):this.options.manager.addSessionEventDeliveryError(t,e)},this.bindings)}};function Ol(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.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.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 kl(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 Al=class{sequence=0;notices=[];add(e){this.append(kl(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 jl(e,t){let n=null;return{schedule(){n||=setTimeout(()=>{n=null,e()},t)},flush(){n&&=(clearTimeout(n),null)}}}var Ml=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 Al;sessionEventNotices=this.sessionNoticeStore.notices;onChange=null;streamBuf=``;debouncedStreamNotify=jl(()=>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 Nl(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 Pl=15e3;var Fl=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 Ml,this.stateManager.onChange=()=>this.onChange?.(),this.userActions=new Sl(()=>this.onChange?.()),this.permissions=new Cl(()=>this.onChange?.()),this.interactiveSession=this.createSession(),this.registry=this.createRegistry(),this.attention=this.createAttention(e.attention),this.eventProjector=new Dl({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 xl({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(t(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 bl([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 de(Ol(this.opts))}createRegistry(){let e=new se;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=Nl(await this.interactiveSession.stopWaitingSelfPacedLoop(`Loop stopped by Esc`));e!==void 0&&this.addEntry(t(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:n,args:r}=yl(e),a=await this.interactiveSession.executeCommand(n,r);if(a){if(a.data?.sessionExecution===!0){this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}vl(a,this.interactiveSession,this.registry,this.stateManager,this.opts.reloadPluginCommandSource);return}this.stateManager.addEntry(t(i(`Unknown command "/${n}". 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=_l({check:()=>this.runInitCheck(),intervalMs:200,timeoutMs:Pl,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 hl({source:e,onRecap:e=>this.stateManager.addAttentionRecap(e)})}onInitFailure(e){let t=e.kind===`timeout`?`Session initialization timed out after ${Pl/Ut}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 Il(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 Ll=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&&Il(e,t.content));return r===-1?!0:(e=r+1,!1)})}};const Rl=`appearance-settings-patch`;function zl(e){return e instanceof Error?e.message:String(e)}function Bl(e){return{result:{success:!1,message:e},uiIntents:[]}}function Vl(e,t){return e?.commands.find(e=>e.name===t)}async function Hl(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!==Rl)return Bl(`Cannot apply '${e.type}' on this terminal.`);if(!c(e.patch))return Bl(`Failed to apply '${Rl}': invalid appearance settings patch`);a.push(e.patch)}for(let e of a)try{await r.writeAppearanceSettings(e)}catch(e){return Bl(`Failed to apply '${Rl}': ${zl(e)}`)}return{result:{message:i.message,success:i.success,...i.data===void 0?{}:{data:i.data}},uiIntents:i.uiIntents??[]}}function Ul(e){let t=new ee(e.terminalHandoff),{cwd:n}=e;return{canHandoffTerminal:()=>t.canHandoffTerminal(),runWithTerminal:e=>t.runWithTerminal(e),getCwd:()=>n,getCommandInvocationSource:()=>`user`}}function Wl(e,t){return e!==void 0&&e===t?ne:e}function Gl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Kl(e,t){if(!Gl(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&&Gl(r)&&r.driverId===t&&(n={...n,metadata:{...r,driverId:ne}}),n}function ql(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:Kl(e.data,r)}})}function Jl(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 Yl(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(Jl)}:{}})),...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 Xl(e,t){let n=t.toLowerCase();return e.find(e=>e.name.toLowerCase()===n&&e.subcommands!==void 0)?.subcommands??[]}function Zl(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>e.name.toLowerCase().startsWith(n))}const Ql=[`get-context`,`get-commands`,`get-status`,`get-executing`,`get-pending`,`get-execution-workspace`],$l=[...Ql,`get-prompts`],eu=[`get-context`,`get-status`,`get-commands`],tu=new Set([`exit`,`quit`]),nu=new Set([`show-plugin-manager`,`show-settings`]);function ru(e){return e instanceof Error?e.message:String(e)}var iu=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)}},au=class{options;sessionName;manager;userActions;permissions;attention;lifecycle;uiEvents=new iu;clientCommands;commandQueryPort={getCommands:e=>Zl(this.commandCatalog,e),getSubcommands:e=>Xl(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:Ul({terminalHandoff:e.terminalHandoff,cwd:e.cwd})},this.hostHistory=new Ll({request:e=>this.send(e===0?{type:`get-history`}:{type:`get-history`,fromIndex:e}),show:(e,t)=>this.manager.syncHostHistory(e,t),revive:e=>ql(e,this.own)}),this.userActions=new Sl(()=>this.notify()),this.permissions=new Cl(()=>this.notify()),this.attention=e.attention?new hl({source:e.attention,onRecap:e=>this.manager.addAttentionRecap(e)}):void 0,this.lifecycle=new xl({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}=yl(e);if(tu.has(t)){this.end(`user`);return}let r=Vl(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 Hl(e,t,n.host,n.set);for(let e of i)this.uiEvents.emitUiIntent({intent:e,requesterDriverId:ne});this.notice(r.message)}catch(t){this.notice(`/${e.name} failed: ${ru(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:Nl(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: ${ru(t)}`)}}project(e){let t=this.manager;switch(e.type){case`user_message`:{let t=Wl(e.driverId,this.options.driverId)??null;this.hostHistory.echo(wl(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=Yl(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(t){if(this.showsPrompt(t.id))return;this.attention?.onNeedsInput();let n=t.requesterDriverId?.startsWith(`peer:`)?e(t.requesterDriverId):void 0,r=this.promptGeneration;this.permissions.enqueue(t.toolName,t.toolArgs,t.id,t.canPersistProjectPermission,n,t.requester).then(e=>this.answer(r,t.id,{type:`permission-response`,id:t.id,result:e}))}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(nu.has(e.intent.type)){this.notice(`That screen is not available while attached to a daemon.`);return}let t={...e,requesterDriverId:ne};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:Ho(e.sessionId));t!==void 0&&t!==this.sessionName&&this.rename(t)}showCommandResult(e){for(let e of eu)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(Ho(e)),this.requestSnapshot()}requestSnapshot(){this.hostHistory.reload(),this.requestState()}requestState(){for(let e of this.readOnly?Ql:$l)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&&!Ie(e.type))return!1;try{return this.options.connection.send(e),!0}catch(e){return this.notice(`Could not reach the session: ${ru(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 Ml;return e.onChange=()=>this.notify(),e}notice(e){this.manager.addEntry(t(i(e)))}notify(){this.onChange?.()}};function ou(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.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.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 su(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 cu(e){try{await e.keybindingsSource?.start(),await du(e,t=>({createChannel:uu(e,t)}))}finally{e.keybindingsSource?.dispose()}}async function lu(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 au({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 uu(e,t){let n=e.workspaceMovedFrom;return r=>{let i=n;n=void 0;let a=new Fl({...ou(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&&Zc({enabled:n,channel:e.screenReaderChannel,hint:e.screenReaderHint});let r=el({enabled:n,overrides:e.screenReaderPacing}),i=n&&r.preparkMs>0?ol({stdout:process.stdout,preparkMs:r.preparkMs}):void 0;Je()||(T.level=0);let a=new ll,o=Ze({override:e.focusReporting}),s=cl({supported:()=>o}),c=new qc({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 nl(r.startupQuietMs,process.stdin);let f=new Yc(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:sl(i),m=B(Ma,{name:e.productDisplayName,modelCommandToolPrefix:e.modelCommandToolPrefix,children:B(nr,{source:e.keybindingsSource,children:B(qe,{enabled:n,children:B(Kr,{overrides:e.terminalCapabilities,children:B(Kc,{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=O(p===void 0?m:B(Ur,{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 su(()=>h.waitUntilExit(),()=>u)}finally{await i?.flush(),a.setTerminalModeHooks(void 0),s.disable(),c.dispose(),f.detach(),process.stdin.pause()}}const fu={drive:`drive (send prompts, answer its questions)`,observe:`observe (read only)`},pu=[`needs-input`,`working`,`idle`,`unknown`,`unverified`,`dead`];function mu(e,t){if(e.length<=t)return e;let n=Math.max(1,t-1);return[...e.slice(0,n),`… ${e.length-n} more — see robota trust status`]}function $(e){return e?.liveness===`alive`&&e.control===`available`&&e.generation!==void 0}function hu(e){return e.liveness===`dead`?`dead`:$(e)?e.activity:`unverified`}function gu(e){return[...e].sort((e,t)=>pu.indexOf(hu(e))-pu.indexOf(hu(t))||e.id.localeCompare(t.id))}function _u(e){return[...e].sort((e,t)=>(e.cwd===void 0)-+(t.cwd===void 0)||(e.cwd??``).localeCompare(t.cwd??``)||pu.indexOf(hu(e))-pu.indexOf(hu(t))||e.id.localeCompare(t.id))}function vu(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 Oe(bu(c))<=n?c:e.slice(o)}function yu(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 bu(e){return yu(e).join(``)}function xu(e,t){let n=yu(e);if(Oe(n.join(``))<=t)return n.join(``);let r=Math.ceil((t-1)/2),i=t-r-1,a=``;for(let e of n){if(Oe(a)+Oe(e)>r)break;a+=e}let o=``;for(let e of[...n].reverse()){if(Oe(o)+Oe(e)>i)break;o=e+o}return`${a}…${o}`}function Su(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 Cu(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 wu({loadRows:e,onStop:t,onStart:n,startTrustQuestion:r,onOpenPr:i,onAttach:a,filteredByCwd:o=!1,filteredByName:s=!1,filteredByPr:c=!1,stateFilter:l,refreshMs:u=2e3,initialSelectedId:d,initialGroupByDirectory:f=!1}){let{exit:p}=Se(),{stdout:m}=Ee(),h=Math.max(12,m.columns??80),g=K(),[_,ee]=R([]),[te,v]=R(Date.now),[y,b]=R(`loading`),[ne,re]=R(d),[ie,ae]=R(!1),[oe,se]=R(f),[x,ce]=R(),S=x?.id,[le,ue]=R(`idle`),[C,de]=R(`idle`),[fe,pe]=R(),w=L(!1),[me,he]=R(`idle`),[ge,_e]=R(),[T,ve]=R(),E=L(!1),[ye,be]=R(`idle`),xe=L(!1),O=L(!0),Ce=e=>{n!==void 0&&(E.current=!0,he(`starting`),Promise.resolve().then(()=>n(e)).then(e=>{O.current&&(_e(e),he(`started`))}).catch(()=>{O.current&&he(`failed`)}).finally(()=>{E.current=!1}))},k=I(()=>{let e=_.filter(e=>l===void 0||hu(e)===l);return oe?_u(e):gu(e)},[_,l,oe]),Te=I(()=>{let e=[],t=[...new Set(k.map(e=>e.cwd).filter(e=>e!==void 0))],n,r=0;return k.forEach((i,a)=>{let o=oe?i.cwd??`unverified`:hu(i);if(o!==n){let n=oe?i.cwd===void 0?`Directory: unverified`:(()=>{let e=`Dir ${++r}: `,n=Math.max(4,h-e.length),a=xu(vu(i.cwd,t,n),n),o=`${e}${a} — ${bu(i.cwd)}`;return g||Oe(o)<=h?o:`${e}${a}`})():`${o}:`;e.push({kind:`group`,label:n})}e.push({kind:`row`,row:i,index:a}),n=o}),e},[k,oe,h,g]);F(()=>{let t=new AbortController,n=!0,r,i=async()=>{try{let r=gu(await e(t.signal));if(!n||t.signal.aborted)return;let i=Date.now();ee(e=>Su(e,r)?e:r),v(e=>r.some(t=>t.nextLoopAt!==void 0&&Cu(t.nextLoopAt,e)!==Cu(t.nextLoopAt,i))?i:e),b(`ready`)}catch{n&&!t.signal.aborted&&b(`unavailable`)}finally{n&&!t.signal.aborted&&(r=setTimeout(()=>{i()},u))}};return i(),()=>{n=!1,r!==void 0&&clearTimeout(r),t.abort()}},[e,u]),F(()=>(O.current=!0,()=>{O.current=!1}),[]);let A=ne!==void 0&&k.some(e=>e.id===ne)?ne:k[0]?.id;F(()=>{re(e=>k.length===0||e!==void 0&&k.some(t=>t.id===e)?e:k[0]?.id)},[k]),we((e,o)=>{if(!w.current&&!(xe.current&&e!==`q`&&!(!g&&o.escape)&&!(o.ctrl&&e===`c`))&&!(E.current&&e!==`q`&&!(!g&&o.escape)&&!(o.ctrl&&e===`c`))){if(T!==void 0){e===`y`||e===`r`?(ve(void 0),Ce(e===`y`?`trust`:`restricted`)):(e===`n`||o.escape)&&ve(void 0);return}if(S!==void 0){if(e===`n`||o.escape){ce(void 0);return}if(e===`y`&&x?.action===`attach`){let e=x,t=k.find(t=>t.id===e.id);if(ce(void 0),y!==`ready`||!$(t)||t.generation!==e.generation||e.mode===void 0||a===void 0){ue(`unavailable`);return}a({id:e.id,generation:e.generation,mode:e.mode,groupByDirectory:oe}),p();return}if(e===`y`){let e=x,n=k.find(t=>t.id===e?.id);if(ce(void 0),y!==`ready`||e===void 0||!$(n)||n.generation!==e.generation||t===void 0){de(`unavailable`);return}w.current=!0,de(`stopping`),t(e.id,e.generation).then(()=>{O.current&&(pe(e.id),de(`stopped`))}).catch(()=>{O.current&&de(`failed`)}).finally(()=>{w.current=!1})}return}if(e===`q`||!g&&o.escape||o.ctrl&&e===`c`){p();return}if(e===`?`){ae(e=>!e);return}if(e===`g`){j.clear(),se(e=>!e);return}if(e===`n`&&n!==void 0){if(r===void 0){Ce();return}E.current=!0,r().then(e=>{E.current=!1,O.current&&(e===void 0?Ce():ve(e))}).catch(()=>{E.current=!1,O.current&&he(`failed`)});return}if((e===`a`||e===`p`)&&a!==void 0){let t=k.find(e=>e.id===A);y!==`ready`||!$(t)?ue(`unavailable`):(ue(`idle`),de(`idle`),ce({id:t.id,generation:t.generation,action:`attach`,mode:e===`a`?`drive`:`observe`}));return}if(e===`o`&&i!==void 0){let e=k.find(e=>e.id===A);if(y!==`ready`||!$(e)||!e.pr){be(`unavailable`);return}xe.current=!0,be(`opening`),i(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=k.find(e=>e.id===A);y!==`ready`||!$(e)?de(`unavailable`):(de(`idle`),ue(`idle`),ce({id:e.id,generation:e.generation,action:`stop`}));return}if(!(g||k.length===0)&&(o.upArrow||o.downArrow)){let e=Math.max(0,k.findIndex(e=>e.id===A)),t=Math.max(0,Math.min(k.length-1,e+(o.downArrow?1:-1)));re(k[t]?.id)}}});let j=kn({enabled:g&&S===void 0&&T===void 0&&C!==`stopping`,itemCount:k.length,cancellable:!0,repeatable:!0,onSelect:e=>{re(k[e]?.id),de(`idle`)},onCancel:()=>{w.current||p()}}),M=k.find(e=>e.id===A),N=y===`ready`&&$(M)?M.name:void 0,P=y===`ready`&&$(M)&&M.activity===`idle`&&M.nextLoopAt?Cu(M.nextLoopAt,te):``,De=y===`ready`&&$(M)?M.pr:void 0,ke=Math.max(8,m.rows??24),Ae=[`Keys:`,g?`Number+Enter Select`:`↑/↓ Select`,`s Request stop`,`g Group state/dir`,...n===void 0?[]:[`n New session`],...a===void 0?[]:[`a Attach (drive)`,`p Peek (read only)`],...i===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`],je=ie&&S===void 0&&C!==`stopping`,Me=2+(l===void 0?0:1)+ +(y===`loading`||y===`unavailable`||y===`ready`&&k.length===0)+(A===void 0?0:1)+(N===void 0?0:1)+(De===void 0?0:2)+ +!!P+(ye===`idle`?0:1)+(me===`idle`?0:1)+(T===void 0?0:1)+(S===void 0?C===`idle`?0:1:g?1:2)+ +(S===void 0&&le!==`idle`)+1+(je?Ae.length:0)+2,Ne=Math.max(1,ke-Me),Pe=Math.max(0,Te.findIndex(e=>e.kind===`row`&&e.row.id===A)),H=Math.min(Math.max(0,Pe-Math.floor(Ne/2)),Math.max(0,Te.length-Ne)),Fe=g?Te:Te.slice(H,H+Ne),Ie=T===void 0?[]:mu([`Not trusted: ${T.folder}`,`Trusting it loads the project's own settings, hooks, plugins, skills and MCP servers:`,...T.loads],g?1/0:Ne),U=g?{}:{wrap:`truncate-end`},Le=a!==void 0&&y===`ready`&&$(M),Re=C===`stopping`?`Stop in progress; wait for result.`:T===void 0?S===void 0?g?`Type a number and Enter to select; s Stop;${Le?` a Attach; p Peek;`:``}${n?` n New;`:``}${i?` o Open PR;`:``} g Group; Escape to close; ? Help.`:`↑↓ Navigate s Stop${Le?` a Attach p Peek`:``}${n?` n New`:``}${i?` 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.`,W=e=>x?.action===`attach`&&x.mode!==void 0?`${x.mode===`drive`?`Attach to`:`Peek at`} ${e} to ${fu[x.mode]}?`:`Stop ${e}?`;return V(D,{flexDirection:`column`,...g?{}:{height:ke},children:[V(G,{...U,children:[o?`Background sessions in selected directory`:`Background sessions across projects`,s?` · name filter active`:``,c?` · PR filter active`:``]}),V(G,{...U,children:[k.length,` supervised session(s). Foreground peers and saved records are separate.`]}),l!==void 0&&V(G,{...U,children:[`State: `,l]}),y===`loading`&&B(G,{...U,children:`Loading supervised sessions...`}),y===`unavailable`&&B(G,{...U,children:`Supervised session discovery unavailable; last verified rows remain below.`}),y===`ready`&&k.length===0&&B(G,{...U,children:`No supervised sessions.`}),Ie.map((e,t)=>B(G,{...U,children:e},`trust-${t}`)),T===void 0&&H>0&&!g&&V(G,{children:[H,` more above`]}),(T===void 0?Fe:[]).map(e=>e.kind===`group`?B(G,{...U,children:e.label},`group-${e.label}`):V(G,{...g?{}:{wrap:`truncate-end`},children:[g?ar(e.index):e.row.id===A?`> `:` `,e.row.name&&$(e.row)?g?`${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,y===`ready`&&$(e.row)&&e.row.activity===`idle`&&e.row.nextLoopAt?` ${Cu(e.row.nextLoopAt,te)}`:``,e.row.problem?` ${e.row.problem}`:``,y===`ready`&&$(e.row)&&e.row.pr?` ${e.row.pr.host} ${e.row.pr.kind===`pull`?`#`:`!`}${e.row.pr.number}`:``]},`row-${e.row.id}`)),T===void 0&&!g&&H+Fe.length<Te.length&&V(G,{children:[Te.length-H-Fe.length,` more below`]}),A!==void 0&&V(G,{...U,children:[`Selected `,A]}),N!==void 0&&V(G,{...U,children:[`Name: `,N]}),De!==void 0&&V(G,{...U,children:[`PR: `,De.host,` `,De.kind===`pull`?`#`:`!`,De.number]}),De!==void 0&&V(G,{...U,children:[`URL: `,De.url]}),P&&B(G,{...U,children:P}),ye===`opening`&&B(G,{...U,children:`Opening linked PR...`}),ye===`opened`&&B(G,{...U,children:`Opened linked PR.`}),ye===`failed`&&B(G,{...U,children:`PR link changed or could not be opened.`}),ye===`unavailable`&&B(G,{...U,children:`No verified PR link is available.`}),me===`starting`&&B(G,{...U,children:`Starting a background session...`}),me===`started`&&V(G,{...U,children:[`Started `,ge,s||l!==void 0?` (may be hidden by filter)`:``]}),me===`failed`&&B(G,{...U,children:`Start failed; check workspace trust or run session start --background for details.`}),T!==void 0&&B(G,{...U,children:`y Trust and start / r Start Restricted / n Cancel`}),S!==void 0&&(g?V(G,{children:[W(S),` y Yes / n No`]}):V(z,{children:[B(G,{...U,children:W(`…${S.slice(-8)}`)}),B(G,{...U,children:`y Yes / n No`})]})),S===void 0&&C===`unavailable`&&B(G,{...U,children:`This session cannot be stopped from the view.`}),S===void 0&&le===`unavailable`&&B(G,{...U,children:`This session cannot be attached to from the view.`}),C===`stopping`&&B(G,{...U,children:`Stopping selected session; wait for confirmation.`}),C===`stopped`&&V(G,{...U,children:[`Stopped `,fe]}),C===`failed`&&B(G,{...U,children:`Stop failed; session remains listed until verified otherwise.`}),g&&k.length>0&&S===void 0&&C!==`stopping`&&V(G,{children:[ir(k.length,!0),j.buffer?` ${j.buffer}`:``]}),g&&j.invalid&&B(G,{children:`Selection out of range.`}),B(G,{...U,children:Re}),je&&Ae.map(e=>B(G,{...U,children:e},e))]})}async function Tu(e){e.announce!==!1&&Zc({enabled:e.screenReader,channel:e.screenReaderChannel,hint:e.screenReaderHint});let t,n=O(B(qe,{enabled:e.screenReader,children:B(wu,{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 Eu({providerDefinitions:e,reloadPluginCommandSource:t,userSettingsPath:r,settingsSources:i,formatResumeCommand:a}){return{getUserSettingsPath:()=>r,readSettings:e=>p(e),reloadPluginCommandSource:e=>{t(e)},applyActiveModelChange:(e,t,n)=>(u(i,[_(`user`,r)],t,n),{applied:!0}),getGitBranch:e=>ae(e),getProviderDisplayName:t=>n(e,t)?.displayName??t,...a===void 0?{}:{formatResumeCommand:a}}}function Du(e){return{$schema:e,version:1,bindings:{}}}function Ou(e,t){let n=Jn(JSON.stringify(Du(t)),e);if(!n.ok)throw Error(n.diagnostic.message);return n.snapshot}var ku=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=Ou(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=w(this.filePath);if(await he(e,{recursive:!0}),await this.#u(),this.#s)throw Error(`Keybindings source is disposed.`);this.#i=fe(e,{persistent:!1},(e,t)=>{(t===null||t.toString()===pe(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 he(w(this.filePath),{recursive:!0});try{await _e(this.filePath,`${JSON.stringify(Du(this.#e),null,2)}\n`,{encoding:`utf8`,flag:`wx`,mode:384})}catch(e){if(!ju(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 ge(this.filePath,`utf8`)}catch(e){if(Au(e))return;this.#d({file:this.filePath,path:`$`,message:Nu(e)});return}let t=Jn(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 Au(e){return Mu(e)&&e.code===`ENOENT`}function ju(e){return Mu(e)&&e.code===`EEXIST`}function Mu(e){return e instanceof Error&&`code`in e}function Nu(e){return e instanceof Error?e.message:String(e)}function Pu(e){return new ku(e)}function Fu(e){if(e===`1`)return!0;if(e===`0`)return!1}function Iu(e){if(e.flag!==void 0)return{reducedMotion:e.flag,override:`flag`};let t=Fu(e.env);return t===void 0?{reducedMotion:e.settings}:{reducedMotion:t,override:`environment`}}function Lu(e,t,n){let r=C(e??{}),i=Iu({settings:r.reducedMotion,flag:t,env:n.ROBOTA_REDUCED_MOTION});return{appearance:r,reducedMotion:i.reducedMotion,...i.override===void 0?{}:{reducedMotionOverride:i.override}}}const Ru=me(`.robota`,`themes`),zu=RegExp(`^[A-Za-z0-9._-]{1,24}$`,`u`);function Bu(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(me(t,r.name),n)}))}function Vu(e,t){let n=`load ${t.source} themes`,r=b(t.root);for(let i of Bu(r,t.directory,n)){let n=i.fileName.slice(0,-5);if(!zu.test(n)){let n=Dt(i.fileName);e.skipped.push({id:`${t.idPrefix}${n}`,fileName:Ot(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=Vt({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 Hu(e,t,n,r){let i=ie(e,t,r);try{return h(i,{settingsPath:S(t)}).map(e=>({name:e.manifest.name,pluginDir:e.pluginDir}))}catch(e){let t=kt(i.join(`, `)),r=kt(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 Uu(e){let t={themes:[],skipped:[],claimed:new Set};Vu(t,{root:e.userHome,directory:Ru,source:`user`,idPrefix:`custom:`});let n=e.plugins??Hu(e.cwd,e.userHome,t,e.projectAccess);for(let e of n){if(!zu.test(e.name)){let n=Dt(e.name);t.skipped.push({id:`custom:${n}`,fileName:Ot(e.name),reason:`$: the plugin name ${n} cannot be part of a theme id — its themes are not loaded`});continue}Vu(t,{root:e.pluginDir,directory:`themes`,source:`plugin`,idPrefix:`custom:${e.name}:`})}return{themes:t.themes,skipped:t.skipped}}function Wu(e){let t=Lu(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=Uu({cwd:e.cwd,userHome:e.userHome,...e.projectAccess===void 0?{}:{projectAccess:e.projectAccess}}),i=kc([...We(),...r.themes],r.skipped);return{registry:i,cataloguePort:Mc({registry:i,readAppearance:()=>Lu(p(S()),void 0,{}).appearance,...t.reducedMotionOverride===void 0?{}:{reducedMotionPin:{tier:t.reducedMotionOverride,reducedMotion:t.reducedMotion}}}),skipped:r.skipped,...n}}let Gu=null,Ku=!1;function qu(){return Ku}const Ju=[`string-width`,`setCursorPosition`,`getStringWidth`,`slice`,`charCodeAt`];function Yu(e,t){if(!t)return`rethrow`;let n=e.message??``;return Ju.some(e=>n.includes(e))?`ime-hint`:`guard-owned`}function Xu(e){Gu=e}function Zu(e,t){try{if(Gu){Gu.getSession().reportBackgroundError(e,t);return}}catch{}process.stderr.write(`\n[robota] ${t}: ${e.message}\n`)}function Qu(){Ku||(Ku=!0,process.on(`unhandledRejection`,e=>{Zu(e instanceof Error?e:Error(String(e)),`unhandled rejection`)}),process.on(`uncaughtException`,e=>{Zu(e instanceof Error?e:Error(String(e)),`uncaught exception`)}))}async function $u(e={}){return te(x(process.argv))?(v(oe()),new Promise(()=>void 0)):ce(e,m,{renderApp:cu,renderSupervisedSessionView:Tu,renderAttachedApp:lu,createDefaultTuiCliAdapter:Eu,createNodeKeybindingsSource:Pu,createThemeSurface:Wu,installTuiProcessGuards:Qu,setLiveChannel:Xu})}f(),process.on(`uncaughtException`,e=>{let t=Yu(e,qu());if(t===`ime-hint`){process.stderr.write(`
32
+ _(interrupted)_`:``))}):B(G,{wrap:`wrap`,children:r})})]})});function to({entry:e}){let t=q(),n=Ia(),r=e.data,i=r?.tools,a=r?.summary?.split(`
33
+ `)??[];return i&&i.length>0?V(E,{flexDirection:`column`,marginBottom:1,children:[B(E,{children:B(Za,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),B(G,{children:` `}),i.map((e,r)=>{let i=Va(e,aa(e)?.status===`error`);return V(E,{flexDirection:`column`,children:[V(G,{color:Jt(t,i),children:[` `,Ha(e,i,n)]}),B(Ua,{tool:e}),e.diffLines&&e.diffLines.length>0&&B(Ja,{file:e.diffFile,lines:e.diffLines})]},r)})]}):V(E,{flexDirection:`column`,marginBottom:1,children:[B(E,{children:B(Za,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),B(G,{children:` `}),a.map((e,n)=>V(G,{color:t.text.success,children:[` `,W(e)]},n))]})}function no({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 B(z,{});let i=W(r);return V(E,{flexDirection:`column`,marginBottom:1,children:[B(E,{children:B(Za,{kind:`warning`,text:`System: `,color:t.text.warning})}),B(G,{children:` `}),B(E,{marginLeft:2,children:B(G,{wrap:`wrap`,children:i})})]})}function ro({entry:e}){if(e.category===`chat`){let t=e.data;return B(eo,{message:t})}return e.type===`tool-summary`?B(to,{entry:e}):e.type===`usage-summary`?B(Ya,{entry:e}):e.type===`tool-start`||e.type===`tool-end`?B(z,{}):B(no,{entry:e})}const io=[{keys:`↑↓`,label:`Navigate`},{keys:`Enter`,label:`Select`},{keys:`Esc`,label:`Cancel`}];function ao({items:e,renderItem:t,onSelect:n,onCancel:r,maxVisible:i=3,footerHints:a=io,initialIndex:o=0}){let[s,c]=R(()=>{let t=o>=0&&o<e.length?o:0;return{...bn(t),scrollOffset:Math.max(0,t-i+1)}}),l=L(s),u=N(t=>{let a=Cn(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=jn({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 B(E,{});if(d){let n=or(e.length,!0);return V(E,{flexDirection:`column`,children:[e.map((e,n)=>V(E,{children:[B(G,{children:sr(n)}),t(e,!1)]},n)),V(G,{children:[n,f.buffer.length>0?` ${f.buffer}`:``]}),f.invalid&&B(G,{children:n})]})}let m=wn(s,{itemCount:e.length,maxVisible:i});m!==s&&(l.current=m);let{selectedIndex:h,scrollOffset:g}=m,_=e.slice(g,g+i),ee=g+i<e.length;return V(E,{flexDirection:`column`,children:[g>0&&V(G,{dimColor:!0,children:[` ↑ `,g,` more above`]}),_.map((e,n)=>B(E,{marginBottom:1,children:t(e,g+n===h)},g+n)),ee&&V(G,{dimColor:!0,children:[` ↓ `,e.length-g-i,` more below`]}),B(Y,{hints:a===io?p:a})]})}function oo({label:e,index:t,isCursor:n,isChecked:r,screenReader:i}){let a=q(),o=r?`[x] `:`[ ] `;return i?V(G,{children:[sr(t),o,e]}):V(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?B(cr,{itemCount:e.itemCount,cancellable:!0,buffer:e.numbered.buffer,invalid:e.numbered.invalid}):B(Y,{hints:t})}function lo(e){let t=q(),{title:n,description:r,options:i,cursor:a,selected:o,screenReader:s,numbered:c}=e;return V(E,{flexDirection:`column`,...s?{}:{borderStyle:`round`,borderColor:t.border.attention},paddingX:1,children:[B(G,{color:t.text.warning,bold:!0,children:n}),r!==void 0&&r.length>0&&B(G,{dimColor:!0,children:r}),i.map((e,t)=>B(oo,{label:e.label,index:t,isCursor:t===a,isChecked:o.has(e.value),screenReader:s},e.value)),B(co,{screenReader:s,itemCount:i.length,numbered:c,canConfirm:e.canConfirm,minSelect:e.minSelect})]})}function uo(e){let{options:t,minSelect:n,maxSelect:r,defaultValues:i,onConfirm:a}=e,[o,s]=R(0),[c,l]=R(()=>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 fo({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}=uo({options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o}),m=jn({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 B(lo,{title:e,...t===void 0?{}:{description:t},options:n,cursor:l,selected:d,screenReader:c,canConfirm:h,minSelect:r,numbered:m})}function po(){return{value:``,resolved:!1}}function mo(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`}}:ho(e,n)}function ho(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 go({title:e,description:t,placeholder:n,onSubmit:r,onCancel:i,validate:a,allowEmpty:o=!1,masked:s=!1}){let c=q(),[l,u]=R(()=>po()),d=L(l),f=N(e=>{let t=mo(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 V(E,{flexDirection:`column`,...p?{}:{borderStyle:`round`,borderColor:c.border.attention},paddingX:1,children:[B(G,{color:c.text.warning,bold:!0,children:e}),B(_o,{description:t}),V(E,{marginTop:1,children:[B(G,{color:c.text.accent,children:`> `}),l.value?B(G,{children:s?`*`.repeat(l.value.length):l.value}):n?B(G,{dimColor:!0,children:n}):null,B(G,{color:c.text.accent,children:`█`})]}),l.error&&B(G,{color:c.text.error,children:l.error}),B(Y,{hints:m})]})}function _o({description:e}){return e===void 0||e.length===0?null:B(G,{dimColor:!0,children:e})}const vo={value:``,label:`Type a custom answer…`};function yo({request:e,onAnswer:t}){let n=q(),[r,i]=R(!1),a=e.options??[],o=a.length>0,s=e.maxSelect??1,c=()=>t({type:`cancelled`});if(!o||r)return B(go,{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 B(fo,{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,vo]:[...a],u=e.default?.values?.[0],d=u===void 0?0:Math.max(0,l.findIndex(e=>e.value===u));return V(E,{flexDirection:`column`,children:[B(G,{bold:!0,children:e.title}),e.description!==void 0&&e.description.length>0&&B(G,{dimColor:!0,children:e.description}),B(ao,{items:l,initialIndex:d,maxVisible:e.maxVisible,renderItem:(e,t)=>V(G,{color:t?n.text.accent:void 0,children:[t?`> `:` `,e.label]}),onSelect:e=>{e===vo?i(!0):t({type:`answer`,values:[e.value]})},onCancel:c})]})}const bo=[`Allow [y]`,`Allow always (this session) [s]`,`Allow always (this project) [p]`,`Deny [n]`];function xo(e,t=!0){return[bo[0],`Allow ${e} always (this session) [s]`,t?`Allow ${e} always (this project) [p]`:`Project-wide approval unavailable`,bo[3]]}function So(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`}}:wo(e,t.index);let r=Cn(e,t,{itemCount:bo.length});return r.effect.type!==`select`||r.effect.index===2&&!n?{state:r.state,effect:{type:`none`}}:{state:r.state,effect:{type:`resolve`,decision:Co(r.effect.index)}}}function Co(e){return e===0?!0:e===1?`allow-session`:e===2&&`allow-project`}function wo(e,t){return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`resolve`,decision:Co(t)}}}function To(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 Eo({request:e,armDelayMs:t=450}){let n=q(),r=e.canPersistProjectPermission!==!1,[i,a]=j.useState(()=>bn()),o=j.useRef(i),s=j.useRef(e);if(s.current!==e){s.current=e;let t=bn();o.current=t,a(t)}let[c,l]=j.useState();j.useEffect(()=>{if(t<=0)return;let n=setTimeout(()=>l(e),t);return()=>clearTimeout(n)},[e,t]);let u=t<=0||c===e,d=j.useCallback(t=>{let n=So(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=xo(fe(e.toolName,e.toolArgs),r),m=jn({enabled:f&&u,itemCount:p.length,onSelect:t=>{let n=So(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;j.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?B(lr,{title:La.permissionRequired,description:`${_===void 0?``:`Background agent ${_} wants to run `}${e.toolName} — ${To(e.toolArgs)}${e.requestedByPeer===void 0?``:` (requested by another session: ${e.requestedByPeer})`}`,options:p,buffer:m.buffer,invalid:m.invalid}):V(E,{flexDirection:`column`,borderStyle:`round`,borderColor:u?n.border.attention:n.border.muted,paddingX:1,children:[V(E,{children:[B(G,{color:n.text.warning,bold:!0,children:`[Permission Required]`}),u?null:B(G,{dimColor:!0,children:` keys answer in a moment`})]}),_===void 0?V(G,{children:[`Tool:`,` `,B(G,{color:n.text.accent,bold:!0,children:e.toolName})]}):V(G,{color:n.text.warning,children:[`Background agent `,B(G,{bold:!0,children:_}),` wants to run`,` `,B(G,{color:n.text.accent,bold:!0,children:e.toolName})]}),V(G,{dimColor:!0,children:[` `,To(e.toolArgs)]}),e.requestedByPeer===void 0?null:V(G,{color:n.text.warning,children:[`Requested by another session: `,e.requestedByPeer]}),B(E,{marginTop:1,flexDirection:`column`,children:p.map((e,t)=>{let r=u&&t===i.selectedIndex;return B(E,{children:V(G,{color:r?n.text.accent:void 0,bold:r,dimColor:!u,children:[r?`> `:` `,e]})},e)})}),B(Y,{hints:g})]})}function Do(){return{buffer:``,resolved:!1}}const Oo=[`y`,`yes`],ko=[`n`,`no`];function Ao(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 Oo.includes(t)?{state:{buffer:``,resolved:!0},effect:{type:`select`,index:0}}:ko.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 jo(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:typeof t==`string`?Cn(e,t,{itemCount:n}):{state:{...e,selectedIndex:t.index,resolved:!0},effect:{type:`select`,index:t.index}}}function Mo({message:e,options:t=[`Yes`,`No`],onSelect:n}){let r=q(),[i,a]=R(()=>bn()),o=L(i),s=N(e=>{let r=jo(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]=R(Do),d=L(l);De((e,t)=>{let r=Ao(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?V(E,{flexDirection:`column`,children:[B(G,{children:e}),V(G,{children:[`Answer y or n and press Enter`,l.buffer.length>0?` ${l.buffer}`:``]})]}):V(E,{flexDirection:`column`,borderStyle:`round`,borderColor:r.border.attention,paddingX:1,children:[B(G,{color:r.text.warning,children:e}),B(E,{marginTop:1,children:t.map((e,t)=>B(E,{marginRight:2,children:V(G,{color:t===i.selectedIndex?r.text.accent:void 0,bold:t===i.selectedIndex,children:[t===i.selectedIndex?`> `:` `,e]})},e))}),B(Y,{hints:f})]})}function No(e,t,n,r,i){let[a,o]=R([]),[s,c]=R(!1),[l,u]=R();return F(()=>{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 Po({title:e,items:t,onSelect:n,onBack:r,loading:i,error:a}){let o=q(),[s,c]=R(()=>bn()),l=L(s),u=!i&&!a,d=K(),f=jn({enabled:d&&u,itemCount:t.length,cancellable:!0,onSelect:e=>{let r=t[e];r!==void 0&&n(r.value)},onCancel:r}),p=N(e=>{let i=Cn(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=wn(s,{itemCount:t.length});g!==s&&(l.current=g);let _=g.selectedIndex;return d?B(lr,{title:e,options:i||a?[]:t.map(e=>e.label),description:i?`Loading...`:a,cancellable:!0,buffer:f.buffer,invalid:f.invalid}):V(E,{flexDirection:`column`,borderStyle:`round`,borderColor:o.border.attention,paddingX:1,children:[B(G,{color:o.text.warning,bold:!0,children:e}),i&&B(E,{marginTop:1,children:B(G,{dimColor:!0,children:`Loading...`})}),a&&B(E,{marginTop:1,children:B(G,{color:o.text.error,children:a})}),!i&&!a&&B(E,{flexDirection:`column`,marginTop:1,children:t.map((e,t)=>V(E,{children:[V(G,{color:t===_?o.text.accent:void 0,bold:t===_,children:[t===_?`> `:` `,e.label]}),e.hint&&V(G,{dimColor:!0,children:[` `,e.hint]})]},e.value))}),B(Y,{hints:i?[]:a?h:m})]})}function Fo(e,t){e===`marketplace`?t.push({screen:`marketplace-list`}):e===`installed`&&t.push({screen:`installed-list`})}function Io(e,t){e===`__add__`?t.push({screen:`marketplace-add`}):t.push({screen:`marketplace-action`,context:{marketplace:e}})}function Lo(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 Ro(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 zo(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 Bo(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 Vo(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 Ho({callbacks:e,onClose:t,addMessage:n}){let[r,i]=R([{screen:`main`}]),[a,o]=R(),[s,c]=R(0),l=r[r.length-1]??{screen:`main`},u=N(e=>{i(t=>[...t,e])},[]),d=N(()=>{i(e=>e.length<=1?(t(),e):e.slice(0,-1))},[t]),f=N(e=>{i(n=>{let r=n.slice(0,Math.max(1,n.length-e));return r.length===0?(t(),n):r})},[t]),p=N(e=>{n?.({role:`system`,content:e})},[n]),m=N(()=>{c(e=>e+1)},[]),h=N(e=>o(e),[o]),g={push:N(e=>u({screen:e.screen,context:e.context}),[u]),pop:d,popN:f,notify:p,setConfirm:h,refresh:m},{items:_,loading:ee,error:te}=No(l.screen,l.context?.marketplace,e,s,r.length),v=N(t=>{let n=l.screen,r=l.context;n===`main`?Fo(t,g):n===`marketplace-list`?Io(t,g):n===`marketplace-action`?Lo(t,r?.marketplace??``,e,g):n===`marketplace-browse`?Ro(t,r?.marketplace??``,_,g):n===`marketplace-install-scope`?zo(t,r?.pluginId??``,e,g):n===`installed-list`?Bo(t,e,g):n===`installed-action`&&Vo(t,r?.pluginId??``,e,g)},[l,_,e,u,d,f,p,o,m]),ne=N(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 B(Mo,{message:a.message,onSelect:e=>{e===0?a.onConfirm():a.onCancel()}});let y=l.screen;return y===`marketplace-add`?B(go,{title:`Add Marketplace Source`,placeholder:`owner/repo or git URL`,onSubmit:ne,onCancel:d,validate:e=>e.includes(`/`)?void 0:`Must be owner/repo or a git URL`}):y===`marketplace-action`?B(Po,{title:`Marketplace: ${l.context?.marketplace??``}`,items:[{label:`Browse plugins`,value:`browse`},{label:`Update`,value:`update`},{label:`Remove`,value:`remove`}],onSelect:v,onBack:d},r.length):y===`marketplace-install-scope`?B(Po,{title:`Install scope for "${l.context?.pluginId??``}"`,items:[{label:`User scope`,value:`user`},{label:`Project scope`,value:`project`}],onSelect:v,onBack:d},r.length):y===`installed-action`?B(Po,{title:`Plugin: ${l.context?.pluginId??``}`,items:[{label:`Uninstall`,value:`uninstall`}],onSelect:v,onBack:d},r.length):B(Po,{title:{main:`Plugin Management`,"marketplace-list":`Marketplace`,"marketplace-browse":`Browse: ${l.context?.marketplace??``}`,"installed-list":`Installed Plugins`}[y]??`Plugin Management`,items:{main:[{label:`Marketplace`,value:`marketplace`},{label:`Installed Plugins`,value:`installed`}]}[y]??_,onSelect:v,onBack:d,loading:ee,error:te},`${y}-${r.length}-${s}`)}function Uo({notices:e}){let t=q();return e.length===0?null:B(E,{flexDirection:`column`,paddingX:1,children:e.map(e=>B(G,{color:t.text.muted,children:e.message},e.id))})}function Wo(e){let t=e.startsWith(`session_`)?e.slice(8):e;return t===``?e:t.slice(0,8)}function Go(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 Ko({sessions:e,onSelect:t,onCancel:n}){let r=q();return V(E,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[B(G,{bold:!0,color:r.text.accent,children:`Select a session to resume:`}),B(ao,{items:[...e],renderItem:(e,t)=>{let n=Go(e),i=e.preview?e.preview.slice(0,60)+(e.preview.length>60?`...`:``):``;return V(G,{children:[t?`> `:` `,B(G,{bold:!0,children:e.name??Wo(e.id)}),` `,B(G,{dimColor:!0,children:new Date(e.updatedAt).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}),` `,V(G,{dimColor:!0,children:[`msgs: `,e.messageCount]}),n===null?null:V(z,{children:[` `,B(G,{color:r.text.success,children:n})]}),i?V(z,{children:[`
34
+ `,B(G,{dimColor:!0,children:i})]}):null]})},onSelect:e=>t(e.id),onCancel:n})]})}function qo(e){let t=Jo(e),n=e.hasPendingPrompt&&t.kind!==`queued`?[`queued`]:[],r=[t.label,...n].join(` · `);return{...t,segments:n,text:r}}function Jo(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 Yo=` | `;function Xo(e,t){return e>=90?t.text.error:e>=70?t.text.warning:t.text.success}function Zo({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r}){let i=q(),a=qo({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r});return B(G,{color:i.text[a.tone],bold:a.kind!==`idle`,children:a.text})}function Qo({percentage:e,usedTokens:t,maxTokens:n}){return V(G,{color:Xo(e,q()),children:[`Context: `,Math.round(e),`% (`,i(t),`/`,i(n),` tokens)`]})}function $o(){return B(G,{color:q().text.warning,bold:!0,children:`Observing — read only`})}function es({permissionMode:e}){return V(z,{children:[B(G,{color:q().text.accent,bold:!0,children:`Mode:`}),` `,B(G,{children:e})]})}function ts(e,t){return t||e!=="default"}function ns({activePresetId:e}){return V(z,{children:[B(G,{color:q().text.accent,bold:!0,children:`Preset:`}),` `,B(G,{children:e})]})}function rs(e){return e!==void 0&&e!=="default"}function is({modelName:e,providerDisplayName:t,effort:n}){return V(G,{dimColor:!0,children:[t===void 0?e:`${t} ${e}`,n===void 0?``:` Effort: ${n}`]})}function as(e){let t=q(),n=e.showGitBranch&&e.gitBranch!==void 0&&e.gitBranch.length>0,r=K(),i=ts(e.permissionMode,r),a=e.activePresetId,o=rs(a);return V(G,{children:[e.readOnly&&V(z,{children:[B($o,{}),!r&&Yo]}),!r&&B(Zo,{isThinking:e.isThinking,activeToolCount:e.activeToolCount,activeBackgroundTaskCount:e.activeBackgroundTaskCount,hasPendingPrompt:e.hasPendingPrompt}),i&&V(z,{children:[Yo,B(es,{permissionMode:e.permissionMode})]}),o&&V(z,{children:[Yo,B(ns,{activePresetId:a})]}),e.sessionName&&V(z,{children:[Yo,B(G,{color:t.text.session,children:e.sessionName})]}),n&&V(z,{children:[Yo,V(G,{dimColor:!0,children:[`git: `,e.gitBranch]})]}),Yo,B(is,{modelName:e.modelName,providerDisplayName:e.providerDisplayName,effort:e.effort}),!r&&V(z,{children:[Yo,B(Qo,{percentage:e.contextPercentage,usedTokens:e.contextUsedTokens,maxTokens:e.contextMaxTokens})]})]})}function os({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 ee=q();return V(E,{paddingLeft:1,paddingRight:1,justifyContent:`space-between`,children:[B(as,{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&&V(G,{color:ee.text.warning,bold:!0,children:[`[`,m,`]`]})]})}const ss=M(null),cs=ss.Provider;function ls(){let e=P(ss);if(!e)throw Error(`TuiCliAdapterContext not provided`);return e}function us({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 _=ls(),ee=I(()=>_.getGitBranch(e),[_,e,h]),te=I(()=>r===void 0?void 0:_.getProviderDisplayName(r),[_,r]);return d.enabled?B(os,{permissionMode:t,modelName:n??``,providerDisplayName:te,sessionId:i,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextPercentage:l.percentage,contextUsedTokens:l.usedTokens,contextMaxTokens:l.maxTokens,sessionName:u,gitBranch:ee,showGitBranch:d.gitBranch,activeAgentLabel:f,activePresetId:p,effort:m,readOnly:g}):g?B($o,{}):null}function ds(e,t){let n=Yt(e);return{color:Jt(t,n),icon:qt[n],strikethrough:n===`error`||n===`denied`}}function fs({isThinking:e}){let t=q();return e?B(E,{marginBottom:1,children:B(G,{color:t.text.warning,children:`Thinking...`})}):B(z,{})}function ps({activeTools:e}){let t=q(),n=Ia();return V(E,{flexDirection:`column`,marginBottom:1,children:[B(G,{color:t.text.emphasis,bold:!0,children:`Tools:`}),B(G,{children:` `}),e.map((e,r)=>{let{color:i,icon:a,strikethrough:o}=ds(e,t);return V(E,{flexDirection:`column`,children:[V(G,{color:i,strikethrough:o,children:[` `,a,` `,Aa(e.toolName,n),`(`,ja(e.firstArg),`)`]}),e.diffLines&&e.diffLines.length>0&&B(Ja,{file:e.diffFile,lines:e.diffLines})]},`${e.toolName}-${r}`)})]})}function ms(e,t,n,r){let i=t.map(e=>Aa(e.toolName,r)).join(`, `),a=[i.length>0?`${La.tool} ${i}`:void 0,e.length>0?e:n?La.thinking:void 0].filter(e=>e!==void 0);return a.length===0?B(z,{}):B(G,{children:a.join(` — `)})}function hs({text:e,activeTools:t,isThinking:n=!1}){let r=q(),i=Oa(),a=t.length>0,o=e.length>0,s=K(),c=Fa(),l=Ia();return s?ms(e,t,n,l):!a&&!o?B(fs,{isThinking:n}):V(E,{flexDirection:`column`,children:[a&&B(ps,{activeTools:t}),o&&V(E,{flexDirection:`column`,marginBottom:1,children:[V(G,{color:r.text.accent,bold:!0,children:[c,`:`]}),B(G,{children:` `}),B(E,{marginLeft:2,children:B(He,{wrap:`wrap`,children:i(e)})})]})]})}function gs(e,t){let n=t?` (current)`:``;return`${e.name} — ${e.appearance}, ${e.source}${n}`}function _s({theme:e,isFocused:t,isActive:n,rowNumber:r}){let i=q(),a=r===void 0?t?`> `:` `:sr(r);return V(G,{...t&&r===void 0?{color:i.text.accent,bold:!0}:{},children:[a,gs(e,n)]})}function vs({itemCount:e,buffer:t,invalid:n}){let r=or(e,!0);return V(E,{flexDirection:`column`,children:[V(G,{children:[r,t.length>0?` ${t}`:``]}),n&&B(G,{children:r})]})}function ys(e,t){let n=e.findIndex(e=>e.id===t);return n<0?0:n}function bs(e){let[t,n]=j.useState(()=>({syntaxHighlighting:e.syntaxHighlighting,reducedMotion:e.reducedMotion}));return{toggles:t,setToggles:n}}function xs(e){let{themes:t,activeThemeId:n,preview:r}=e,[i,a]=j.useState(()=>ys(t,n));return{focusedIndex:i,move:j.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 Ss(e,t){let{themes:n,select:r,cancel:i}=e,{focusedIndex:a,move:o}=xs(e),{toggles:s,setToggles:c}=bs(e),l=j.useRef(s);l.current=s;let u=j.useCallback(e=>{let t=n[e];t&&r(t.id,l.current)},[r,n]),d=jn({enabled:t&&n.length>0,itemCount:n.length,cancellable:!0,onSelect:u,onCancel:i}),f=j.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 Cs({themes:e,activeThemeId:t,focusedIndex:n,screenReader:r}){return e.length===0?B(G,{dimColor:!0,children:`No themes installed`}):B(z,{children:e.map((e,i)=>B(_s,{theme:e,isFocused:i===n,isActive:e.id===t,...r?{rowNumber:i}:{}},e.id))})}function ws(){return Xe()?B(z,{}):B(G,{dimColor:!0,children:`Colour is off for this terminal — themes apply, previews cannot show.`})}function Ts({skipped:e}){return e.length===0?B(z,{}):B(E,{flexDirection:`column`,marginTop:1,children:e.map((e,t)=>B(G,{dimColor:!0,children:` Skipped "${e.fileName}" — ${e.reason}`},t))})}function Es({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 V(E,{flexDirection:`column`,children:[B(G,{dimColor:!0,children:`syntax ${r(e.syntaxHighlighting)} · motion ${r(!e.reducedMotion)}${i}`}),n&&B(G,{dimColor:!0,children:`Change with /theme syntax on|off or /theme motion on|off`})]})}function Ds({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?B(vs,{itemCount:t,buffer:n.buffer,invalid:n.invalid}):B(Y,{hints:r})}function Os({picker:e}){let t=q(),n=K(),{themes:r,activeThemeId:i}=e,{focusedIndex:a,toggles:o,numbered:s}=Ss(e,n);return V(E,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.focused},paddingX:1,children:[B(G,{color:t.text.accent,bold:!0,children:`Theme`}),B(ws,{}),B(Es,{toggles:o,reducedMotionPin:e.reducedMotionPin,screenReader:n}),B(E,{flexDirection:`column`,marginTop:1,children:B(Cs,{themes:r,activeThemeId:i,focusedIndex:a,screenReader:n})}),B(Ts,{skipped:e.skipped}),B(Ds,{screenReader:n,itemCount:r.length,numbered:s})]})}function ks({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 B(E,{children:B(G,{color:t?n.text.accent:void 0,bold:t,children:`${i} ${e.transport.name.padEnd(18)} ${a} ${s}`})})}function As(e,t,n,r,i,a,o,s,c){Q(`transport-settings`,N(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 js({registry:e,onClose:t}){let n=q(),r=Fa(),[i,a]=R(()=>e.getAll()),[o,s]=R(0),[c,l]=R(!1),[u,d]=R(void 0),f=N(()=>{a(e.getAll())},[e]),p=Z(`transport-settings`,[[[`previous`,`next`],`Select`],[`toggle`,`Toggle`],[`close`,`Close`]]);return As(i,o,c,e,s,l,d,t,f),V(E,{flexDirection:`column`,paddingX:2,paddingY:1,children:[B(G,{bold:!0,children:`Settings › Transports`}),B(E,{marginTop:1,flexDirection:`column`,children:i.map((e,t)=>B(ks,{entry:e,selected:t===o},e.transport.name))}),V(E,{marginTop:1,flexDirection:`column`,children:[B(Y,{hints:p}),V(G,{dimColor:!0,children:[`A toggle is saved now and applies the next time `,r,` starts.`]})]}),c&&B(E,{marginTop:1,children:B(G,{color:n.text.warning,children:`Saving…`})}),u!==void 0&&B(E,{marginTop:1,children:B(G,{color:n.text.error,children:`Not saved — ${u}`})})]})}function Ms({message:e}){return B(E,{paddingX:1,marginBottom:1,children:B(G,{color:q().text.warning,children:e})})}function Ns({model:e}){return B(D,{items:e.staticItems,children:e=>e.kind===`banner`?B(Wt,{version:e.version},`logo`):B(ro,{entry:e.entry},e.entry.id)},e.transcriptKey)}function Ps({model:e}){let t=q(),{background:n,stream:r}=e;return V(E,{flexDirection:`column`,paddingX:1,flexGrow:1,children:[n.selectedEntry&&n.selectedEntry.kind!==`main_thread`&&B(vn,{entry:n.selectedEntry,page:n.detail.page,loading:n.detail.loading,error:n.detail.error}),e.isShuttingDown&&B(G,{color:t.text.warning,children:`Shutting down...`}),(r.isThinking||r.activeTools.length>0)&&V(E,{flexDirection:`column`,marginBottom:1,children:[B(hs,{text:r.text,activeTools:r.activeTools,isThinking:r.isThinking}),r.isStalled&&B(G,{color:t.text.warning,children:`⚠ Still waiting on the provider — the network may be stalled. Esc to interrupt.`})]}),!r.isThinking&&r.lastErrorMessage&&B(G,{color:t.text.error,children:`✖ Last turn failed — the session is alive; type your next prompt when ready.`}),B(gn,{entries:n.entries,focusedIndex:n.focusedIndex})]})}function Fs({model:e}){if(e.coordinationError!==void 0||e.coordinationPending)return B(z,{});let{background:t,plugin:n,sessionPicker:r,transport:i}=e,a=e.pendingUserAction;return V(z,{children:[t.switcherVisible&&B(dr,{snapshot:t.snapshot,selectedEntryId:t.selectedEntryId,onSelect:t.select,onClose:t.closeSwitcher,onAttach:t.attachToFork}),e.permissionRequest&&B(Eo,{request:e.permissionRequest}),a&&B(yo,{request:a,onAnswer:t=>e.resolveUserAction(a,t)}),n.visible&&B(Ho,{callbacks:n.callbacks,onClose:n.close,addMessage:e=>n.addMessage(e.content)}),i.visible&&i.registry&&B(js,{registry:i.registry,onClose:i.close}),r.visible&&B(Ko,{sessions:r.sessions,onSelect:r.select,onCancel:r.cancel}),e.theme.picker.visible&&B(Os,{picker:e.theme.picker})]})}function Is({model:e}){let{input:t}=e;return V(z,{children:[B(_n,{percentage:e.contextPercentage}),B(ra,{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}),B(us,{...e.status})]})}function Ls({viewModel:e}){let t=q(),n=ar();return V(E,{flexDirection:`column`,children:[B(Ns,{model:e}),!e.handoffSuspended&&V(z,{children:[e.updateNotice&&B(Ms,{message:e.updateNotice}),e.coordinationError&&V(G,{color:t.text.error,children:[e.coordinationError,` Press Enter to retry.`]}),n.diagnostic&&B(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=>B(G,{color:t.text.warning,children:`Keybindings ${e.path}: ${e.message}`},`${e.path}:${e.code}`)),e.theme.unknownThemeNotice!==void 0&&B(G,{color:t.text.warning,children:e.theme.unknownThemeNotice}),B(Uo,{notices:e.sessionEventNotices}),B(Ps,{model:e}),B(Fs,{model:e}),B(Is,{model:e})]})]})}function Rs(e){return[...e.screenReader?[]:[{kind:`banner`,version:e.version??`0.0.0`}],...e.history.map(e=>({kind:`entry`,entry:e}))]}function zs(e){let t=e.forceExit??(e=>process.exit(e));if(e.isShuttingDown){t(130);return}e.graceful()}function Bs(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 Vs={promptStart:`A`,promptEnd:`B`,turnStart:`C`,turnEnd:`D`};function Hs(e){return`\x1b]133;${Vs[e]}\x07`}function Us(e){let t=e.write??(e=>{process.stdout.write(e)});return{emit(n){!e.enabled||!e.supported()||t(Hs(n))}}}function Ws(e,t){return e.executionId??`${e.toolName}#${t}`}function Gs(e){let t=new Set;return e.forEach((e,n)=>{e.isRunning&&t.add(Ws(e,n))}),t}function Ks(e){let{enabled:t,isThinking:n,activeTools:r,awaitingAnswer:i}=e,a=I(()=>Bs({enabled:t}),[t]),o=Kr(),s=Yr(),c=I(()=>Us({enabled:t,supported:()=>Qe({override:s.turnMarks}),write:e=>o.write(e)}),[t,o,s.turnMarks]),l=L(!1),u=L(new Set);F(()=>{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]),F(()=>{c.emit(`promptStart`)},[c]),F(()=>{i&&a.promptMounted()},[i,a]),F(()=>{let e=Gs(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 qs(e){return!!(e.permissionRequest||e.pendingUserAction||e.pluginVisible||e.transportVisible||e.sessionPickerVisible||e.workspaceSwitcherVisible||e.historySearchOpen||e.themePickerVisible||e.coordinationBlocked)}function Js(e){Q(e.isThinking?`thinking`:`background-detail`,t=>{if(qs(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 Ys(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 Xs(e){Q(`recovery`,t=>{e.recoveryError!==void 0&&!e.recoveryPending&&t.includes(`retry`)&&e.retryRecovery()})}function Zs(e,t){return e===``||t&&e===`]`}function Qs(e){let{exit:t}=Te(),n=n=>{zs({isShuttingDown:e.isShuttingDown,graceful:()=>void e.shutdown(n).finally(()=>t())})};De((t,r)=>{(r.ctrl&&t===`c`||e.attached&&Zs(t,r.ctrl))&&n(`prompt_input_exit`)}),F(()=>{let e=()=>n(`other`);return process.on(`SIGINT`,e),process.on(`SIGTERM`,e),()=>{process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}})}function $s(e){Js(e),Xs(e),Ys(e),Qs(e);let t=K();return Ks({enabled:t,isThinking:e.isThinking,activeTools:e.activeTools,awaitingAnswer:e.permissionRequest!==null||e.pendingUserAction!==null}),t}function ec(){return Promise.reject(Error(`Plugin management is unavailable in this host.`))}function tc(){return{listInstalled:ec,listAvailablePlugins:ec,install:ec,uninstall:ec,enable:ec,disable:ec,marketplaceAdd:ec,marketplaceRemove:ec,marketplaceUpdate:ec,marketplaceList:ec,reloadPlugins:ec}}function nc(e){return e??tc()}function rc(e){return I(()=>nc(e),[e])}function ic(e){let n=rc(e.pluginAdapter),r=N(n=>e.addEntry(a(t(n))),[e.addEntry]),i=N(t=>{e.setSessionPickerVisible(!1),e.onSessionSwitch(t)},[e.onSessionSwitch,e.setSessionPickerVisible]),o=N(()=>{e.setSessionPickerVisible(!1),e.addEntry(a(t(`Session resume cancelled.`)))},[e.addEntry,e.setSessionPickerVisible]),s=e.hostSessions??C(e.sessionStore,e.cwd),c=e.sessionPickerVisible&&s.length===0;return F(()=>{c&&(e.setSessionPickerVisible(!1),e.addEntry(a(t(`No saved sessions to resume in this workspace.`))))},[c,e.addEntry,e.setSessionPickerVisible]),{plugin:{visible:e.pluginVisible,callbacks:n,close:()=>e.setPluginVisible(!1),addMessage:r},transport:{visible:e.transportVisible,registry:e.transportRegistry,close:()=>e.setTransportVisible(!1)},sessionPicker:{visible:e.sessionPickerVisible&&!c,sessions:s,select:i,cancel:o}}}function ac(e){let[t,n]=R(0),r=N(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=N(async e=>{n(e=>e+1),await r(e)},[r]),a=L(!1);return F(()=>{a.current&&!e.isThinking&&n(e=>e+1),a.current=e.isThinking},[e.isThinking]),{submit:i,gitRefreshToken:t}}function oc(e){let{screens:t,workspace:n}=e.shell,r=ac({selectedEntry:n.background.selectedEntry,submit:t.handleSubmit,sendAgentJob:e.state.sendAgentJob,isThinking:e.state.isThinking}),i=$s({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:ic({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 sc(e){let t=Fa();F(()=>{let n=W(e??``),r=W(t),i=n?`${r} — ${n}`:r;process.stdout.write(`\x1b]0;${i}\x07`)},[e,t])}function cc(e){let[t,n]=R(!1);return F(()=>{if(e)return e.registerSuspendHooks({suspend:async()=>{n(!0),await new Promise(e=>setTimeout(e,50))},resume:()=>n(!1)})},[e]),t}function lc(e){let[t,n]=R(),[r,i]=R(!0),a=N(()=>{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 F(()=>{a()},[e,a]),{startError:t,startPending:r,retryStart:a}}function uc(e){let[t,n]=R();return F(()=>{let t=!0;return e?.then(e=>{t&&e!==void 0&&n(e)}).catch(()=>{}),()=>{t=!1}},[e]),t}function dc(e,t){let n=lc(e),[r,i]=R(e.sessionName);return F(()=>{e.sessionName!==void 0&&e.sessionName!==r&&i(e.sessionName)},[e,e.sessionName,r]),sc(r),{sessionName:r,setSessionName:i,handoffSuspended:cc(e.terminalHandoffController),updateNotice:uc(t),...n}}function fc(e){return v(e.readSettings(e.getUserSettingsPath()))}function pc(){let e=ls(),[t,n]=R(()=>fc(e));return[t,N(()=>{n(fc(e))},[e])]}function mc(e){let[t,n]=R(null),[r,i]=R(),[a,o]=R(!1),{entry:s,snapshot:c,read:l}=e;return F(()=>{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 hc(e,t){let n=c(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 gc({sessionStore:e,onSessionSwitch:n,addEntry:r}){let i=ls();return N(o=>{let s=e=>r(a(t(e)));if(e===void 0){s(`This surface has no session store, so it cannot attach to a forked session.`);return}hc(o,{hasSessionRecord:t=>e.load(t).status===`valid`,switchSession:n,notify:s,...i.formatResumeCommand===void 0?{}:{formatResumeCommand:i.formatResumeCommand}})},[r,i,n,e])}function _c(e){let{snapshot:t,selectedEntryId:n}=e,r=I(()=>t?.entries.find(e=>e.id===n),[t,n]);return{entry:r,detail:mc({entry:r,snapshot:t,read:e.read}),attachToFork:gc({sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.addEntry})}}function vc(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 yc(e,t,n,r,i){Q(`background-list`,i=>{if(e===null)return;let a=vc(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 bc(e,t,n){let[r,i]=R(null);return F(()=>{i(t=>t===null||e.length===0?null:Math.min(t,e.length-1))},[e.length]),yc(r,e,i,t,n),{focusedIndex:r,focusList:N(()=>{e.length>0&&i(0)},[e.length])}}function xc(e){return{open:N(()=>e(!0),[e]),toggle:N(()=>e(e=>!e),[e]),close:N(()=>e(!1),[e])}}function Sc(e){let t=I(()=>en(e.snapshot),[e.snapshot]),{focusedIndex:n,focusList:r}=bc(t.map(e=>e.id),e.select,e.navigationEnabled),i=_c({selectedEntryId:e.selectedEntryId,snapshot:e.snapshot,read:e.read,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.addEntry}),a=xc(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:tn(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 Cc(e,t,n){let r=e=>{if(e.requesterDriverId===h)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 wc(e){let t=L(e);return t.current=e,t}function Tc({uiEventPort:e,baseHandleSubmit:t,setSessionName:n,refreshStatusLineSettings:r,refreshAppearanceSettings:i,showSessionPickerOnStart:a,openAgentSwitcher:o}){let[s,c]=R(!1),[l,u]=R(a??!1),[d,f]=R(!1),[p,m]=R(!1),h=wc({setSessionName:n,refreshStatusLineSettings:r,refreshAppearanceSettings:i,openAgentSwitcher:o});return Ae(()=>Cc(e,{setShowPluginTUI:c,setShowTransportTUI:f,setShowSessionPicker:u,setShowThemePicker:m},h),[e]),{handleSubmit:N(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 Ec(e){let t={..._},n=e.statusline;return Dc(n)?{enabled:typeof n.enabled==`boolean`?n.enabled:t.enabled,gitBranch:typeof n.gitBranch==`boolean`?n.gitBranch:t.gitBranch}:t}function Dc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Oc(e){return Ec(e.readSettings(e.getUserSettingsPath()))}function kc(){let e=ls(),[t,n]=R(()=>Oc(e));return[t,N(()=>{n(Oc(e))},[e])]}function Ac(e){let[t,n]=R(!1),[r,i]=R(!1),[a,o]=kc(),[s,c]=pc(),l=Tc({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:Sc({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 jc(e=Ke(),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===Ge)return{theme:qe(n.get(Ge))};let t=n.get(e);return t?{theme:t}:{theme:qe(n.get(Ge)),unknownId:e}}}}function Mc(e){return`Theme "${e}" is not installed — using "${Ge}".`}function Nc(e){return{id:e.id,name:e.name,appearance:e.appearance,source:e.source}}function Pc(e){return{listThemes:()=>e.registry.list().map(Nc),getTheme:t=>{let n=e.registry.get(t);return n?Nc(n):void 0},getAppearance:()=>({settings:e.readAppearance(),...e.reducedMotionPin===void 0?{}:{reducedMotionPin:e.reducedMotionPin}})}}function Fc(e){let t=I(()=>e.registry??jc(),[e.registry]),[n,r]=R(void 0),i=I(()=>t.resolve(n??e.appearance.theme),[t,n,e.appearance.theme]),{setVisible:a,submit:o}=e,s=N(()=>{r(void 0),a(!1)},[a]),{syntaxHighlighting:c,reducedMotion:l}=e.appearance,u=N((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:Mc(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 Ic(e){let[,t]=R(0);F(()=>e.subscribe(()=>t(e=>e+1)),[e]);let n=e.getSnapshot(),r=N(t=>e.selectExecutionWorkspaceEntry(t),[e]),i=N(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 Lc(e,t){let n=e.sessionSwitchError??t.startError,r=!!(e.sessionSwitchPending||t.startPending);return{error:n,pending:r,blocked:n!==void 0||r}}function Rc(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 zc(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:Rc(e)}}function Bc(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 Vc(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:zc(e),status:Bc(e)}}function Hc(e,t){return Fc({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 Uc(e,t){let[n,r]=R(e);return{initialValue:n,consumeInitialValue:N(()=>r(void 0),[]),externalPromptOrigin:t===`external-link`}}function Wc(e,t,n){return I(()=>Rs({history:e,version:t,screenReader:n}),[e,n,t])}function Gc(e){let t=Uc(e.initialInput,e.initialInputOrigin),n=Ic(e.channel),r=dc(e.channel,e.startupUpdateNotice),i=Lc(e,r),a=Ac({state:n,setSessionName:r.setSessionName,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,showSessionPickerOnStart:e.showSessionPickerOnStart,coordinationBlocked:i.blocked}),o=oc({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=Vc({props:e,state:n,lifecycle:r,shell:a,interaction:o,staticItems:Wc(n.history,e.version,o.screenReader),runtime:n.getRuntimeStatusSnapshot(e.permissionMode??`default`),coordination:i,theme:Hc(e,a)});return{...s,input:{...s.input,...t}}}function Kc(e){let t=Gc(e);return B(rt,{theme:t.theme.resolved,reducedMotion:t.theme.reducedMotion,syntaxHighlighting:t.theme.syntaxHighlighting,children:B(Ls,{viewModel:t})})}function qc(e){let[t,n]=R(()=>({channel:e.createChannel(e.resumeSessionId),sessionId:e.resumeSessionId})),[r,i]=R(e.showSessionPickerOnStart??!1),[a,o]=R(),[s,c]=R(!1),[l,u]=R(),d=L(!1),f=L(!0);F(()=>()=>{f.current=!1},[]);let p=N(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:N(()=>{l!==void 0&&p(l)},[l,p])}}function Jc(e){let t=qc(e);return B(cs,{value:e.cliAdapter,children:B(Kc,{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 Yc=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 Xc(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 Zc=class extends be{source;hooks;onData=e=>{let t=Xc(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 Qc(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 $c(e,t=e=>{process.stdout.write(e)}){let n=Qc(e);n!==void 0&&t(`${n}\n`)}function el(e){return e??(e=>{process.stderr.write(`${e}\n`)})}function tl(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 nl(e){if(!e.enabled)return{startupQuietMs:0,preparkMs:0};let t=el(e.warn);return{startupQuietMs:tl(e.overrides?.startupQuiet?.raw,e.overrides?.startupQuiet?.label??`startup quiet period`,900,6e5,t),preparkMs:tl(e.overrides?.prepark?.raw,e.overrides?.prepark?.label??`pre-write park`,50,5e3,t)}}function rl(e){return e?.isTTY!==!0||typeof e.setRawMode!=`function`?()=>{}:(e.setRawMode(!0),()=>{e.setRawMode?.(!1)})}async function il(e,t){if(e<=0)return`elapsed`;let n=rl(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 al(e){return typeof e==`string`?e:Buffer.from(e).toString(`utf8`)}function ol(e){return W(e).trim().length>0}var sl=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=al(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&&ol(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 cl(e){return new sl(e)}function ll(e){return{armEchoRelease:()=>e.armEchoRelease(),write:t=>{e.write(t)}}}function ul(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 dl=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 fl=new Set([`completed`,`failed`,`stopped`]);var pl=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 gl(`While away ${hl(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&&fl.has(n);if(!fl.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} ${ml(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} ${ml(this.errorCount,`error`)}`),e}reset(){this.turnsFinished=0,this.wakeTurnsFinished=0,this.needsInputCount=0,this.errorCount=0,this.reachedTerminal.clear()}};function ml(e,t){return e===1?t:`${t}s`}function hl(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 gl(e){return e.length<=120?e:`${e.slice(0,119)}…`}var _l=class{options;recap=new pl;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 vl(e){return/not initialized/i.test(e.message)}function yl(e){let t=e.isBenignError??vl,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 bl(e,n,r,i,o){if(e.data?.pluginRegistryReloaded===!0&&o?.(r),i.addEntry(a(t(e.message))),n.isInitialized){let e=n.getContextState();i.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})}}function xl(e){let t=e.slice(1).split(/\s+/);return{name:t[0]?.toLowerCase()??``,args:t.slice(1).join(` `)}}var Sl=class extends AggregateError{},Cl=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 Sl&&(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)}},wl=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()}}},Tl=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 El(e,t){let n=null;try{n=t.getActiveDriverId?.()??null}catch{n=null}return a(r(e,n?{metadata:{driverId:n}}:{}))}function Dl(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 Ol(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 kl=class{options;bindings=[];constructor(e){this.options=e}wire(){if(this.bindings.length>0)return;let{session:e,manager:t,attention:n}=this.options,r=n=>{t.addUserEcho(El(n,e))},i=()=>t.syncHistory(e.getFullHistory());this.bind(`user_message`,r),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),n?.onComplete(),i()}),this.bind(`interrupted`,t.onInterrupted),this.bind(`error`,e=>{t.onError(e),n?.onError(),i()}),this.bind(`context_update`,t.onContextUpdate),this.bind(`compact`,i),this.bind(`skill_activation`,i),this.bind(`memory_event`,i),this.bind(`execution_workspace_event`,e=>{t.syncExecutionWorkspaceSnapshot(e.snapshot),n?.onWorkspaceSnapshot(e.snapshot)}),this.bind(`history_cleared`,()=>t.clearHistory()),this.bind(`turn_source`,e=>n?.onTurnSource(e)),Dl(this.bind.bind(this),t),this.bind(`permission_request`,({id:t,toolName:r,toolArgs:i,canPersistProjectPermission:a,requesterDriverId:s,requester:c})=>{n?.onNeedsInput();let l=s?.startsWith(`peer:`)?o(s):void 0;this.options.requestPermission(r,i,t,a,l,c).then(n=>e.resolvePermission(t,n)).catch(()=>e.resolvePermission(t,!1))}),this.bind(`ask_request`,({id:t,request:r})=>{n?.onNeedsInput(),this.options.askUser(r,t).then(n=>e.resolveAsk(t,n)).catch(()=>e.resolveAsk(t,{type:`cancelled`}))}),this.bind(`prompt_resolved`,({id:e})=>this.options.dismissPrompt(e)),n?.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){Ol(this.options.session,e,t,t=>{let n=this.options.onDeliveryError;n?n(t,e):this.options.manager.addSessionEventDeliveryError(t,e)},this.bindings)}};function Al(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.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 jl(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 Ml=class{sequence=0;notices=[];add(e){this.append(jl(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 Nl(e,t){let n=null;return{schedule(){n||=setTimeout(()=>{n=null,e()},t)},flush(){n&&=(clearTimeout(n),null)}}}var Pl=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 Ml;sessionEventNotices=this.sessionNoticeStore.notices;onChange=null;streamBuf=``;debouncedStreamNotify=Nl(()=>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 Fl(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 Il=15e3;var Ll=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 Pl,this.stateManager.onChange=()=>this.onChange?.(),this.userActions=new wl(()=>this.onChange?.()),this.permissions=new Tl(()=>this.onChange?.()),this.interactiveSession=this.createSession(),this.registry=this.createRegistry(),this.attention=this.createAttention(e.attention),this.eventProjector=new kl({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 Cl({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(t(`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 Sl([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 d(Al(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=Fl(await this.interactiveSession.stopWaitingSelfPacedLoop(`Loop stopped by Esc`));e!==void 0&&this.addEntry(a(t(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:n,args:r}=xl(e),i=await this.interactiveSession.executeCommand(n,r);if(i){if(i.data?.sessionExecution===!0){this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}bl(i,this.interactiveSession,this.registry,this.stateManager,this.opts.reloadPluginCommandSource);return}this.stateManager.addEntry(a(t(`Unknown command "/${n}". 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=yl({check:()=>this.runInitCheck(),intervalMs:200,timeoutMs:Il,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 _l({source:e,onRecap:e=>this.stateManager.addAttentionRecap(e)})}onInitFailure(e){let t=e.kind===`timeout`?`Session initialization timed out after ${Il/Gt}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 Rl(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 zl=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&&Rl(e,t.content));return r===-1?!0:(e=r+1,!1)})}};const Bl=`appearance-settings-patch`;function Vl(e){return e instanceof Error?e.message:String(e)}function Hl(e){return{result:{success:!1,message:e},uiIntents:[]}}function Ul(e,t){return e?.commands.find(e=>e.name===t)}async function Wl(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!==Bl)return Hl(`Cannot apply '${e.type}' on this terminal.`);if(!ee(e.patch))return Hl(`Failed to apply '${Bl}': invalid appearance settings patch`);a.push(e.patch)}for(let e of a)try{await r.writeAppearanceSettings(e)}catch(e){return Hl(`Failed to apply '${Bl}': ${Vl(e)}`)}return{result:{message:i.message,success:i.success,...i.data===void 0?{}:{data:i.data}},uiIntents:i.uiIntents??[]}}function Gl(e){let t=new pe(e.terminalHandoff),{cwd:n}=e;return{canHandoffTerminal:()=>t.canHandoffTerminal(),runWithTerminal:e=>t.runWithTerminal(e),getCwd:()=>n,getCommandInvocationSource:()=>`user`}}function Kl(e,t){return e!==void 0&&e===t?h:e}function ql(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jl(e,t){if(!ql(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&&ql(r)&&r.driverId===t&&(n={...n,metadata:{...r,driverId:h}}),n}function Yl(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:Jl(e.data,r)}})}function Xl(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 Zl(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(Xl)}:{}})),...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 Ql(e,t){let n=t.toLowerCase();return e.find(e=>e.name.toLowerCase()===n&&e.subcommands!==void 0)?.subcommands??[]}function $l(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>e.name.toLowerCase().startsWith(n))}const eu=[`get-context`,`get-commands`,`get-status`,`get-executing`,`get-pending`,`get-execution-workspace`],tu=[...eu,`get-prompts`],nu=[`get-context`,`get-status`,`get-commands`],ru=new Set([`exit`,`quit`]),iu=new Set([`show-plugin-manager`,`show-settings`]);function au(e){return e instanceof Error?e.message:String(e)}var ou=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)}},su=class{options;sessionName;manager;userActions;permissions;attention;lifecycle;uiEvents=new ou;clientCommands;commandQueryPort={getCommands:e=>$l(this.commandCatalog,e),getSubcommands:e=>Ql(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:Gl({terminalHandoff:e.terminalHandoff,cwd:e.cwd})},this.hostHistory=new zl({request:e=>this.send(e===0?{type:`get-history`}:{type:`get-history`,fromIndex:e}),show:(e,t)=>this.manager.syncHostHistory(e,t),revive:e=>Yl(e,this.own)}),this.userActions=new wl(()=>this.notify()),this.permissions=new Tl(()=>this.notify()),this.attention=e.attention?new _l({source:e.attention,onRecap:e=>this.manager.addAttentionRecap(e)}):void 0,this.lifecycle=new Cl({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}=xl(e);if(ru.has(t)){this.end(`user`);return}let r=Ul(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 Wl(e,t,n.host,n.set);for(let e of i)this.uiEvents.emitUiIntent({intent:e,requesterDriverId:h});this.notice(r.message)}catch(t){this.notice(`/${e.name} failed: ${au(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:Fl(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: ${au(t)}`)}}project(e){let t=this.manager;switch(e.type){case`user_message`:{let t=Kl(e.driverId,this.options.driverId)??null;this.hostHistory.echo(El(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=Zl(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:`)?o(e.requesterDriverId):void 0,n=this.promptGeneration;this.permissions.enqueue(e.toolName,e.toolArgs,e.id,e.canPersistProjectPermission,t,e.requester).then(t=>this.answer(n,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(iu.has(e.intent.type)){this.notice(`That screen is not available while attached to a daemon.`);return}let t={...e,requesterDriverId:h};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:Wo(e.sessionId));t!==void 0&&t!==this.sessionName&&this.rename(t)}showCommandResult(e){for(let e of nu)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(Wo(e)),this.requestSnapshot()}requestSnapshot(){this.hostHistory.reload(),this.requestState()}requestState(){for(let e of this.readOnly?eu:tu)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&&!U(e.type))return!1;try{return this.options.connection.send(e),!0}catch(e){return this.notice(`Could not reach the session: ${au(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 Pl;return e.onChange=()=>this.notify(),e}notice(e){this.manager.addEntry(a(t(e)))}notify(){this.onChange?.()}};function cu(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.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 lu(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 uu(e){try{await e.keybindingsSource?.start(),await pu(e,t=>({createChannel:fu(e,t)}))}finally{e.keybindingsSource?.dispose()}}async function du(e){let t=`user`,n=()=>void 0,r=new Promise(e=>{n=e});try{await e.keybindingsSource?.start(),await pu(e,i=>{let a;return{createChannel:()=>a??=new su({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 fu(e,t){let n=e.workspaceMovedFrom;return r=>{let i=n;n=void 0;let a=new Ll({...cu(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 pu(e,t){let n=e.screenReader===!0;e.announce!==!1&&$c({enabled:n,channel:e.screenReaderChannel,hint:e.screenReaderHint});let r=nl({enabled:n,overrides:e.screenReaderPacing}),i=n&&r.preparkMs>0?cl({stdout:process.stdout,preparkMs:r.preparkMs}):void 0;Xe()||(T.level=0);let a=new dl,o=$e({override:e.focusReporting}),s=ul({supported:()=>o}),c=new Yc({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 il(r.startupQuietMs,process.stdin);let f=new Zc(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:ll(i),m=B(Pa,{name:e.productDisplayName,modelCommandToolPrefix:e.modelCommandToolPrefix,children:B(ir,{source:e.keybindingsSource,children:B(Ye,{enabled:n,children:B(Jr,{overrides:e.terminalCapabilities,children:B(Jc,{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=O(p===void 0?m:B(Gr,{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 lu(()=>h.waitUntilExit(),()=>u)}finally{await i?.flush(),a.setTerminalModeHooks(void 0),s.disable(),c.dispose(),f.detach(),process.stdin.pause()}}const mu={drive:`drive (send prompts, answer its questions)`,observe:`observe (read only)`},hu=[`needs-input`,`working`,`idle`,`unknown`,`unverified`,`dead`];function gu(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 _u(e){return e.liveness===`dead`?`dead`:$(e)?e.activity:`unverified`}function vu(e){return[...e].sort((e,t)=>hu.indexOf(_u(e))-hu.indexOf(_u(t))||e.id.localeCompare(t.id))}function yu(e){return[...e].sort((e,t)=>(e.cwd===void 0)-+(t.cwd===void 0)||(e.cwd??``).localeCompare(t.cwd??``)||hu.indexOf(_u(e))-hu.indexOf(_u(t))||e.id.localeCompare(t.id))}function bu(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(Su(c))<=n?c:e.slice(o)}function xu(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 Su(e){return xu(e).join(``)}function Cu(e,t){let n=xu(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 wu(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 Tu(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 Eu({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}=Te(),{stdout:h}=ke(),g=Math.max(12,h.columns??80),_=K(),[ee,te]=R([]),[v,ne]=R(Date.now),[y,re]=R(`loading`),[ie,ae]=R(f),[oe,se]=R(!1),[ce,le]=R(p),[b,ue]=R(),x=b?.id,[de,fe]=R(`idle`),[S,C]=R(`idle`),[pe,me]=R(),he=L(!1),[ge,_e]=R(`idle`),[ve,ye]=R(),[w,be]=R(),T=L(!1),[xe,Se]=R(`idle`),Ce=L(!1),D=L(!0),we=e=>{n!==void 0&&(T.current=!0,_e(`starting`),Promise.resolve().then(()=>n(e)).then(e=>{D.current&&(ye(e),_e(`started`))}).catch(()=>{D.current&&_e(`failed`)}).finally(()=>{T.current=!1}))},O=I(()=>{let e=ee.filter(e=>u===void 0||_u(e)===u);return ce?yu(e):vu(e)},[ee,u,ce]),Ee=I(()=>{let e=[],t=[...new Set(O.map(e=>e.cwd).filter(e=>e!==void 0))],n,r=0;return O.forEach((i,a)=>{let o=ce?i.cwd??`unverified`:_u(i);if(o!==n){let n=ce?i.cwd===void 0?`Directory: unverified`:(()=>{let e=`Dir ${++r}: `,n=Math.max(4,g-e.length),a=Cu(bu(i.cwd,t,n),n),o=`${e}${a} — ${Su(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},[O,ce,g,_]);F(()=>{let t=new AbortController,n=!0,r,i=async()=>{try{let r=vu(await e(t.signal));if(!n||t.signal.aborted)return;let i=Date.now();te(e=>wu(e,r)?e:r),ne(e=>r.some(t=>t.nextLoopAt!==void 0&&Tu(t.nextLoopAt,e)!==Tu(t.nextLoopAt,i))?i:e),re(`ready`)}catch{n&&!t.signal.aborted&&re(`unavailable`)}finally{n&&!t.signal.aborted&&(r=setTimeout(()=>{i()},d))}};return i(),()=>{n=!1,r!==void 0&&clearTimeout(r),t.abort()}},[e,d]),F(()=>(D.current=!0,()=>{D.current=!1}),[]);let k=ie!==void 0&&O.some(e=>e.id===ie)?ie:O[0]?.id;F(()=>{ae(e=>O.length===0||e!==void 0&&O.some(t=>t.id===e)?e:O[0]?.id)},[O]),De((e,i)=>{if(!he.current&&!(Ce.current&&e!==`q`&&!(!_&&i.escape)&&!(i.ctrl&&e===`c`))&&!(T.current&&e!==`q`&&!(!_&&i.escape)&&!(i.ctrl&&e===`c`))){if(w!==void 0){e===`y`||e===`r`?(be(void 0),we(e===`y`?`trust`:`restricted`)):(e===`n`||i.escape)&&be(void 0);return}if(x!==void 0){if(e===`n`||i.escape){ue(void 0);return}if(e===`y`&&b?.action===`attach`){let e=b,t=O.find(t=>t.id===e.id);if(ue(void 0),y!==`ready`||!$(t)||t.generation!==e.generation||e.mode===void 0||o===void 0){fe(`unavailable`);return}o({id:e.id,generation:e.generation,mode:e.mode,groupByDirectory:ce}),m();return}if(e===`y`){let e=b,n=O.find(t=>t.id===e?.id);if(ue(void 0),y!==`ready`||e===void 0||!$(n)||n.generation!==e.generation||t===void 0){C(`unavailable`);return}he.current=!0,C(`stopping`),t(e.id,e.generation).then(()=>{D.current&&(me(e.id),C(`stopped`))}).catch(()=>{D.current&&C(`failed`)}).finally(()=>{he.current=!1})}return}if(e===`q`||!_&&i.escape||i.ctrl&&e===`c`){m();return}if(e===`?`){se(e=>!e);return}if(e===`g`){Oe.clear(),le(e=>!e);return}if(e===`n`&&n!==void 0){if(r===void 0){we();return}T.current=!0,r().then(e=>{T.current=!1,D.current&&(e===void 0?we():be(e))}).catch(()=>{T.current=!1,D.current&&_e(`failed`)});return}if((e===`a`||e===`p`)&&o!==void 0){let t=O.find(e=>e.id===k);y!==`ready`||!$(t)?fe(`unavailable`):(fe(`idle`),C(`idle`),ue({id:t.id,generation:t.generation,action:`attach`,mode:e===`a`?`drive`:`observe`}));return}if(e===`o`&&a!==void 0){let e=O.find(e=>e.id===k);if(y!==`ready`||!$(e)||!e.pr){Se(`unavailable`);return}Ce.current=!0,Se(`opening`),a(e.id,e.pr.url,e.generation).then(()=>{D.current&&Se(`opened`)}).catch(()=>{D.current&&Se(`failed`)}).finally(()=>{Ce.current=!1});return}if(e===`s`&&t!==void 0){let e=O.find(e=>e.id===k);y!==`ready`||!$(e)?C(`unavailable`):(C(`idle`),fe(`idle`),ue({id:e.id,generation:e.generation,action:`stop`}));return}if(!(_||O.length===0)&&(i.upArrow||i.downArrow)){let e=Math.max(0,O.findIndex(e=>e.id===k)),t=Math.max(0,Math.min(O.length-1,e+(i.downArrow?1:-1)));ae(O[t]?.id)}}});let Oe=jn({enabled:_&&x===void 0&&w===void 0&&S!==`stopping`,itemCount:O.length,cancellable:!0,repeatable:!0,onSelect:e=>{ae(O[e]?.id),C(`idle`)},onCancel:()=>{he.current||m()}}),A=O.find(e=>e.id===k),j=y===`ready`&&$(A)?A.name:void 0,M=y===`ready`&&$(A)&&A.activity===`idle`&&A.nextLoopAt?Tu(A.nextLoopAt,v):``,N=y===`ready`&&$(A)?A.pr:void 0,P=Math.max(8,h.rows??24),Ae=[`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`],Me=oe&&x===void 0&&S!==`stopping`,Ne=2+(u===void 0?0:1)+ +(y===`loading`||y===`unavailable`||y===`ready`&&O.length===0)+(k===void 0?0:1)+(j===void 0?0:1)+(N===void 0?0:2)+ +!!M+(xe===`idle`?0:1)+(ge===`idle`?0:1)+(w===void 0?0:1)+(x===void 0?S===`idle`?0:1:_?1:2)+ +(x===void 0&&de!==`idle`)+1+(Me?Ae.length:0)+2,Pe=Math.max(1,P-Ne),Fe=Math.max(0,Ee.findIndex(e=>e.kind===`row`&&e.row.id===k)),Ie=Math.min(Math.max(0,Fe-Math.floor(Pe/2)),Math.max(0,Ee.length-Pe)),H=_?Ee:Ee.slice(Ie,Ie+Pe),Le=w===void 0?[]:gu([`Not trusted: ${w.folder}`,`Trusting it loads the project's own settings, hooks, plugins, skills and MCP servers:`,...w.loads],_?1/0:Pe,i),U=_?{}:{wrap:`truncate-end`},Re=o!==void 0&&y===`ready`&&$(A),ze=S===`stopping`?`Stop in progress; wait for result.`:w===void 0?x===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 ${b?.action===`attach`?`attach`:`stop`} or cancel before closing.`:`Answer the trust question or cancel before closing.`,Be=e=>b?.action===`attach`&&b.mode!==void 0?`${b.mode===`drive`?`Attach to`:`Peek at`} ${e} to ${mu[b.mode]}?`:`Stop ${e}?`;return V(E,{flexDirection:`column`,..._?{}:{height:P},children:[V(G,{...U,children:[s?`Background sessions in selected directory`:`Background sessions across projects`,c?` · name filter active`:``,l?` · PR filter active`:``]}),V(G,{...U,children:[O.length,` supervised session(s). Foreground peers and saved records are separate.`]}),u!==void 0&&V(G,{...U,children:[`State: `,u]}),y===`loading`&&B(G,{...U,children:`Loading supervised sessions...`}),y===`unavailable`&&B(G,{...U,children:`Supervised session discovery unavailable; last verified rows remain below.`}),y===`ready`&&O.length===0&&B(G,{...U,children:`No supervised sessions.`}),Le.map((e,t)=>B(G,{...U,children:e},`trust-${t}`)),w===void 0&&Ie>0&&!_&&V(G,{children:[Ie,` more above`]}),(w===void 0?H:[]).map(e=>e.kind===`group`?B(G,{...U,children:e.label},`group-${e.label}`):V(G,{..._?{}:{wrap:`truncate-end`},children:[_?sr(e.index):e.row.id===k?`> `:` `,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,y===`ready`&&$(e.row)&&e.row.activity===`idle`&&e.row.nextLoopAt?` ${Tu(e.row.nextLoopAt,v)}`:``,e.row.problem?` ${e.row.problem}`:``,y===`ready`&&$(e.row)&&e.row.pr?` ${e.row.pr.host} ${e.row.pr.kind===`pull`?`#`:`!`}${e.row.pr.number}`:``]},`row-${e.row.id}`)),w===void 0&&!_&&Ie+H.length<Ee.length&&V(G,{children:[Ee.length-Ie-H.length,` more below`]}),k!==void 0&&V(G,{...U,children:[`Selected `,k]}),j!==void 0&&V(G,{...U,children:[`Name: `,j]}),N!==void 0&&V(G,{...U,children:[`PR: `,N.host,` `,N.kind===`pull`?`#`:`!`,N.number]}),N!==void 0&&V(G,{...U,children:[`URL: `,N.url]}),M&&B(G,{...U,children:M}),xe===`opening`&&B(G,{...U,children:`Opening linked PR...`}),xe===`opened`&&B(G,{...U,children:`Opened linked PR.`}),xe===`failed`&&B(G,{...U,children:`PR link changed or could not be opened.`}),xe===`unavailable`&&B(G,{...U,children:`No verified PR link is available.`}),ge===`starting`&&B(G,{...U,children:`Starting a background session...`}),ge===`started`&&V(G,{...U,children:[`Started `,ve,c||u!==void 0?` (may be hidden by filter)`:``]}),ge===`failed`&&B(G,{...U,children:`Start failed; check workspace trust or run session start --background for details.`}),w!==void 0&&B(G,{...U,children:`y Trust and start / r Start Restricted / n Cancel`}),x!==void 0&&(_?V(G,{children:[Be(x),` y Yes / n No`]}):V(z,{children:[B(G,{...U,children:Be(`…${x.slice(-8)}`)}),B(G,{...U,children:`y Yes / n No`})]})),x===void 0&&S===`unavailable`&&B(G,{...U,children:`This session cannot be stopped from the view.`}),x===void 0&&de===`unavailable`&&B(G,{...U,children:`This session cannot be attached to from the view.`}),S===`stopping`&&B(G,{...U,children:`Stopping selected session; wait for confirmation.`}),S===`stopped`&&V(G,{...U,children:[`Stopped `,pe]}),S===`failed`&&B(G,{...U,children:`Stop failed; session remains listed until verified otherwise.`}),_&&O.length>0&&x===void 0&&S!==`stopping`&&V(G,{children:[or(O.length,!0),Oe.buffer?` ${Oe.buffer}`:``]}),_&&Oe.invalid&&B(G,{children:`Selection out of range.`}),B(G,{...U,children:ze}),Me&&Ae.map(e=>B(G,{...U,children:e},e))]})}async function Du(e){e.announce!==!1&&$c({enabled:e.screenReader,channel:e.screenReaderChannel,hint:e.screenReaderHint});let t;process.stdin.resume();let n=O(B(Ye,{enabled:e.screenReader,children:B(Eu,{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 Ou({providerDefinitions:t,reloadPluginCommandSource:n,userSettingsPath:r,settingsSources:i,formatResumeCommand:a}){return{getUserSettingsPath:()=>r,readSettings:e=>ae(e),reloadPluginCommandSource:e=>{n(e)},applyActiveModelChange:(e,t,n)=>(m(i,[l(`user`,r)],t,n),{applied:!0}),getGitBranch:e=>re(e),getProviderDisplayName:n=>e(t,n)?.displayName??n,...a===void 0?{}:{formatResumeCommand:a}}}function ku(e){return{...e===void 0?{}:{$schema:e},version:1,bindings:{}}}function Au(e,t){let n=Xn(JSON.stringify(ku(t)),e);if(!n.ok)throw Error(n.diagnostic.message);return n.snapshot}var ju=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=Au(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=ge(this.filePath);if(await ve(e,{recursive:!0}),await this.#u(),this.#s)throw Error(`Keybindings source is disposed.`);this.#i=me(e,{persistent:!1},(e,t)=>{(t===null||t.toString()===he(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 ve(ge(this.filePath),{recursive:!0});try{await w(this.filePath,`${JSON.stringify(ku(this.#e),null,2)}\n`,{encoding:`utf8`,flag:`wx`,mode:384})}catch(e){if(!Nu(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 ye(this.filePath,`utf8`)}catch(e){if(Mu(e))return;this.#d({file:this.filePath,path:`$`,message:Fu(e)});return}let t=Xn(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 Mu(e){return Pu(e)&&e.code===`ENOENT`}function Nu(e){return Pu(e)&&e.code===`EEXIST`}function Pu(e){return e instanceof Error&&`code`in e}function Fu(e){return e instanceof Error?e.message:String(e)}function Iu(e){return new ju(e)}function Lu(e){if(e===`1`)return!0;if(e===`0`)return!1}function Ru(e){if(e.flag!==void 0)return{reducedMotion:e.flag,override:`flag`};let t=Lu(e.env);return t===void 0?{reducedMotion:e.settings}:{reducedMotion:t,override:`environment`}}function zu(e,t,n){let r=v(e??{}),i=Ru({settings:r.reducedMotion,flag:t,env:n.PRODUCT_REDUCED_MOTION});return{appearance:r,reducedMotion:i.reducedMotion,...i.override===void 0?{}:{reducedMotionOverride:i.override}}}const Bu=RegExp(`^[A-Za-z0-9._-]{1,24}$`,`u`);function Vu(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(_e(t,r.name),n)}))}function Hu(e,t){let n=`load ${t.source} themes`,r=ie(t.root);for(let i of Vu(r,t.directory,n)){let n=i.fileName.slice(0,-5);if(!Bu.test(n)){let n=kt(i.fileName);e.skipped.push({id:`${t.idPrefix}${n}`,fileName:At(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=Ut({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 Uu(e,t,n,r){let i=ne(e,t,r);try{return oe(i,{settingsPath:y(t)}).map(e=>({name:e.manifest.name,pluginDir:e.pluginDir}))}catch(e){let t=jt(i.join(`, `)),r=jt(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 Wu(e){let t={themes:[],skipped:[],claimed:new Set};Hu(t,{root:e.productRuntime.layout.userRoot,directory:`themes`,source:`user`,idPrefix:`custom:`});let n=e.plugins??Uu(e.cwd,e.productRuntime,t,e.projectAccess);for(let e of n){if(!Bu.test(e.name)){let n=kt(e.name);t.skipped.push({id:`custom:${n}`,fileName:At(e.name),reason:`$: the plugin name ${n} cannot be part of a theme id — its themes are not loaded`});continue}Hu(t,{root:e.pluginDir,directory:`themes`,source:`plugin`,idPrefix:`custom:${e.name}:`})}return{themes:t.themes,skipped:t.skipped}}function Gu(e){let t=zu(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=Wu({cwd:e.cwd,productRuntime:e.productRuntime,userHome:e.userHome,...e.projectAccess===void 0?{}:{projectAccess:e.projectAccess}}),i=jc([...Ke(),...r.themes],r.skipped);return{registry:i,cataloguePort:Pc({registry:i,readAppearance:()=>zu(ae(y(e.productRuntime)),void 0,{}).appearance,...t.reducedMotionOverride===void 0?{}:{reducedMotionPin:{tier:t.reducedMotionOverride,reducedMotion:t.reducedMotion}}}),skipped:r.skipped,...n}}let Ku=null,qu=!1;function Ju(){return qu}const Yu=[`string-width`,`setCursorPosition`,`getStringWidth`,`slice`,`charCodeAt`];function Xu(e,t){if(!t)return`rethrow`;let n=e.message??``;return Yu.some(e=>n.includes(e))?`ime-hint`:`guard-owned`}function Zu(e){Ku=e}function Qu(e,t){try{if(Ku){Ku.getSession().reportBackgroundError(e,t);return}}catch{}process.stderr.write(`\n[robota] ${t}: ${e.message}\n`)}function $u(){qu||(qu=!0,process.on(`unhandledRejection`,e=>{Qu(e instanceof Error?e:Error(String(e)),`unhandled rejection`)}),process.on(`uncaughtException`,e=>{Qu(e instanceof Error?e:Error(String(e)),`uncaught exception`)}))}async function ed(e={}){let t=de(e),n={...e,productRuntime:t};return b(ue(process.argv))?(se(t.environment),ce(le(t)),new Promise(()=>void 0)):x(n,f,{renderApp:uu,renderSupervisedSessionView:Du,renderAttachedApp:du,createDefaultTuiCliAdapter:Ou,createNodeKeybindingsSource:Iu,createThemeSurface:Gu,installTuiProcessGuards:$u,setLiveChannel:Zu})}if(p(),process.on(`uncaughtException`,e=>{let t=Xu(e,Ju());if(t===`ime-hint`){process.stderr.write(`
35
35
  [robota] CJK/IME input error — this is a known issue with macOS Terminal.app.
36
36
  Workaround: use iTerm2 (https://iterm2.com) or input your prompt in English.
37
- Alternatively, use headless mode: robota -p "your prompt here"
37
+ Alternatively, use headless mode: -p "your prompt here"
38
38
 
39
- `);return}if(t!==`guard-owned`)throw e}),te(x(process.argv))?v(oe()):$u().catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(t+`
39
+ `);return}if(t!==`guard-owned`)throw e}),b(ue(process.argv)))try{let e=de({});se(e.environment),ce(le(e))}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}else ed().catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(t+`
40
40
  `),process.exit(1)});export{};