@robota-sdk/agent-ui-terminal 3.0.0-beta.82 → 3.0.0-beta.83

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 (67) hide show
  1. package/CHANGELOG.md +858 -0
  2. package/README.md +5 -1
  3. package/dist/node/index.d.ts +189 -54
  4. package/dist/node/index.d.ts.map +1 -1
  5. package/dist/node/index.js +21 -21
  6. package/dist/node/index.js.map +1 -1
  7. package/package.json +16 -21
  8. package/src/App.tsx +14 -3
  9. package/src/AppPresentation.tsx +1 -1
  10. package/src/PermissionPrompt.tsx +50 -17
  11. package/src/SessionPicker.tsx +27 -7
  12. package/src/SessionStatusBar.tsx +6 -2
  13. package/src/StatusBar.tsx +24 -0
  14. package/src/SupervisedSessionView.tsx +479 -157
  15. package/src/TuiInteractionChannel.ts +8 -53
  16. package/src/__tests__/SupervisedSessionView-render.test.tsx +28 -0
  17. package/src/__tests__/SupervisedSessionView.test.tsx +453 -82
  18. package/src/__tests__/TuiInteractionChannel.display-contract.test.ts +32 -22
  19. package/src/__tests__/TuiInteractionChannel.lifecycle.test.ts +10 -2
  20. package/src/__tests__/attached-app-session-switch.test.tsx +317 -0
  21. package/src/__tests__/checkpoint-store-per-channel.test.ts +81 -0
  22. package/src/__tests__/command-handoff-pty-e2e.test.ts +2 -2
  23. package/src/__tests__/default-tui-cli-adapter-host-settings.test.ts +3 -1
  24. package/src/__tests__/fixtures/command-handoff-driver.tsx +8 -5
  25. package/src/__tests__/grant-history-reaches-the-session.test.ts +31 -0
  26. package/src/__tests__/numbered-selection-chunk.test.tsx +41 -0
  27. package/src/__tests__/palette-consistency.test.ts +0 -1
  28. package/src/__tests__/permission-prompt-arming.test.tsx +153 -0
  29. package/src/__tests__/pty/screen-005-prompt-footers.ptytest.ts +2 -1
  30. package/src/__tests__/pty/screen-006-no-color.ptytest.ts +2 -0
  31. package/src/__tests__/pty/session-attach.ptytest.ts +144 -0
  32. package/src/__tests__/render-channel-options.test.ts +6 -6
  33. package/src/__tests__/sandbox-reaches-the-session.test.ts +37 -0
  34. package/src/__tests__/screen-reader-menus.test.tsx +1 -1
  35. package/src/__tests__/session-picker.test.tsx +93 -0
  36. package/src/__tests__/status-bar.test.tsx +8 -0
  37. package/src/__tests__/tui-channel-init-failure.test.ts +10 -2
  38. package/src/__tests__/wire-tui-channel.test.ts +1445 -0
  39. package/src/__tests__/wire-tui-client-commands.test.ts +243 -0
  40. package/src/app-view-model.ts +6 -2
  41. package/src/attached-session-connection.ts +14 -0
  42. package/src/hooks/__tests__/use-app-detach-key.test.tsx +72 -0
  43. package/src/hooks/__tests__/use-app-loop-escape.test.tsx +13 -0
  44. package/src/hooks/useAppController.ts +6 -2
  45. package/src/hooks/useAppInputBindings.ts +20 -2
  46. package/src/hooks/useAppInteractionState.ts +3 -0
  47. package/src/hooks/useAppOverlays.ts +20 -4
  48. package/src/hooks/useNumberedSelection.ts +19 -2
  49. package/src/hooks/useTuiChannel.ts +13 -1
  50. package/src/index.ts +17 -3
  51. package/src/render.tsx +218 -27
  52. package/src/short-session-id.ts +9 -0
  53. package/src/slash-command-input.ts +11 -0
  54. package/src/tui-app-channel-port.ts +29 -1
  55. package/src/tui-channel-options.ts +11 -2
  56. package/src/tui-session-event-projector.ts +0 -2
  57. package/src/tui-session-events.ts +6 -0
  58. package/src/tui-session-options.ts +9 -0
  59. package/src/tui-state-manager.ts +17 -3
  60. package/src/waiting-loop-stop-notice.ts +23 -0
  61. package/src/wire-history-sync.ts +159 -0
  62. package/src/wire-tui-channel.ts +962 -0
  63. package/src/wire-tui-client-commands.ts +142 -0
  64. package/src/wire-tui-projection.ts +136 -0
  65. package/dist/node/index.cjs +0 -32
  66. package/dist/node/index.d.cts +0 -1066
  67. package/dist/node/index.d.cts.map +0 -1
@@ -1,33 +1,33 @@
1
- import e,{Chalk as t,backgroundColorNames as n,foregroundColorNames as r}from"chalk";import{Box as i,Static as a,Text as o,render as s,useApp as c,useBoxMetrics as l,useCursor as u,useInput as d,usePaste as f,useStdout as p,useWindowSize as m}from"ink";import h,{createContext as g,useCallback as _,useContext as v,useEffect as y,useLayoutEffect as b,useMemo as x,useRef as S,useState as C}from"react";import{Fragment as w,jsx as T,jsxs as E}from"react/jsx-runtime";import D from"string-width";import{CommandRegistry as ee,DEFAULT_STATUS_LINE_COMMAND_SETTINGS as O,MODEL_COMMAND_TOOL_PREFIX as te,applyActiveModelChange as k,buildRuntimeSession as ne,consentScopeFor as re,createNodeHostSettingsStore as ie,generateSessionName as ae,isSlashCommand as oe,listResumableSessionSummaries as A,readAppearanceSettings as se,readSettings as j,resolveExecutionAttach as ce,resolveGitBranchFromNodeHost as le,tokeniseSlashCommand as ue}from"@robota-sdk/agent-framework";import{createSystemMessage as M,createUserMessage as de,findProviderDefinition as N,formatTokenCount as P,isAssistantMessage as fe,isToolMessage as pe,messageToHistoryEntry as F,printablePeerDriver as me}from"@robota-sdk/agent-core";import{marked as he}from"marked";import I from"marked-terminal";import{OWNER_DRIVER_ID as L}from"@robota-sdk/agent-interface-session";import{Readable as R}from"node:stream";import{watch as ge}from"node:fs";import{mkdir as z,readFile as _e,writeFile as ve}from"node:fs/promises";import{basename as B,dirname as ye}from"node:path";const be=new Set([` `,`
2
- `]),xe=/\r\n/g,Se=/\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 V(e){return e.replace(xe,`
3
- `).replace(Se,e=>be.has(e)?e:``)}function Ce(e){return typeof e==`string`?V(e):typeof e==`number`||typeof e==`boolean`||e==null?e:Array.isArray(e)?e.map(e=>Ce(e)):e}function H(e){let{children:t,...n}=e;return T(o,{...n,children:Ce(t)})}function U(e){return T(o,{...e})}const we={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`]}},W=[we,{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`]}}],Te=we.id;function Ee(){return W}function De(e){return e??we}const Oe=g(!1);function ke({enabled:e,children:t}){return T(Oe.Provider,{value:e,children:t})}function G(){return v(Oe)}function Ae(){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 je(e={}){return e.override===!0?!0:e.override===!1||process.env.TERM_PROGRAM===`Apple_Terminal`?!1:!!process.stdout.isTTY}function Me(e={}){return e.override===!0?!0:e.override===!1||process.env.TERM_PROGRAM===`WezTerm`?!1:!!process.stdout.isTTY}function Ne(e={}){return e.override===!0||e.override!==!1&&!!process.stdin.isTTY&&!!process.stdout.isTTY}const Pe=g(we),Fe=g(!1),Ie=g(!0);function Le({theme:e,reducedMotion:t=!1,syntaxHighlighting:n=!0,children:r}){return T(Pe.Provider,{value:De(e),children:T(Fe.Provider,{value:t,children:T(Ie.Provider,{value:n,children:r})})})}function Re(){return v(Pe)}function K(){return Re().colors}function ze(){return Re().motion}function Be(){let e=G(),t=v(Fe);return Ae()&&!e&&!t}function Ve(){return v(Ie)}const He=[`keyword`,`built_in`,`type`,`literal`,`number`,`regexp`,`string`,`class`,`function`,`comment`,`doctag`,`meta`,`tag`,`name`,`attr`,`addition`,`deletion`],Ue=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/iu,We=/^ansi256\((\d{1,3})\)$/iu,Ge=/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/iu,Ke=`<chalk name> | #rgb | #rrggbb | ansi256(n) | rgb(r,g,b)`,qe=new Map([...r,...n].map(t=>[t,e[t]])),Je=new Set(r);function Ye(e){return Je.has(e)}function Xe(e){if(Ue.test(e))return!0;let t=We.exec(e);if(t)return Number(t[1])<=255;let n=Ge.exec(e);return n?n.slice(1).every(e=>Number(e)<=255):Ye(e)}function Ze(e){throw Error(`Theme colour ${JSON.stringify(e)} is not in Ink's colour grammar (${Ke}).`)}function q(t,n=e){if(Ue.test(t))return n.hex(t);let r=We.exec(t);if(r)return n.ansi256(Number(r[1]));let i=Ge.exec(t);if(i)return n.rgb(Number(i[1]),Number(i[2]),Number(i[3]));let a=Ye(t)?qe.get(t):void 0;return a===void 0&&Ze(t),Reflect.get(n,t)??a}function Qe(t,n=e){if(Ue.test(t))return n.bgHex(t);let r=We.exec(t);if(r)return n.bgAnsi256(Number(r[1]));let i=Ge.exec(t);if(i)return n.bgRgb(Number(i[1]),Number(i[2]),Number(i[3]));let a=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;return Reflect.get(n,a)??Ze(t)}const $e=new t({level:3});function et(){return e.level===0?$e:e}function tt(t){return{heading:q(t.heading).bold,firstHeading:q(t.firstHeading).underline.bold,code:q(t.code),codespan:q(t.codespan),link:q(t.link),href:q(t.href).underline,blockquote:q(t.blockquote).italic,del:q(t.del,e.dim).strikethrough,html:q(t.html)}}function nt(e){let t={};for(let n of He)t[n]=n===`type`?q(e[n]).dim:q(e[n]);return t}function rt(e){let{markdown:t}=e,n=et(),r=Qe(t.diffAddedBackground,n),i=q(t.diffAdded,n),a=Qe(t.diffRemovedBackground,n),o=q(t.diffRemoved,n);return{added:e=>r(i(e)),removed:e=>a(o(e)),hunk:q(t.diffHunk,n),meta:e=>n.dim(e)}}function J(e){return e.split(/\s+/u).map(Number)}J(`0 95 135 175 215 255`),J(`0.1121 0.8853 -0.0005`),J(`0.1127 0.8897 -0.0001`),J(`0.0045 0.0 1.0019`),J(`0.292 0.7054 -0.0003`),J(`0.2934 0.7089 0.0`),J(`-0.0209 0.4614 0.5677`),J(`0.4124 0.3576 0.1805`),J(`0.2126 0.7152 0.0722`),J(`0.0193 0.1192 0.9505`),J(`0.95047 1 1.08883`);function it(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const at=new Set([`name`,`base`,`overrides`]),ot=/[\u0000-\u001F\u007F-\u009F]/u,st=new RegExp(ot.source,`gu`);function ct(e){return JSON.stringify(e).replace(st,e=>`\\u${(e.codePointAt(0)??0).toString(16).padStart(4,`0`)}`)}function lt(e){return ct(e).slice(1,-1)}function ut(e){return V(e).replaceAll(`
4
- `,` `).replaceAll(` `,` `).trim()}function dt(e){return ot.test(e)?ct(e):e}function ft(e){return{ok:!1,error:e}}function pt(e,t){return typeof e==`string`?Xe(e)?{ok:!0,value:e}:{ok:!1,error:`${t}: ${ct(e)} is not a colour in Ink's grammar (${Ke})`}:{ok:!1,error:`${t}: expected a colour string`}}function mt(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=gt(a,t[i]??null,`${n}[${i}]`);if(!e.ok)return e;r.push(e.value)}return{ok:!0,value:r}}function ht(e,t,n){if(!it(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}.${dt(i)} is not a theme token`};let a=gt(e[i]??null,t[i]??null,`${n}.${dt(i)}`);if(!a.ok)return a;r[i]=a.value}return{ok:!0,value:r}}function gt(e,t,n){return typeof e==`string`?pt(t,n):Array.isArray(e)?mt(e,t,n):it(e)?ht(e,t,n):{ok:!1,error:`${n} is not a theme token`}}function _t(e){return JSON.parse(JSON.stringify(e))}function vt(e){return JSON.parse(JSON.stringify({colors:e.colors,markdown:e.markdown,syntax:e.syntax,motion:e.motion}))}function yt(e){let t;try{t=JSON.parse(e)}catch(e){return{ok:!1,error:`$: ${e instanceof Error?ut(e.message):`invalid JSON`}`}}if(!it(t))return{ok:!1,error:`$: expected an object`};for(let e of Object.keys(t))if(!at.has(e))return{ok:!1,error:`$.${dt(e)} is not a theme token`};return{ok:!0,value:t}}function bt(e,t){let n=e.name;return n===void 0?ot.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`}:ot.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 xt(e){let t=e.base===void 0?Te:e.base;if(typeof t!=`string`)return{ok:!1,error:`$.base: expected a built-in theme id`};let n=W.find(e=>e.id===t);return n?{ok:!0,theme:n}:{ok:!1,error:`$.base: ${ct(t)} is not a built-in theme`}}function St(e){let t=yt(e.text);if(!t.ok)return ft(t.error);let n=t.value,r=xt(n);if(!r.ok)return ft(r.error);let i=bt(n,e.id);if(!i.ok)return ft(i.error);let a=n.overrides===void 0?{}:n.overrides,o=gt(vt(r.theme),a,`$.overrides`);if(!o.ok)return ft(o.error);let{colors:s,markdown:c,syntax:l,motion:u}=_t(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 Ct({version:e}){return E(i,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[T(H,{color:K().text.accent,bold:!0,children:`
1
+ import e,{Chalk as t,backgroundColorNames as n,foregroundColorNames as r}from"chalk";import{Box as i,Static as a,Text as o,render as s,useApp as c,useBoxMetrics as l,useCursor as u,useInput as d,usePaste as f,useStdout as p,useWindowSize as m}from"ink";import h,{createContext as g,useCallback as _,useContext as v,useEffect as y,useLayoutEffect as b,useMemo as x,useRef as S,useState as C}from"react";import{Fragment as w,jsx as T,jsxs as E}from"react/jsx-runtime";import D from"string-width";import{CommandRegistry as ee,DEFAULT_STATUS_LINE_COMMAND_SETTINGS as te,MODEL_COMMAND_TOOL_PREFIX as ne,SessionTerminalHandoffGate as re,applyActiveModelChange as O,buildRuntimeSession as ie,consentScopeFor as ae,createNodeHostSettingsStore as oe,isAppearanceSettingsPatch as se,isSlashCommand as ce,listResumableSessionSummaries as le,readAppearanceSettings as ue,readSettings as k,resolveExecutionAttach as de,resolveGitBranchFromNodeHost as A,tokeniseSlashCommand as fe}from"@robota-sdk/agent-framework";import{createSystemMessage as j,createUserMessage as M,findProviderDefinition as N,formatTokenCount as P,isAssistantMessage as pe,isToolMessage as me,messageToHistoryEntry as F,printablePeerDriver as he}from"@robota-sdk/agent-core";import{marked as ge}from"marked";import _e from"marked-terminal";import{OWNER_DRIVER_ID as I}from"@robota-sdk/agent-interface-session";import{Readable as ve}from"node:stream";import{isObserverMessageType as ye}from"@robota-sdk/agent-transport/client";import{watch as be}from"node:fs";import{mkdir as L,readFile as R,writeFile as xe}from"node:fs/promises";import{basename as z,dirname as Se}from"node:path";const B=new Set([` `,`
2
+ `]),Ce=/\r\n/g,we=/\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 V(e){return e.replace(Ce,`
3
+ `).replace(we,e=>B.has(e)?e:``)}function Te(e){return typeof e==`string`?V(e):typeof e==`number`||typeof e==`boolean`||e==null?e:Array.isArray(e)?e.map(e=>Te(e)):e}function H(e){let{children:t,...n}=e;return T(o,{...n,children:Te(t)})}function Ee(e){return T(o,{...e})}const De={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`]}},Oe=[De,{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`]}}],ke=De.id;function Ae(){return Oe}function je(e){return e??De}const Me=g(!1);function U({enabled:e,children:t}){return T(Me.Provider,{value:e,children:t})}function W(){return v(Me)}function Ne(){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 Pe(e={}){return e.override===!0?!0:e.override===!1||process.env.TERM_PROGRAM===`Apple_Terminal`?!1:!!process.stdout.isTTY}function Fe(e={}){return e.override===!0?!0:e.override===!1||process.env.TERM_PROGRAM===`WezTerm`?!1:!!process.stdout.isTTY}function Ie(e={}){return e.override===!0||e.override!==!1&&!!process.stdin.isTTY&&!!process.stdout.isTTY}const Le=g(De),Re=g(!1),ze=g(!0);function Be({theme:e,reducedMotion:t=!1,syntaxHighlighting:n=!0,children:r}){return T(Le.Provider,{value:je(e),children:T(Re.Provider,{value:t,children:T(ze.Provider,{value:n,children:r})})})}function Ve(){return v(Le)}function G(){return Ve().colors}function He(){return Ve().motion}function Ue(){let e=W(),t=v(Re);return Ne()&&!e&&!t}function We(){return v(ze)}const Ge=[`keyword`,`built_in`,`type`,`literal`,`number`,`regexp`,`string`,`class`,`function`,`comment`,`doctag`,`meta`,`tag`,`name`,`attr`,`addition`,`deletion`],Ke=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/iu,qe=/^ansi256\((\d{1,3})\)$/iu,Je=/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/iu,Ye=`<chalk name> | #rgb | #rrggbb | ansi256(n) | rgb(r,g,b)`,Xe=new Map([...r,...n].map(t=>[t,e[t]])),Ze=new Set(r);function Qe(e){return Ze.has(e)}function $e(e){if(Ke.test(e))return!0;let t=qe.exec(e);if(t)return Number(t[1])<=255;let n=Je.exec(e);return n?n.slice(1).every(e=>Number(e)<=255):Qe(e)}function et(e){throw Error(`Theme colour ${JSON.stringify(e)} is not in Ink's colour grammar (${Ye}).`)}function K(t,n=e){if(Ke.test(t))return n.hex(t);let r=qe.exec(t);if(r)return n.ansi256(Number(r[1]));let i=Je.exec(t);if(i)return n.rgb(Number(i[1]),Number(i[2]),Number(i[3]));let a=Qe(t)?Xe.get(t):void 0;return a===void 0&&et(t),Reflect.get(n,t)??a}function tt(t,n=e){if(Ke.test(t))return n.bgHex(t);let r=qe.exec(t);if(r)return n.bgAnsi256(Number(r[1]));let i=Je.exec(t);if(i)return n.bgRgb(Number(i[1]),Number(i[2]),Number(i[3]));let a=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;return Reflect.get(n,a)??et(t)}const nt=new t({level:3});function rt(){return e.level===0?nt:e}function it(t){return{heading:K(t.heading).bold,firstHeading:K(t.firstHeading).underline.bold,code:K(t.code),codespan:K(t.codespan),link:K(t.link),href:K(t.href).underline,blockquote:K(t.blockquote).italic,del:K(t.del,e.dim).strikethrough,html:K(t.html)}}function at(e){let t={};for(let n of Ge)t[n]=n===`type`?K(e[n]).dim:K(e[n]);return t}function ot(e){let{markdown:t}=e,n=rt(),r=tt(t.diffAddedBackground,n),i=K(t.diffAdded,n),a=tt(t.diffRemovedBackground,n),o=K(t.diffRemoved,n);return{added:e=>r(i(e)),removed:e=>a(o(e)),hunk:K(t.diffHunk,n),meta:e=>n.dim(e)}}function q(e){return e.split(/\s+/u).map(Number)}q(`0 95 135 175 215 255`),q(`0.1121 0.8853 -0.0005`),q(`0.1127 0.8897 -0.0001`),q(`0.0045 0.0 1.0019`),q(`0.292 0.7054 -0.0003`),q(`0.2934 0.7089 0.0`),q(`-0.0209 0.4614 0.5677`),q(`0.4124 0.3576 0.1805`),q(`0.2126 0.7152 0.0722`),q(`0.0193 0.1192 0.9505`),q(`0.95047 1 1.08883`);function st(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const ct=new Set([`name`,`base`,`overrides`]),lt=/[\u0000-\u001F\u007F-\u009F]/u,ut=new RegExp(lt.source,`gu`);function dt(e){return JSON.stringify(e).replace(ut,e=>`\\u${(e.codePointAt(0)??0).toString(16).padStart(4,`0`)}`)}function ft(e){return dt(e).slice(1,-1)}function pt(e){return V(e).replaceAll(`
4
+ `,` `).replaceAll(` `,` `).trim()}function mt(e){return lt.test(e)?dt(e):e}function ht(e){return{ok:!1,error:e}}function gt(e,t){return typeof e==`string`?$e(e)?{ok:!0,value:e}:{ok:!1,error:`${t}: ${dt(e)} is not a colour in Ink's grammar (${Ye})`}:{ok:!1,error:`${t}: expected a colour string`}}function _t(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=yt(a,t[i]??null,`${n}[${i}]`);if(!e.ok)return e;r.push(e.value)}return{ok:!0,value:r}}function vt(e,t,n){if(!st(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=yt(e[i]??null,t[i]??null,`${n}.${mt(i)}`);if(!a.ok)return a;r[i]=a.value}return{ok:!0,value:r}}function yt(e,t,n){return typeof e==`string`?gt(t,n):Array.isArray(e)?_t(e,t,n):st(e)?vt(e,t,n):{ok:!1,error:`${n} is not a theme token`}}function bt(e){return JSON.parse(JSON.stringify(e))}function xt(e){return JSON.parse(JSON.stringify({colors:e.colors,markdown:e.markdown,syntax:e.syntax,motion:e.motion}))}function St(e){let t;try{t=JSON.parse(e)}catch(e){return{ok:!1,error:`$: ${e instanceof Error?pt(e.message):`invalid JSON`}`}}if(!st(t))return{ok:!1,error:`$: expected an object`};for(let e of Object.keys(t))if(!ct.has(e))return{ok:!1,error:`$.${mt(e)} is not a theme token`};return{ok:!0,value:t}}function Ct(e,t){let n=e.name;return n===void 0?lt.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`}:lt.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 wt(e){let t=e.base===void 0?ke:e.base;if(typeof t!=`string`)return{ok:!1,error:`$.base: expected a built-in theme id`};let n=Oe.find(e=>e.id===t);return n?{ok:!0,theme:n}:{ok:!1,error:`$.base: ${dt(t)} is not a built-in theme`}}function Tt(e){let t=St(e.text);if(!t.ok)return ht(t.error);let n=t.value,r=wt(n);if(!r.ok)return ht(r.error);let i=Ct(n,e.id);if(!i.ok)return ht(i.error);let a=n.overrides===void 0?{}:n.overrides,o=yt(xt(r.theme),a,`$.overrides`);if(!o.ok)return ht(o.error);let{colors:s,markdown:c,syntax:l,motion:u}=bt(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 Et({version:e}){return E(i,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[T(H,{color:G().text.accent,bold:!0,children:`
5
5
  ____ ___ ____ ___ _____ _
6
6
  | _ \\ / _ \\| __ ) / _ \\_ _|/ \\
7
7
  | |_) | | | | _ \\| | | || | / _ \\
8
8
  | _ <| |_| | |_) | |_| || |/ ___ \\
9
9
  |_| \\_\\\\___/|____/ \\___/ |_/_/ \\_\\
10
- `}),E(H,{dimColor:!0,children:[` v`,e]})]})}const wt=1e3;function Tt(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/wt),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 Et={running:`⟳`,success:`✓`,error:`✗`,denied:`⊘`,waiting:`◴`,cancelled:`⊗`,idle:`·`};function Dt(e,t){return e.status[t]}function Ot(e){return e.isRunning?`running`:e.result===`error`?`error`:e.result===`denied`?`denied`:`success`}const kt=[`active`,`queued`,`running`,`sleeping`];function At(e,t){return t===`failed`||e===`failed`?`error`:t===`permission`||e===`waiting_permission`?`waiting`:e===`completed`?`success`:e===`cancelled`?`cancelled`:kt.includes(e)?`running`:`idle`}const jt=[`active`,`queued`,`running`,`waiting_permission`,`sleeping`],Mt=/\s+/g;function Nt(e){return(e?.entries??[]).filter(e=>e.kind===`background_task`&&e.visibility==="default")}function Pt(e){return Nt(e).filter(e=>jt.includes(e.status)).length}function Ft(e,t={}){let n=e.id===t.selectedEntryId,r={id:e.id,radio:n?`●`:`○`,state:e.state,title:Lt(e),subtitle:Rt(e),statusLabel:zt(e.status),preview:Vt(e.preview??e.currentAction),statusKind:Bt(e),isSelected:n};return{...r,accessibleText:Ht(r)}}function It(e){let t=e.text.trim().replace(Mt,` `);return t?t.length>160?`${t.slice(0,160)}...`:t:e.kind}function Lt(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 Rt(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 zt(e){return e.replace(/_/g,` `)}function Bt(e){return At(e.status,e.attention)}function Vt(e){return e?.trim().replace(Mt,` `)||void 0}function Ht(e){return[`${e.radio} ${e.state}`,e.title,e.statusLabel,e.subtitle,e.preview].filter(e=>typeof e==`string`&&e.length>0).join(` · `)}const Ut={branch:`├`,last:`└`,plain:`-`};function Wt(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 Gt(e){return e.screenReader===!0?Ut.plain:e.isLast===!1?Ut.branch:Ut.last}function Kt(e,t={}){let n=Ft(e),r=Et[At(e.status,e.attention)],i=[n.statusLabel,n.subtitle].filter(e=>typeof e==`string`&&e.length>0),a=Gt(t),o=Wt(e,n.preview,n.subtitle),s=e.nextFireAt===void 0?void 0:Tt(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 qt(e,t){let n=e&&!t,[r,i]=C(()=>new Date);return y(()=>{if(!n)return;i(new Date);let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[n]),n?r:new Date}function Jt({entries:e,focusedIndex:t=null}){let n=K(),r=G(),a=qt(e.some(e=>e.nextFireAt!==void 0),r);if(e.length===0)return null;let o=t===null?` · ↓ select · Ctrl+B all`:` · ↑↓ select · Enter open · Esc back`;return E(i,{flexDirection:`column`,marginBottom:1,children:[E(i,{children:[T(H,{color:n.text.accent,bold:!0,children:`Background work`}),T(H,{dimColor:!0,children:o})]}),e.map((i,o)=>{let s=Kt(i,{isLast:o===e.length-1,screenReader:r,now:a});return E(H,{wrap:`truncate-end`,inverse:o===t,children:[`${s.connector} `,T(H,{color:Dt(n,s.statusKind),children:`${s.marker} ${s.state}`}),` ${s.label}`,s.segments.map((e,t)=>T(H,{dimColor:!0,children:` · ${e}`},`${e}-${t}`)),s.headline?T(H,{dimColor:!0,children:` · ${s.headline}`}):null,s.preview?T(H,{dimColor:!0,children:` · ${s.preview}`}):null,s.countdown?T(H,{color:Dt(n,s.statusKind),children:` · ${s.countdown}`}):null]},i.id)})]})}function Yt({percentage:e}){let t=K(),n=G();return e>=90?T(i,{...n?{}:{borderStyle:`single`,borderColor:t.border.error},paddingX:1,children:E(H,{color:t.text.error,bold:!0,children:[`⚠ Context at `,Math.round(e),`% — window nearly full. Run /compact to summarize the conversation.`]})}):e>=70?T(i,{paddingX:1,children:E(H,{color:t.text.warning,children:[`Context at `,Math.round(e),`% — consider running /compact to free up space.`]})}):null}function Xt({entry:e,page:t,loading:n,error:r}){let a=K(),o=Ft(e,{selectedEntryId:e.id}),s=t?.records.slice(-12)??[];return E(i,{flexDirection:`column`,marginBottom:1,children:[T(H,{color:a.text.accent,bold:!0,children:`Viewing ${o.title}`}),E(H,{dimColor:!0,children:[o.statusLabel,o.subtitle?` · ${o.subtitle}`:``,o.preview?` · ${o.preview}`:``]}),n?T(H,{dimColor:!0,children:`Loading workspace detail...`}):null,r?T(H,{color:a.text.error,children:r}):null,!n&&!r&&s.length===0?T(H,{dimColor:!0,children:`No detail yet`}):null,!n&&!r&&s.map(e=>{let{symbol:t,color:n}=Zt(e.kind,a);return E(H,{color:n,children:[t?`${t} `:``,It(e)]},e.id)}),t?.nextCursor?T(H,{dimColor:!0,children:`... more detail available`}):null]})}function Zt(e,t){return e===`error`?{symbol:Et.error,color:Dt(t,`error`)}:e===`result`?{symbol:Et.success,color:Dt(t,`success`)}:e===`group_summary`?{symbol:`▸`,color:t.text.accent}:e===`process_output`?{symbol:`·`,color:t.text.emphasis}:{symbol:``,color:void 0}}function Qt(e=0){return{selectedIndex:e,scrollOffset:0,resolved:!1}}function $t(){return{buffer:``,invalid:!1,resolved:!1}}function en(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 tn(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=on(e.selectedIndex,n.itemCount);return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`select`,index:t}}}let r=rn(e.selectedIndex,t,n),i=an(r,e.scrollOffset,n);return{state:{...e,selectedIndex:r,scrollOffset:i},effect:{type:`none`}}}function nn(e,t){if(t.itemCount===0)return{...e,selectedIndex:0,scrollOffset:0};let n=on(e.selectedIndex,t.itemCount),r=an(n,e.scrollOffset,t);return n===e.selectedIndex&&r===e.scrollOffset?e:{...e,selectedIndex:n,scrollOffset:r}}function rn(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 an(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 on(e,t){return Math.min(Math.max(e,0),t-1)}function sn({entries:e,selectedEntryId:t,onSelect:n,onClose:r}){let[i,a]=C(()=>Qt()),o=S(i);y(()=>{let n=ln({selectedIndex:Math.max(0,e.findIndex(e=>e.id===t)),itemCount:e.length});o.current=n,a(n)},[e.length,t]);let s=ln({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:cn({entries:e,stateRef:o,setState:a,onSelect:n,onClose:r})}}function cn({entries:e,stateRef:t,setState:n,onSelect:r,onClose:i}){return a=>{let o=tn(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 ln(e){return nn({selectedIndex:e.selectedIndex,scrollOffset:e.scrollOffset??0,resolved:!1},{itemCount:e.itemCount,maxVisible:8})}function un(e){let[t,n]=C($t),r=S(t),{enabled:i,itemCount:a,cancellable:o,multi:s,repeatable:c,onSelect:l,onCancel:u,onConfirm:f}=e,p=_(()=>{let e=$t();r.current=e,n(e)},[]),m=_((e,t)=>{let i=en(r.current,e,t,{itemCount:a,...o===!0?{cancellable:!0}:{},...s===!0?{multi:!0}:{},...c===!0?{repeatable:!0}:{}});r.current=i.state,n(i.state),i.effect.type===`select`?l(i.effect.index):i.effect.type===`cancel`?u?.():i.effect.type===`confirm`&&f?.()},[a,o,s,c,l,u,f]);return d((e,t)=>{m(e,t)},{isActive:i}),{buffer:t.buffer,invalid:t.invalid,clear:p}}function dn(e){return e.map(e=>`${e.keys} ${e.label}`).join(` · `)}function Y({hints:e}){return e.length===0?null:E(H,{dimColor:!0,children:[` `,dn(e)]})}const fn={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`]}},mn=new Set([`chat-input`,`text-input`,`text-prompt`,`history-search`]),hn={ctrl:`ctrl`,control:`ctrl`,alt:`alt`,option:`alt`,meta:`meta`,cmd:`meta`,command:`meta`,shift:`shift`},gn=[`ctrl`,`alt`,`meta`,`shift`],_n={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 vn(e){let t=e.trim().split(/\s+/u);if(t.length<1||t.length>2)return;let n=t.map(yn);return n.every(e=>e!==void 0)?n.join(` `):void 0}function yn(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=hn[e.toLowerCase()];if(t===void 0||r.has(t))return;r.add(t)}let i=_n[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[...gn.filter(e=>r.has(e)),i].join(`+`)}function bn(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 xn(e,t){let n=bn(e,t);return n===void 0?[]:n===`enter`?[`enter`,`ctrl+m`]:n===`tab`?[`tab`,`ctrl+i`]:n===`escape`?[`escape`,`ctrl+[`]:[n]}function Sn(e){return e.split(` `).map(e=>e===`ctrl+m`?`enter`:e===`ctrl+i`?`tab`:e===`ctrl+[`?`escape`:e).join(` `)}function Cn(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 wn(){return Object.fromEntries(Object.entries(pn).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([e,t])=>[e,[...t]]))]))}function Tn(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 En(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=Sn(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&&mn.has(e)&&Dn(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 Dn(e){return!e.includes(`+`)&&[...e].length===1}function On(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 kn(e,t){let n;try{n=JSON.parse(e)}catch(e){return X(t,`$`,e instanceof Error?e.message:`Invalid JSON.`)}if(!it(n))return X(t,`$`,`Expected an object.`);if(n.version!==1)return X(t,`$.version`,`Expected version 1.`);if(!it(n.bindings))return X(t,`$.bindings`,`Expected an object.`);let r=wn(),i=[];for(let[e,a]of Object.entries(n.bindings)){if(!(e in fn))return X(t,`$.bindings.${e}`,`Unknown keybinding context.`);let n=e;if(!it(a))return X(t,`$.bindings.${n}`,`Expected an action object.`);for(let[e,o]of Object.entries(a)){if(!fn[n].includes(e))return X(t,`$.bindings.${n}.${e}`,`Unknown action.`);let a=Tn(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=vn(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(...On(n,s))}r[n][e]=c}}for(let e of Object.keys(r)){let n=En(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 An(){return{strokes:[]}}function jn(e,t){return Object.entries(e.bindings[t])}function Mn(e){let t=xn(e.input,e.key);if(t.length===0)return{state:An(),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=jn(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:An(),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?Mn({...e,state:An()}):{state:An(),actions:[],consumed:!1}}function Nn(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(Cn),s=o.every(e=>/^[↑↓←→]$/u.test(e))?o.join(``):o.join(`/`);return a.length===0?[]:[{keys:s,label:r}]})}const Pn=kn(`{"version":1,"bindings":{}}`,`<defaults>`);if(!Pn.ok)throw Error(Pn.diagnostic.message);const Fn=Pn.snapshot,In=g(Fn);function Ln({source:e,children:t}){let[n,r]=C(()=>e?.getSnapshot()??Fn);return y(()=>{if(e!==void 0)return r(e.getSnapshot()),e.subscribe(r)},[e]),T(In.Provider,{value:n,children:t})}function Rn(){return v(In)}function Z(e,t){return Nn(Rn(),e,t)}function Q(e,t,n={}){let r=Rn(),i=S(An()),a=S(An()),{fallbackContext:o}=n;y(()=>{i.current=An(),a.current=An()},[e,o,r.generation]),d((n,s)=>{let c=Mn({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=An(),t(c.actions,n,s,c.consumed,e);return}let l=Mn({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 zn(e,t){let n=`Enter selection (1-${e})`;return t?`${n} or Escape to cancel`:n}function Bn(e){return`${e+1}. `}function Vn({itemCount:e,cancellable:t=!1,buffer:n=``,invalid:r=!1}){if(e===0)return null;let i=zn(e,t);return E(w,{children:[E(H,{children:[i,n.length>0?` ${n}`:``]}),r&&T(H,{children:i})]})}function Hn({title:e,description:t,options:n,cancellable:r=!1,buffer:a=``,invalid:o=!1}){return E(i,{flexDirection:`column`,children:[e!==void 0&&e.length>0&&T(H,{children:e}),t!==void 0&&t.length>0&&T(H,{children:t}),n.map((e,t)=>E(H,{children:[Bn(t),e]},`${t}-${e}`)),T(Vn,{itemCount:n.length,cancellable:r,buffer:a,invalid:o})]})}function Un(e){return e?.controls.includes(`attach`)===!0}function Wn({snapshot:e,selectedEntryId:t,onSelect:n,onClose:r,onAttach:a}){let o=K(),s=[...e?.entries??[]],{normalized:c,visibleEntries:l,applyAction:u}=sn({entries:s,selectedEntryId:t,onSelect:n,onClose:r}),d=s[c.selectedIndex],f=a!==void 0&&Un(d),p=G(),m=un({enabled:p&&s.length>0,itemCount:s.length,cancellable:!0,onSelect:e=>{let t=s[e];t&&n(t.id)},onCancel:r});Q(`workspace-switcher`,e=>{for(let t of e)t===`attach`&&f&&d?(a(d),r()):t===`previous`||t===`next`||t===`select`?u(t):t===`close`&&u(`cancel`)},{isActive:!p});let h=Z(`workspace-switcher`,[[[`previous`,`next`],`Navigate`],[`select`,`Switch`],[`close`,`Close`]]),g=Z(`workspace-switcher`,[[`attach`,`Attach`]]);return E(i,{flexDirection:`column`,...p?{}:{borderStyle:`round`,borderColor:o.border.focused},paddingX:1,children:[T(H,{color:o.text.accent,bold:!0,children:`Execution workspace`}),T(i,{flexDirection:`column`,marginTop:1,children:l.length===0?T(H,{dimColor:!0,children:`No workspace entries`}):p?s.map((e,n)=>T(Kn,{entry:e,isFocused:!1,selectedEntryId:t,rowNumber:n},e.id)):l.map((e,n)=>T(Kn,{entry:e,isFocused:c.scrollOffset+n===c.selectedIndex,selectedEntryId:t},e.id))}),p?T(Gn,{itemCount:s.length,buffer:m.buffer,invalid:m.invalid}):T(Y,{hints:f?[...h,...g]:h})]})}function Gn({itemCount:e,buffer:t,invalid:n}){let r=zn(e,!0);return E(i,{flexDirection:`column`,children:[E(H,{children:[r,t.length>0?` ${t}`:``]}),n&&T(H,{children:r})]})}function Kn({entry:e,isFocused:t,selectedEntryId:n,rowNumber:r}){let i=K(),a=Ft(e,{selectedEntryId:n});return E(H,{children:[T(H,{color:t?i.text.accent:void 0,bold:t,children:r===void 0?t?`> `:` `:Bn(r)}),T(H,{color:Dt(i,a.statusKind),children:`${a.radio} ${a.state}`}),T(H,{color:t?i.text.accent:void 0,bold:t,children:` ${a.title}`}),T(H,{dimColor:!0,children:` · ${a.statusLabel}`}),a.subtitle?T(H,{dimColor:!0,children:` · ${a.subtitle}`}):null,a.preview?T(H,{dimColor:!0,children:` · ${a.preview}`}):null]})}function qn(e,t,n){let r=0;for(let i=0;i<t&&i<e.length;i++){let t=D(e[i]),a=r%n;a+t>n&&(r+=n-a),r+=t}return r}function Jn(e,t,n){let r=0;for(let i=0;i<e.length;i++){if(r>=t)return i;let a=D(e[i]),o=r%n;o+a>n&&(r+=n-o),r+=a}return e.length}function Yn(e,t,n){if(!n||n<=0)return{state:e,effect:{type:`none`}};let r=[...e.value],i=qn(r,e.cursor,n),a=t===`up`?i-n:i+n;if(a<0)return{state:e,effect:{type:`none`}};let o=Jn(r,a,n);return o===e.cursor?{state:e,effect:{type:`none`}}:{state:{...e,cursor:o},effect:{type:`render`}}}function Xn(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 Zn(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 Qn(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 $n(e,t){if(!(t<=0))return{value:e.slice(t),cursor:0,deleted:e.slice(0,t)}}const er=`[200~`,tr=`[201~`;function nr(e){return{value:e,cursor:e.length,isPasting:!1,pasteBuffer:``}}function rr(e,t,n){return t===e.value?e:{...e,value:t,cursor:n==null?t.length:Math.min(n,t.length)}}function ir(e,t,n,r){let i=or(e,t,r);if(i!==void 0)return i;let a=sr(e,t,n,r);if(a!==void 0)return a;let o=cr(e,n,r);return o===void 0?mr(e,t):o}function ar(e,t,n){let r=t.replace(/\r\n?/g,`
10
+ `}),E(H,{dimColor:!0,children:[` v`,e]})]})}const Dt=1e3;function Ot(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/Dt),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 kt={running:`⟳`,success:`✓`,error:`✗`,denied:`⊘`,waiting:`◴`,cancelled:`⊗`,idle:`·`};function At(e,t){return e.status[t]}function jt(e){return e.isRunning?`running`:e.result===`error`?`error`:e.result===`denied`?`denied`:`success`}const Mt=[`active`,`queued`,`running`,`sleeping`];function Nt(e,t){return t===`failed`||e===`failed`?`error`:t===`permission`||e===`waiting_permission`?`waiting`:e===`completed`?`success`:e===`cancelled`?`cancelled`:Mt.includes(e)?`running`:`idle`}const Pt=[`active`,`queued`,`running`,`waiting_permission`,`sleeping`],Ft=/\s+/g;function It(e){return(e?.entries??[]).filter(e=>e.kind===`background_task`&&e.visibility==="default")}function Lt(e){return It(e).filter(e=>Pt.includes(e.status)).length}function Rt(e,t={}){let n=e.id===t.selectedEntryId,r={id:e.id,radio:n?`●`:`○`,state:e.state,title:Bt(e),subtitle:Vt(e),statusLabel:Ht(e.status),preview:Wt(e.preview??e.currentAction),statusKind:Ut(e),isSelected:n};return{...r,accessibleText:Gt(r)}}function zt(e){let t=e.text.trim().replace(Ft,` `);return t?t.length>160?`${t.slice(0,160)}...`:t:e.kind}function Bt(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 Vt(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 Ht(e){return e.replace(/_/g,` `)}function Ut(e){return Nt(e.status,e.attention)}function Wt(e){return e?.trim().replace(Ft,` `)||void 0}function Gt(e){return[`${e.radio} ${e.state}`,e.title,e.statusLabel,e.subtitle,e.preview].filter(e=>typeof e==`string`&&e.length>0).join(` · `)}const Kt={branch:`├`,last:`└`,plain:`-`};function qt(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 Jt(e){return e.screenReader===!0?Kt.plain:e.isLast===!1?Kt.branch:Kt.last}function Yt(e,t={}){let n=Rt(e),r=kt[Nt(e.status,e.attention)],i=[n.statusLabel,n.subtitle].filter(e=>typeof e==`string`&&e.length>0),a=Jt(t),o=qt(e,n.preview,n.subtitle),s=e.nextFireAt===void 0?void 0:Ot(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 Xt(e,t){let n=e&&!t,[r,i]=C(()=>new Date);return y(()=>{if(!n)return;i(new Date);let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[n]),n?r:new Date}function Zt({entries:e,focusedIndex:t=null}){let n=G(),r=W(),a=Xt(e.some(e=>e.nextFireAt!==void 0),r);if(e.length===0)return null;let o=t===null?` · ↓ select · Ctrl+B all`:` · ↑↓ select · Enter open · Esc back`;return E(i,{flexDirection:`column`,marginBottom:1,children:[E(i,{children:[T(H,{color:n.text.accent,bold:!0,children:`Background work`}),T(H,{dimColor:!0,children:o})]}),e.map((i,o)=>{let s=Yt(i,{isLast:o===e.length-1,screenReader:r,now:a});return E(H,{wrap:`truncate-end`,inverse:o===t,children:[`${s.connector} `,T(H,{color:At(n,s.statusKind),children:`${s.marker} ${s.state}`}),` ${s.label}`,s.segments.map((e,t)=>T(H,{dimColor:!0,children:` · ${e}`},`${e}-${t}`)),s.headline?T(H,{dimColor:!0,children:` · ${s.headline}`}):null,s.preview?T(H,{dimColor:!0,children:` · ${s.preview}`}):null,s.countdown?T(H,{color:At(n,s.statusKind),children:` · ${s.countdown}`}):null]},i.id)})]})}function Qt({percentage:e}){let t=G(),n=W();return e>=90?T(i,{...n?{}:{borderStyle:`single`,borderColor:t.border.error},paddingX:1,children:E(H,{color:t.text.error,bold:!0,children:[`⚠ Context at `,Math.round(e),`% — window nearly full. Run /compact to summarize the conversation.`]})}):e>=70?T(i,{paddingX:1,children:E(H,{color:t.text.warning,children:[`Context at `,Math.round(e),`% — consider running /compact to free up space.`]})}):null}function $t({entry:e,page:t,loading:n,error:r}){let a=G(),o=Rt(e,{selectedEntryId:e.id}),s=t?.records.slice(-12)??[];return E(i,{flexDirection:`column`,marginBottom:1,children:[T(H,{color:a.text.accent,bold:!0,children:`Viewing ${o.title}`}),E(H,{dimColor:!0,children:[o.statusLabel,o.subtitle?` · ${o.subtitle}`:``,o.preview?` · ${o.preview}`:``]}),n?T(H,{dimColor:!0,children:`Loading workspace detail...`}):null,r?T(H,{color:a.text.error,children:r}):null,!n&&!r&&s.length===0?T(H,{dimColor:!0,children:`No detail yet`}):null,!n&&!r&&s.map(e=>{let{symbol:t,color:n}=en(e.kind,a);return E(H,{color:n,children:[t?`${t} `:``,zt(e)]},e.id)}),t?.nextCursor?T(H,{dimColor:!0,children:`... more detail available`}):null]})}function en(e,t){return e===`error`?{symbol:kt.error,color:At(t,`error`)}:e===`result`?{symbol:kt.success,color:At(t,`success`)}:e===`group_summary`?{symbol:`▸`,color:t.text.accent}:e===`process_output`?{symbol:`·`,color:t.text.emphasis}:{symbol:``,color:void 0}}function tn(e=0){return{selectedIndex:e,scrollOffset:0,resolved:!1}}function nn(){return{buffer:``,invalid:!1,resolved:!1}}function rn(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 an(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=ln(e.selectedIndex,n.itemCount);return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`select`,index:t}}}let r=sn(e.selectedIndex,t,n),i=cn(r,e.scrollOffset,n);return{state:{...e,selectedIndex:r,scrollOffset:i},effect:{type:`none`}}}function on(e,t){if(t.itemCount===0)return{...e,selectedIndex:0,scrollOffset:0};let n=ln(e.selectedIndex,t.itemCount),r=cn(n,e.scrollOffset,t);return n===e.selectedIndex&&r===e.scrollOffset?e:{...e,selectedIndex:n,scrollOffset:r}}function sn(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 cn(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 ln(e,t){return Math.min(Math.max(e,0),t-1)}function un({entries:e,selectedEntryId:t,onSelect:n,onClose:r}){let[i,a]=C(()=>tn()),o=S(i);y(()=>{let n=fn({selectedIndex:Math.max(0,e.findIndex(e=>e.id===t)),itemCount:e.length});o.current=n,a(n)},[e.length,t]);let s=fn({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=an(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 fn(e){return on({selectedIndex:e.selectedIndex,scrollOffset:e.scrollOffset??0,resolved:!1},{itemCount:e.itemCount,maxVisible:8})}function pn(e){let[t,n]=C(nn),r=S(t),{enabled:i,itemCount:a,cancellable:o,multi:s,repeatable:c,onSelect:l,onCancel:u,onConfirm:f}=e,p=_(()=>{let e=nn();r.current=e,n(e)},[]),m=_((e,t)=>{let i=rn(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`&&f?.(),i.effect.type!==`none`},[a,o,s,c,l,u,f]);return d((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)?m(``,{...n,return:!0}):m(t,n)))break;return}m(e,t)},{isActive:i}),{buffer:t.buffer,invalid:t.invalid,clear:p}}function mn(e){return e.map(e=>`${e.keys} ${e.label}`).join(` · `)}function J({hints:e}){return e.length===0?null:E(H,{dimColor:!0,children:[` `,mn(e)]})}const hn={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`]},gn={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`]}},_n=new Set([`chat-input`,`text-input`,`text-prompt`,`history-search`]),vn={ctrl:`ctrl`,control:`ctrl`,alt:`alt`,option:`alt`,meta:`meta`,cmd:`meta`,command:`meta`,shift:`shift`},yn=[`ctrl`,`alt`,`meta`,`shift`],bn={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 xn(e){let t=e.trim().split(/\s+/u);if(t.length<1||t.length>2)return;let n=t.map(Sn);return n.every(e=>e!==void 0)?n.join(` `):void 0}function Sn(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=vn[e.toLowerCase()];if(t===void 0||r.has(t))return;r.add(t)}let i=bn[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[...yn.filter(e=>r.has(e)),i].join(`+`)}function Cn(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 wn(e,t){let n=Cn(e,t);return n===void 0?[]:n===`enter`?[`enter`,`ctrl+m`]:n===`tab`?[`tab`,`ctrl+i`]:n===`escape`?[`escape`,`ctrl+[`]:[n]}function Tn(e){return e.split(` `).map(e=>e===`ctrl+m`?`enter`:e===`ctrl+i`?`tab`:e===`ctrl+[`?`escape`:e).join(` `)}function En(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 Y(e,t,n){return{ok:!1,diagnostic:{file:e,path:t,message:n}}}function Dn(){return Object.fromEntries(Object.entries(gn).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([e,t])=>[e,[...t]]))]))}function On(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 kn(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=Tn(t),s=r.get(o),c=`$.bindings.${e}.${a}`;if(s!==void 0&&s!==a)return Y(n,c,`Binding duplicates action ${s}.`);let l=o.split(` `);if(l.length>1&&_n.has(e)&&An(l[0]??``))return Y(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 Y(n,`$.bindings.${e}.${r}`,`Chord prefix collides with action ${a}.`)}}function An(e){return!e.includes(`+`)&&[...e].length===1}function jn(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 Mn(e,t){let n;try{n=JSON.parse(e)}catch(e){return Y(t,`$`,e instanceof Error?e.message:`Invalid JSON.`)}if(!st(n))return Y(t,`$`,`Expected an object.`);if(n.version!==1)return Y(t,`$.version`,`Expected version 1.`);if(!st(n.bindings))return Y(t,`$.bindings`,`Expected an object.`);let r=Dn(),i=[];for(let[e,a]of Object.entries(n.bindings)){if(!(e in hn))return Y(t,`$.bindings.${e}`,`Unknown keybinding context.`);let n=e;if(!st(a))return Y(t,`$.bindings.${n}`,`Expected an action object.`);for(let[e,o]of Object.entries(a)){if(!hn[n].includes(e))return Y(t,`$.bindings.${n}.${e}`,`Unknown action.`);let a=On(o),s=`$.bindings.${n}.${e}`;if(a===void 0)return Y(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=xn(e);if(n===void 0)return Y(t,s,`Invalid binding syntax.`);if(n.split(` `).includes(`ctrl+c`))return Y(t,s,`Ctrl+C is reserved for two-stage shutdown.`);c.push(n),i.push(...jn(n,s))}r[n][e]=c}}for(let e of Object.keys(r)){let n=kn(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 Nn(){return{strokes:[]}}function Pn(e,t){return Object.entries(e.bindings[t])}function Fn(e){let t=wn(e.input,e.key);if(t.length===0)return{state:Nn(),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=Pn(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:Nn(),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?Fn({...e,state:Nn()}):{state:Nn(),actions:[],consumed:!1}}function In(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(En),s=o.every(e=>/^[↑↓←→]$/u.test(e))?o.join(``):o.join(`/`);return a.length===0?[]:[{keys:s,label:r}]})}const Ln=Mn(`{"version":1,"bindings":{}}`,`<defaults>`);if(!Ln.ok)throw Error(Ln.diagnostic.message);const Rn=Ln.snapshot,zn=g(Rn);function Bn({source:e,children:t}){let[n,r]=C(()=>e?.getSnapshot()??Rn);return y(()=>{if(e!==void 0)return r(e.getSnapshot()),e.subscribe(r)},[e]),T(zn.Provider,{value:n,children:t})}function Vn(){return v(zn)}function X(e,t){return In(Vn(),e,t)}function Z(e,t,n={}){let r=Vn(),i=S(Nn()),a=S(Nn()),{fallbackContext:o}=n;y(()=>{i.current=Nn(),a.current=Nn()},[e,o,r.generation]),d((n,s)=>{let c=Fn({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=Nn(),t(c.actions,n,s,c.consumed,e);return}let l=Fn({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 Hn(e,t){let n=`Enter selection (1-${e})`;return t?`${n} or Escape to cancel`:n}function Un(e){return`${e+1}. `}function Wn({itemCount:e,cancellable:t=!1,buffer:n=``,invalid:r=!1}){if(e===0)return null;let i=Hn(e,t);return E(w,{children:[E(H,{children:[i,n.length>0?` ${n}`:``]}),r&&T(H,{children:i})]})}function Gn({title:e,description:t,options:n,cancellable:r=!1,buffer:a=``,invalid:o=!1}){return E(i,{flexDirection:`column`,children:[e!==void 0&&e.length>0&&T(H,{children:e}),t!==void 0&&t.length>0&&T(H,{children:t}),n.map((e,t)=>E(H,{children:[Un(t),e]},`${t}-${e}`)),T(Wn,{itemCount:n.length,cancellable:r,buffer:a,invalid:o})]})}function Kn(e){return e?.controls.includes(`attach`)===!0}function qn({snapshot:e,selectedEntryId:t,onSelect:n,onClose:r,onAttach:a}){let o=G(),s=[...e?.entries??[]],{normalized:c,visibleEntries:l,applyAction:u}=un({entries:s,selectedEntryId:t,onSelect:n,onClose:r}),d=s[c.selectedIndex],f=a!==void 0&&Kn(d),p=W(),m=pn({enabled:p&&s.length>0,itemCount:s.length,cancellable:!0,onSelect:e=>{let t=s[e];t&&n(t.id)},onCancel:r});Z(`workspace-switcher`,e=>{for(let t of e)t===`attach`&&f&&d?(a(d),r()):t===`previous`||t===`next`||t===`select`?u(t):t===`close`&&u(`cancel`)},{isActive:!p});let h=X(`workspace-switcher`,[[[`previous`,`next`],`Navigate`],[`select`,`Switch`],[`close`,`Close`]]),g=X(`workspace-switcher`,[[`attach`,`Attach`]]);return E(i,{flexDirection:`column`,...p?{}:{borderStyle:`round`,borderColor:o.border.focused},paddingX:1,children:[T(H,{color:o.text.accent,bold:!0,children:`Execution workspace`}),T(i,{flexDirection:`column`,marginTop:1,children:l.length===0?T(H,{dimColor:!0,children:`No workspace entries`}):p?s.map((e,n)=>T(Yn,{entry:e,isFocused:!1,selectedEntryId:t,rowNumber:n},e.id)):l.map((e,n)=>T(Yn,{entry:e,isFocused:c.scrollOffset+n===c.selectedIndex,selectedEntryId:t},e.id))}),p?T(Jn,{itemCount:s.length,buffer:m.buffer,invalid:m.invalid}):T(J,{hints:f?[...h,...g]:h})]})}function Jn({itemCount:e,buffer:t,invalid:n}){let r=Hn(e,!0);return E(i,{flexDirection:`column`,children:[E(H,{children:[r,t.length>0?` ${t}`:``]}),n&&T(H,{children:r})]})}function Yn({entry:e,isFocused:t,selectedEntryId:n,rowNumber:r}){let i=G(),a=Rt(e,{selectedEntryId:n});return E(H,{children:[T(H,{color:t?i.text.accent:void 0,bold:t,children:r===void 0?t?`> `:` `:Un(r)}),T(H,{color:At(i,a.statusKind),children:`${a.radio} ${a.state}`}),T(H,{color:t?i.text.accent:void 0,bold:t,children:` ${a.title}`}),T(H,{dimColor:!0,children:` · ${a.statusLabel}`}),a.subtitle?T(H,{dimColor:!0,children:` · ${a.subtitle}`}):null,a.preview?T(H,{dimColor:!0,children:` · ${a.preview}`}):null]})}function Xn(e,t,n){let r=0;for(let i=0;i<t&&i<e.length;i++){let t=D(e[i]),a=r%n;a+t>n&&(r+=n-a),r+=t}return r}function Zn(e,t,n){let r=0;for(let i=0;i<e.length;i++){if(r>=t)return i;let a=D(e[i]),o=r%n;o+a>n&&(r+=n-o),r+=a}return e.length}function Qn(e,t,n){if(!n||n<=0)return{state:e,effect:{type:`none`}};let r=[...e.value],i=Xn(r,e.cursor,n),a=t===`up`?i-n:i+n;if(a<0)return{state:e,effect:{type:`none`}};let o=Zn(r,a,n);return o===e.cursor?{state:e,effect:{type:`none`}}:{state:{...e,cursor:o},effect:{type:`render`}}}function $n(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 er(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 tr(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 nr(e,t){if(!(t<=0))return{value:e.slice(t),cursor:0,deleted:e.slice(0,t)}}const rr=`[200~`,ir=`[201~`;function ar(e){return{value:e,cursor:e.length,isPasting:!1,pasteBuffer:``}}function or(e,t,n){return t===e.value?e:{...e,value:t,cursor:n==null?t.length:Math.min(n,t.length)}}function sr(e,t,n,r){let i=lr(e,t,r);if(i!==void 0)return i;let a=ur(e,t,n,r);if(a!==void 0)return a;let o=dr(e,n,r);return o===void 0?_r(e,t):o}function cr(e,t,n){let r=t.replace(/\r\n?/g,`
11
11
  `);return r.length===0?{state:e,effect:{type:`none`}}:r.includes(`
12
- `)&&n.canPaste?{state:e,effect:{type:`paste`,text:r,cursor:e.cursor}}:mr(e,r)}function or(e,t,n){if(t===er||t.startsWith(er))return dr(e,t);if(e.isPasting)return fr(e,t,n)}function sr(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`?Qn:$n)(e.value,e.cursor),n)}if(n.return===!0)return{state:e,effect:{type:`submit`,value:e.value}};if(t.length>1&&(t.includes(`
12
+ `)&&n.canPaste?{state:e,effect:{type:`paste`,text:r,cursor:e.cursor}}:_r(e,r)}function lr(e,t,n){if(t===rr||t.startsWith(rr))return mr(e,t);if(e.isPasting)return hr(e,t,n)}function ur(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 gr(e,(n===`word`?tr:nr)(e.value,e.cursor),n)}if(n.return===!0)return{state:e,effect:{type:`submit`,value:e.value}};if(t.length>1&&(t.includes(`
13
13
  `)||t.includes(`\r`))&&r.canPaste)return{state:e,effect:{type:`paste`,text:t.replace(/\r\n?/g,`
14
- `),cursor:e.cursor}}}function cr(e,t,n){if(t.upArrow===!0||t.downArrow===!0)return n.enableVerticalNavigation===!1?{state:e,effect:{type:`none`}}:Yn(e,t.upArrow===!0?`up`:`down`,n.availableWidth);if(t.leftArrow===!0)return Xn(e,`left`);if(t.rightArrow===!0)return Xn(e,`right`);if(t.backspace===!0||t.delete===!0)return pr(e,Zn(e.value,e.cursor))}function lr(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 ur(e,t,n){return{value:e.slice(0,t)+n+e.slice(t),cursor:t+n.length}}function dr(e,t){return{state:{...e,isPasting:!0,pasteBuffer:t.slice(5)},effect:{type:`none`}}}function fr(e,t,n){if(t!==tr&&!t.includes(tr))return{state:{...e,pasteBuffer:e.pasteBuffer+t},effect:{type:`none`}};let r=t.split(tr)[0]??``;return ar({...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 mr(e,t){let n=lr(t);if(n.length===0)return{state:e,effect:{type:`none`}};let r=ur(e.value,e.cursor,n);return{state:{...e,value:r.value,cursor:r.cursor},effect:{type:`change`,value:r.value}}}function hr(){return{timer:null,isSubmitting:!1}}function gr(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 _r(e,t=clearTimeout){e.timer!==null&&(t(e.timer),e.timer=null),e.isSubmitting=!1}function vr(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=qn(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 yr(e){return!(!e.capability||!e.hasMeasured||e.viewportRows<=0||e.frameHeight<=0||e.frameHeight>=e.viewportRows||e.y<0||e.y>=e.frameHeight)}function br(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 xr(e,t){return e===void 0||t===void 0?e===t:e.x===t.x&&e.y===t.y&&e.frameHeight===t.frameHeight}function Sr(e){let{setCursorPosition:t}=u(),n=l(e.boxRef),{rows:r}=m(),[i,a]=C(void 0);y(()=>{let t=e.boxRef.current,n=t===null?void 0:br(t);a(e=>xr(e,n)?e:n)});let o=i!==void 0&&e.enabled?vr({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&&yr({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 Cr=g({armEchoRelease(){},write(e){process.stdout.write(e)}});function wr({port:e,children:t}){return T(Cr.Provider,{value:e,children:t})}function Tr(){return v(Cr)}const Er=g({});function Dr({overrides:e,children:t}){return T(Er.Provider,{value:e??{},children:t})}function Or(){return v(Er)}function kr({value:e,onChange:t,onSubmit:n,onPaste:r,placeholder:a=``,focus:o=!0,showCursor:s=!0,availableWidth:c,cursorHint:l=null,enableVerticalNavigation:u=!0,onDeletedText:d,keybindingContext:f=`text-input`}){let p=S(nr(e)),[,m]=C(0),h=S(hr());y(()=>()=>_r(h.current),[]),p.current=rr(p.current,e,l),jr({stateRef:p,onChange:t,onSubmit:n,onPaste:r,availableWidth:c,focus:o,enableVerticalNavigation:u,...d===void 0?{}:{onDeletedText:d},forceRender:m,deferState:h.current,keybindingContext:f});let g=K(),_=x(()=>q(g.text.muted),[g.text.muted]),v=S(null),b=Or(),{realCursorActive:w}=Sr({boxRef:v,enabled:o&&s&&je({override:b.imeCursorPositioning}),value:p.current.value,cursor:p.current.cursor,...c===void 0?{}:{availableWidth:c}});return T(i,{ref:v,children:T(U,{children:Ir(p.current.value,p.current.cursor,a,s&&o&&!w,_)})})}function Ar(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 jr(e){let t=Tr();f(n=>{t.armEchoRelease(),Pr(e,()=>ar(e.stateRef.current,n,Nr(e)))},{isActive:e.focus}),Q(e.keybindingContext,(n,r,i,a,o)=>{let s=Mr(o,n,r,i,a);s!==void 0&&(Ar(n[0],s)&&t.armEchoRelease(),Pr(e,()=>ir(e.stateRef.current,s.input,s.key,Nr(e))))},{isActive:e.focus,...e.keybindingContext===`autocomplete-menu`?{fallbackContext:`chat-input`}:{}})}function Mr(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 Nr(e){return{availableWidth:e.availableWidth,canPaste:e.onPaste!==void 0,enableVerticalNavigation:e.enableVerticalNavigation}}function Pr(e,t){try{let n=t();e.stateRef.current=n.state,Fr(e,n.effect)}catch{}}function Fr(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&&gr(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 Ir(t,n,r,i,a){let o=V(t),s=V(r);if(!i)return o.length>0?o:s?a(s):``;if(o.length===0)return s.length>0?e.inverse(s[0])+a(s.slice(1)):e.inverse(` `);let c=[...o],l=``;for(let t=0;t<c.length;t++){let r=c[t]??``;l+=t===n?e.inverse(r):r}return n>=c.length&&(l+=e.inverse(` `)),l}const Lr=`Prompt from an external link`;function Rr(e){if(e.length!==0)return e.length>1e3?`${Lr} — ${e.length} characters; scroll and review the full text before sending`:Lr}function zr({value:e}){let t=Rr(e);return t===void 0?null:T(H,{dimColor:!0,children:t})}function Br(){return{selectedIndex:null,draft:``}}function Vr(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:Br()}}function Hr(e,t){let n=t.trim();return n.length===0||e[e.length-1]===n?[...e]:[...e,n]}function Ur(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=Hr(t,e.content))}return t}function Wr(e,t,n){return t===0?0:n===`previous`?e>0?e-1:t-1:e<t-1?e+1:0}function Gr(e,t){if(oe(e)&&e.slice(1).includes(` `)){let{name:n}=ue(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 Kr(e,t){if(oe(e)&&e.slice(1).includes(` `)){let{name:n}=ue(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 qr(e,t,n,r){let i=r.split(`
15
- `).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 Jr(e){return e.trim().length>0}const Yr=[`all`,`session`,`project`];function Xr(e){let t=Yr.indexOf(e);return Yr[(t+1)%Yr.length]??`all`}function Zr(e,t,n){switch(t){case`all`:return!0;case`session`:return e.sessionId===n.sessionId;case`project`:return e.project===n.project}}function Qr(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 $r(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 ei(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 ti(e,t){return t<=8||e<8?0:Math.min(e-8+1,t-8)}function ni(e){return`${e} unreadable ${e===1?`line`:`lines`} skipped`}function ri(e){let t=K(),{match:n,selected:r,rowNumber:i,color:a}=e,o=i===void 0?r?`> `:` `:Bn(i),s=ei(n.entry.text.replace(/\r\n|[\r\n]/gu,e=>e.length===2?` ↵`:`↵`),n.ranges);return E(H,{color:r?t.text.accent:void 0,dimColor:!r,wrap:`truncate-end`,children:[o,s.map((e,t)=>e.matched?T(H,{bold:!0,inverse:a,children:a?e.text:`[${e.text}]`},t):T(H,{children:e.text},t))]})}function ii({view:e}){let t=K();if(e.error!==void 0)return E(H,{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(ni(e.skippedLines)),T(H,{dimColor:!0,children:n.join(` · `)})}function ai({view:e}){let t=K(),n=G(),r=Ae(),a=Z(`history-search`,[[[`previous`,`next`],`Navigate`],[`cycle-scope`,`Scope`],[`insert`,`Insert`],[`execute`,`Run`],[`cancel`,`Close`]]);if(!e.open)return null;let o=ti(e.selectedIndex,e.matches.length),s=e.matches.slice(o,o+8);return E(i,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.muted},paddingX:1,children:[E(H,{children:[T(H,{color:t.text.accent,children:`(reverse-i-search)`}),` scope: `,e.scope,` · query:`,` `,e.query]}),s.map((t,i)=>T(ri,{match:t,selected:o+i===e.selectedIndex,rowNumber:n?o+i:void 0,color:r},`${t.entry.at}:${o+i}`)),T(ii,{view:e}),T(Y,{hints:a})]})}function oi(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 si(e,t){let[n,r]=C(0),[i,a]=C(!1),o=h.useRef(e);o.current!==e&&(o.current=e,i&&a(!1));let s=oi(e),c=s.isSlash&&s.parentCommand.length>0,l=h.useRef(s.parentCommand);y(()=>{l.current!==s.parentCommand&&(l.current=s.parentCommand,r(0))},[s.parentCommand]);let u=x(()=>{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 ci={entries:[],skippedLines:0};function li(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 ui(e,t){return[...e].reverse().map(e=>({at:``,sessionId:t.sessionId,project:t.project,text:e}))}const di=()=>new Promise(e=>setImmediate(e));async function fi(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 di())}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]=C(ci),[i,a]=C(!1),[o,s]=C(void 0),c=S(void 0),l=S(ci),u=_(()=>r(l.current),[]),d=_(()=>{c.current?.abort(),c.current=void 0,a(!1)},[]),f=_(()=>{if(d(),l.current=ci,r(ci),s(void 0),e===void 0)return;let n=new AbortController;c.current=n,a(!0),fi({source:e.source,signal:n.signal,pending:l,publishEachBlock:!t,publish:u,setError:s,setLoading:a})},[u,t,d,e]);return y(()=>d,[d]),{loaded:n,loading:i,error:o,start:f,stop:d,publish:u}}function mi(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(Xr(e.scope)),e.setSelectedIndex(0)):!s&&(o.backspace||o.delete)?t(e=>e.slice(0,-1)):!s&&li(a,o)&&t(e=>e+a)},{isActive:e.open})}function hi(e,t,n,r,i){let a=t?.sessionId,o=t?.project;return x(()=>{if(!e||a===void 0||o===void 0)return[];let t={sessionId:a,project:o};return Qr(n===`session`?ui(r,t):i.filter(e=>Zr(e,n,t)))},[i,e,o,n,a,r])}const gi={query:``,scope:`all`,selectedIndex:0};function _i(){let[e,t]=C(gi);return{state:e,reset:_(()=>t(gi),[]),setters:x(()=>({setScope:e=>t(t=>({...t,scope:e})),setSelectedIndex:e=>t(t=>({...t,selectedIndex:e})),setQuery:e=>t(t=>({...t,query:e(t.query)}))}),[])}}function vi(e,t,n,r){let[i,a]=C(!1);return{open:i,openSearch:_(()=>{!t||i||(n(),a(!0),r?.(!0),e.start())},[t,e,r,i,n]),closeSearch:_(()=>{e.stop(),a(!1),r?.(!1)},[e,r])}}function yi(e){let t=G(),n=pi(e.surface,t),{state:r,reset:i,setters:a}=_i(),{query:o,scope:s}=r,{surface:c,onInsert:l,onExecute:u}=e,{open:d,openSearch:f,closeSearch:p}=vi(n,c!==void 0,i,e.onOpenChange),m=hi(d,c,s,e.sessionPrompts,n.loaded.entries),h=x(()=>$r(m,o),[m,o]),g=Math.min(r.selectedIndex,Math.max(0,h.length-1));mi({open:d,matches:h,selected:g,scope:s,screenReader:t,loader:n,close:p,onInsert:l,onExecute:u,...a});let{loading:_,error:v,loaded:y}=n;return{view:{...r,open:d,selectedIndex:g,matches:h,loading:_,error:v,skippedLines:y.skippedLines},openSearch:f,closeSearch:p}}function bi(e){let{historySearch:t,setValue:n,setCursorHint:r,submitPrompt:i,composerActive:a}=e,o=_(e=>{n(e),r(null)},[r,n]),s=_(e=>{n(``),i(e)},[n,i]),{view:c,openSearch:l,closeSearch:u}=yi({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}),y(()=>{c.open&&!a&&u()},[u,a,c.open]),c}function xi(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=>Wr(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 Si(e){let{showPopup:t,isDisabled:n,isQueueCancellationDisabled:r,pendingPrompt:i,searchOpen:a}=e;xi(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=Vr(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 Ci(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 wi(e){return`[deleted: ${e}]`}function Ti({screenReader:e,innerWidth:t,borderColor:n,sessionName:r}){let i=K();if(e)return null;let a=Ci(t,r);return E(H,{color:n,children:[a.left,a.label?T(H,{backgroundColor:n,color:i.text.onAccent,bold:!0,children:a.label}):null,a.right]})}function Ei({screenReader:e,innerWidth:t,borderColor:n}){return e?null:T(H,{color:n,children:`─`.repeat(t)})}function Di({deleted:e}){return e===null?null:T(H,{children:wi(e)})}function Oi(){let{stdout:e}=p(),t=()=>Math.max(40,(e.columns??80)-4),[n,r]=C(t);return y(()=>{let n=()=>r(t());return e.on(`resize`,n),()=>{e.off(`resize`,n)}},[e]),n}function ki(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e.padEnd(t)}function Ai(e){let t=K(),{cmd:n,isSelected:r,showSlash:a,rowWidth:o,nameColWidth:s,rowNumber:c}=e,l=c===void 0?r?`> `:` `:Bn(c),u=r?t.text.accent:void 0,d=!r,f=ki(n.name,s);return T(i,{width:o,children:T(H,{color:u,dimColor:d,wrap:`truncate-end`,children:a?`${l}/${f} ${n.description??``}`:`${l}${f} ${n.description??``}`})})}function ji({commands:e,selectedIndex:t,visible:n,isSubcommandMode:r}){let a=K(),o=Oi(),s=G(),c=Z(`autocomplete-menu`,[[[`previous`,`next`],`Navigate`],[`accept`,`Complete`],[`execute`,`Select`],[`close`,`Close`]]);if(!n||e.length===0)return null;let l=Mi(t,e.length),u=e.slice(l,l+8),d=Math.min(20,Math.max(...u.map(e=>e.name.length)));return E(i,{flexDirection:`column`,...s?{}:{borderStyle:`round`,borderColor:a.border.muted},paddingX:1,children:[u.map((e,n)=>T(Ai,{cmd:e,isSelected:l+n===t,showSlash:!r,rowWidth:o,nameColWidth:d,...s?{rowNumber:l+n}:{}},e.name)),T(Y,{hints:c})]})}function Mi(e,t){if(t<=8||e<8)return 0;let n=t-8;return Math.min(e-8+1,n)}const Ni=/\[Pasted text #(\d+)(?: \+\d+ lines)?\]/g;function Pi(e,t){return e.replace(Ni,(e,n)=>t.get(Number(n))??``)}function Fi({text:e}){let t=G(),n=K(),r=ze(),i=Be(),[a,o]=C(0);return y(()=>{if(!i)return;let e=setInterval(()=>{o(e=>e+1)},400);return()=>clearInterval(e)},[i]),t?T(H,{children:e}):i?T(H,{children:[...e].map((e,t)=>{let n=Math.floor(t/4),i=(a+n)%r.wave.length;return T(H,{color:r.wave[i],children:e},t)})}):T(H,{color:n.text.muted,children:e})}function Ii({onSubmit:e,onCancelQueue:t,isDisabled:n,isQueueCancellationDisabled:r,isAborting:a,pendingPrompt:o,pendingCount:s,commandQueryPort:c,sessionName:l,history:u,onRequestFocusBackgroundList:d,historySearch:f,initialValue:p,consumeInitialValue:h,externalPromptOrigin:g}){let v=K(),[b,w]=C(p??``),[D]=C(g===!0?p??``:``);y(()=>{p!==void 0&&p.length!==0&&h?.()},[p,h]);let[ee,O]=C(null),te=G(),[k,ne]=C(null),[re,ie]=C(Br),[ae,oe]=C([]),A=x(()=>Ur(u??[]),[u]),se=x(()=>ae.reduce((e,t)=>Hr(e,t),A),[A,ae]),j=S(new Map),{columns:ce}=m(),le=ce>0?ce:80,ue=Math.max(1,le-3),M=S(0),de=Z(`chat-input`,[[`submit`,`Submit`]]),{showPopup:N,filteredCommands:P,selectedIndex:fe,setSelectedIndex:pe,isSubcommandMode:F,setShowPopup:me}=si(b,c),he=_((e,t)=>{M.current+=1;let n=M.current;j.current.set(n,e),w(r=>{let i=qr(r,t,n,e);return O(i.cursorHint),i.value})},[]),I=_(()=>{ie(Br())},[]),L=_(e=>{oe(t=>Hr(t,e))},[]),R=_(t=>{L(t),I(),e(t)},[e,L,I]),ge=_(e=>{let t=Gr(b,e);t.type===`insert`&&(w(t.value),t.selectedIndex!==void 0&&pe(t.selectedIndex))},[b,pe]),z=_(e=>{let t=Kr(b,e);if(t.type===`insert`){w(t.value),t.selectedIndex!==void 0&&pe(t.selectedIndex);return}t.type===`submit`&&(w(``),R(t.value))},[b,R,pe]),_e=_(e=>{if(!Jr(e))return;if(N&&P[fe]){z(P[fe]);return}let t=Pi(e.trim(),j.current);w(``),j.current.clear(),M.current=0,R(t)},[N,P,fe,z,R]),ve=bi({historySearch:f,sessionPrompts:se,composerActive:!N&&!n&&!o,setValue:w,setCursorHint:O,submitPrompt:R});Si({value:b,isDisabled:n,searchOpen:ve.open,isQueueCancellationDisabled:r??n,pendingPrompt:o,showPopup:N,setShowPopup:me,filteredCommands:P,selectedIndex:fe,setSelectedIndex:pe,tabCompleteCommand:ge,promptHistory:se,historyState:re,setValue:w,setCursorHint:O,setHistoryState:ie,onRequestFocusBackgroundList:d,onCancelQueue:t});let B=a?v.border.attention:o?v.border.focused:n?v.border.muted:v.border.active,ye=Math.max(1,le-0);return E(i,{flexDirection:`column`,children:[N&&T(ji,{commands:P,selectedIndex:fe,visible:N,isSubcommandMode:F}),T(ai,{view:ve}),T(Di,{deleted:te?k:null}),T(Ti,{screenReader:te,innerWidth:ye,borderColor:B,...l===void 0?{}:{sessionName:l}}),T(i,{paddingLeft:1,children:a?T(H,{color:v.text.warning,children:` Interrupting...`}):o?E(H,{color:v.text.accent,children:[` `,`Queued:`,` `,o.length>50?o.slice(0,47)+`...`:o,` `,typeof s==`number`&&s>1&&E(H,{dimColor:!0,children:[`(+`,s-1,` co-driver queued) `]}),T(H,{dimColor:!0,children:`(Backspace to cancel)`})]}):n?T(Fi,{text:` Waiting for response... (ESC to interrupt)`}):E(i,{children:[T(H,{color:v.text.success,bold:!0,children:`> `}),T(kr,{value:b,onChange:e=>{w(e),I(),O(null)},onDeletedText:ne,onSubmit:_e,onPaste:he,placeholder:`Type a message or /help`,availableWidth:ue,cursorHint:ee,enableVerticalNavigation:!1,keybindingContext:N?`autocomplete-menu`:`chat-input`,focus:!ve.open})]})}),!te&&!n&&!o&&!ve.open&&T(Y,{hints:de}),T(Ei,{screenReader:te,innerWidth:ye,borderColor:B}),D.length>0&&b===D&&T(zr,{value:b})]})}const Li=new Set([`Shell`,`Bash`,`BackgroundProcess`]);function Ri(e){if(!Li.has(e.toolName)||!e.toolResultData)return;let t=zi(e.toolResultData),n=qi(t,`exitCode`),r=Ji(t,`success`),i=Ui(Hi(Bi(e.toolResultData,t))),a=i.slice(0,4).map(V),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:Vi(s,n),previewLines:a,omittedLineCount:o,transcriptHint:o>0?`... +${o} lines (full output in session transcript)`:void 0}}function zi(e){try{return JSON.parse(e)}catch{return e}}function Bi(e,t){if(!Gi(t))return e;let n=Ki(t,`output`);if(n!==void 0)return n;let r=Ki(t,`stdout`),i=Ki(t,`stderr`),a=Ki(t,`error`),o=[];return r&&o.push(r),i&&o.push(Wi(i,`[stderr] `)),!r&&!i&&a&&o.push(a),o.join(`
16
- `)}function Vi(e,t){return t!==void 0&&t!==0?`exit ${t}`:e?`error`:`ok`}function Hi(e){return e?e.replace(/\r\n/g,`
14
+ `),cursor:e.cursor}}}function dr(e,t,n){if(t.upArrow===!0||t.downArrow===!0)return n.enableVerticalNavigation===!1?{state:e,effect:{type:`none`}}:Qn(e,t.upArrow===!0?`up`:`down`,n.availableWidth);if(t.leftArrow===!0)return $n(e,`left`);if(t.rightArrow===!0)return $n(e,`right`);if(t.backspace===!0||t.delete===!0)return gr(e,er(e.value,e.cursor))}function fr(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 pr(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 hr(e,t,n){if(t!==ir&&!t.includes(ir))return{state:{...e,pasteBuffer:e.pasteBuffer+t},effect:{type:`none`}};let r=t.split(ir)[0]??``;return cr({...e,isPasting:!1,pasteBuffer:``},e.pasteBuffer+r,n)}function gr(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 _r(e,t){let n=fr(t);if(n.length===0)return{state:e,effect:{type:`none`}};let r=pr(e.value,e.cursor,n);return{state:{...e,value:r.value,cursor:r.cursor},effect:{type:`change`,value:r.value}}}function vr(){return{timer:null,isSubmitting:!1}}function yr(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 br(e,t=clearTimeout){e.timer!==null&&(t(e.timer),e.timer=null),e.isSubmitting=!1}function xr(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=Xn(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 Sr(e){return!(!e.capability||!e.hasMeasured||e.viewportRows<=0||e.frameHeight<=0||e.frameHeight>=e.viewportRows||e.y<0||e.y>=e.frameHeight)}function Cr(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 wr(e,t){return e===void 0||t===void 0?e===t:e.x===t.x&&e.y===t.y&&e.frameHeight===t.frameHeight}function Tr(e){let{setCursorPosition:t}=u(),n=l(e.boxRef),{rows:r}=m(),[i,a]=C(void 0);y(()=>{let t=e.boxRef.current,n=t===null?void 0:Cr(t);a(e=>wr(e,n)?e:n)});let o=i!==void 0&&e.enabled?xr({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&&Sr({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 Er=g({armEchoRelease(){},write(e){process.stdout.write(e)}});function Dr({port:e,children:t}){return T(Er.Provider,{value:e,children:t})}function Or(){return v(Er)}const kr=g({});function Ar({overrides:e,children:t}){return T(kr.Provider,{value:e??{},children:t})}function jr(){return v(kr)}function Mr({value:e,onChange:t,onSubmit:n,onPaste:r,placeholder:a=``,focus:o=!0,showCursor:s=!0,availableWidth:c,cursorHint:l=null,enableVerticalNavigation:u=!0,onDeletedText:d,keybindingContext:f=`text-input`}){let p=S(ar(e)),[,m]=C(0),h=S(vr());y(()=>()=>br(h.current),[]),p.current=or(p.current,e,l),Pr({stateRef:p,onChange:t,onSubmit:n,onPaste:r,availableWidth:c,focus:o,enableVerticalNavigation:u,...d===void 0?{}:{onDeletedText:d},forceRender:m,deferState:h.current,keybindingContext:f});let g=G(),_=x(()=>K(g.text.muted),[g.text.muted]),v=S(null),b=jr(),{realCursorActive:w}=Tr({boxRef:v,enabled:o&&s&&Pe({override:b.imeCursorPositioning}),value:p.current.value,cursor:p.current.cursor,...c===void 0?{}:{availableWidth:c}});return T(i,{ref:v,children:T(Ee,{children:zr(p.current.value,p.current.cursor,a,s&&o&&!w,_)})})}function Nr(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 Pr(e){let t=Or();f(n=>{t.armEchoRelease(),Lr(e,()=>cr(e.stateRef.current,n,Ir(e)))},{isActive:e.focus}),Z(e.keybindingContext,(n,r,i,a,o)=>{let s=Fr(o,n,r,i,a);s!==void 0&&(Nr(n[0],s)&&t.armEchoRelease(),Lr(e,()=>sr(e.stateRef.current,s.input,s.key,Ir(e))))},{isActive:e.focus,...e.keybindingContext===`autocomplete-menu`?{fallbackContext:`chat-input`}:{}})}function Fr(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 Ir(e){return{availableWidth:e.availableWidth,canPaste:e.onPaste!==void 0,enableVerticalNavigation:e.enableVerticalNavigation}}function Lr(e,t){try{let n=t();e.stateRef.current=n.state,Rr(e,n.effect)}catch{}}function Rr(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&&yr(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 zr(t,n,r,i,a){let o=V(t),s=V(r);if(!i)return o.length>0?o:s?a(s):``;if(o.length===0)return s.length>0?e.inverse(s[0])+a(s.slice(1)):e.inverse(` `);let c=[...o],l=``;for(let t=0;t<c.length;t++){let r=c[t]??``;l+=t===n?e.inverse(r):r}return n>=c.length&&(l+=e.inverse(` `)),l}const Br=`Prompt from an external link`;function Vr(e){if(e.length!==0)return e.length>1e3?`${Br} — ${e.length} characters; scroll and review the full text before sending`:Br}function Hr({value:e}){let t=Vr(e);return t===void 0?null:T(H,{dimColor:!0,children:t})}function Ur(){return{selectedIndex:null,draft:``}}function Wr(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:Ur()}}function Gr(e,t){let n=t.trim();return n.length===0||e[e.length-1]===n?[...e]:[...e,n]}function Kr(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=Gr(t,e.content))}return t}function qr(e,t,n){return t===0?0:n===`previous`?e>0?e-1:t-1:e<t-1?e+1:0}function Jr(e,t){if(ce(e)&&e.slice(1).includes(` `)){let{name:n}=fe(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 Yr(e,t){if(ce(e)&&e.slice(1).includes(` `)){let{name:n}=fe(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 Xr(e,t,n,r){let i=r.split(`
15
+ `).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 Zr(e){return e.trim().length>0}const Qr=[`all`,`session`,`project`];function $r(e){let t=Qr.indexOf(e);return Qr[(t+1)%Qr.length]??`all`}function ei(e,t,n){switch(t){case`all`:return!0;case`session`:return e.sessionId===n.sessionId;case`project`:return e.project===n.project}}function ti(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 ni(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 ri(e,t){let n=[],r=0;for(let[i,a]of t)i>r&&n.push({text:e.slice(r,i),matched:!1}),n.push({text:e.slice(i,a),matched:!0}),r=a;return r<e.length&&n.push({text:e.slice(r),matched:!1}),n}function ii(e,t){return t<=8||e<8?0:Math.min(e-8+1,t-8)}function ai(e){return`${e} unreadable ${e===1?`line`:`lines`} skipped`}function oi(e){let t=G(),{match:n,selected:r,rowNumber:i,color:a}=e,o=i===void 0?r?`> `:` `:Un(i),s=ri(n.entry.text.replace(/\r\n|[\r\n]/gu,e=>e.length===2?` ↵`:`↵`),n.ranges);return E(H,{color:r?t.text.accent:void 0,dimColor:!r,wrap:`truncate-end`,children:[o,s.map((e,t)=>e.matched?T(H,{bold:!0,inverse:a,children:a?e.text:`[${e.text}]`},t):T(H,{children:e.text},t))]})}function si({view:e}){let t=G();if(e.error!==void 0)return E(H,{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(ai(e.skippedLines)),T(H,{dimColor:!0,children:n.join(` · `)})}function ci({view:e}){let t=G(),n=W(),r=Ne(),a=X(`history-search`,[[[`previous`,`next`],`Navigate`],[`cycle-scope`,`Scope`],[`insert`,`Insert`],[`execute`,`Run`],[`cancel`,`Close`]]);if(!e.open)return null;let o=ii(e.selectedIndex,e.matches.length),s=e.matches.slice(o,o+8);return E(i,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.muted},paddingX:1,children:[E(H,{children:[T(H,{color:t.text.accent,children:`(reverse-i-search)`}),` scope: `,e.scope,` · query:`,` `,e.query]}),s.map((t,i)=>T(oi,{match:t,selected:o+i===e.selectedIndex,rowNumber:n?o+i:void 0,color:r},`${t.entry.at}:${o+i}`)),T(si,{view:e}),T(J,{hints:a})]})}function li(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 ui(e,t){let[n,r]=C(0),[i,a]=C(!1),o=h.useRef(e);o.current!==e&&(o.current=e,i&&a(!1));let s=li(e),c=s.isSlash&&s.parentCommand.length>0,l=h.useRef(s.parentCommand);y(()=>{l.current!==s.parentCommand&&(l.current=s.parentCommand,r(0))},[s.parentCommand]);let u=x(()=>{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 fi(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 pi(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 hi(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 gi(e,t){let[n,r]=C(di),[i,a]=C(!1),[o,s]=C(void 0),c=S(void 0),l=S(di),u=_(()=>r(l.current),[]),d=_(()=>{c.current?.abort(),c.current=void 0,a(!1)},[]),f=_(()=>{if(d(),l.current=di,r(di),s(void 0),e===void 0)return;let n=new AbortController;c.current=n,a(!0),hi({source:e.source,signal:n.signal,pending:l,publishEachBlock:!t,publish:u,setError:s,setLoading:a})},[u,t,d,e]);return y(()=>d,[d]),{loaded:n,loading:i,error:o,start:f,stop:d,publish:u}}function _i(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)};Z(`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($r(e.scope)),e.setSelectedIndex(0)):!s&&(o.backspace||o.delete)?t(e=>e.slice(0,-1)):!s&&fi(a,o)&&t(e=>e+a)},{isActive:e.open})}function vi(e,t,n,r,i){let a=t?.sessionId,o=t?.project;return x(()=>{if(!e||a===void 0||o===void 0)return[];let t={sessionId:a,project:o};return ti(n===`session`?pi(r,t):i.filter(e=>ei(e,n,t)))},[i,e,o,n,a,r])}const yi={query:``,scope:`all`,selectedIndex:0};function bi(){let[e,t]=C(yi);return{state:e,reset:_(()=>t(yi),[]),setters:x(()=>({setScope:e=>t(t=>({...t,scope:e})),setSelectedIndex:e=>t(t=>({...t,selectedIndex:e})),setQuery:e=>t(t=>({...t,query:e(t.query)}))}),[])}}function xi(e,t,n,r){let[i,a]=C(!1);return{open:i,openSearch:_(()=>{!t||i||(n(),a(!0),r?.(!0),e.start())},[t,e,r,i,n]),closeSearch:_(()=>{e.stop(),a(!1),r?.(!1)},[e,r])}}function Si(e){let t=W(),n=gi(e.surface,t),{state:r,reset:i,setters:a}=bi(),{query:o,scope:s}=r,{surface:c,onInsert:l,onExecute:u}=e,{open:d,openSearch:f,closeSearch:p}=xi(n,c!==void 0,i,e.onOpenChange),m=vi(d,c,s,e.sessionPrompts,n.loaded.entries),h=x(()=>ni(m,o),[m,o]),g=Math.min(r.selectedIndex,Math.max(0,h.length-1));_i({open:d,matches:h,selected:g,scope:s,screenReader:t,loader:n,close:p,onInsert:l,onExecute:u,...a});let{loading:_,error:v,loaded:y}=n;return{view:{...r,open:d,selectedIndex:g,matches:h,loading:_,error:v,skippedLines:y.skippedLines},openSearch:f,closeSearch:p}}function Ci(e){let{historySearch:t,setValue:n,setCursorHint:r,submitPrompt:i,composerActive:a}=e,o=_(e=>{n(e),r(null)},[r,n]),s=_(e=>{n(``),i(e)},[n,i]),{view:c,openSearch:l,closeSearch:u}=Si({surface:t,sessionPrompts:e.sessionPrompts,onInsert:o,onExecute:s,onOpenChange:t?.onOpenChange});return Z(`chat-input`,e=>{e.includes(`history-search`)&&l()},{isActive:a&&!c.open&&t!==void 0}),y(()=>{c.open&&!a&&u()},[u,a,c.open]),c}function wi(e){let{showPopup:t,isDisabled:n,filteredCommands:r,selectedIndex:i}=e;Z(`autocomplete-menu`,n=>{if(t){for(let t of n)if(t===`previous`||t===`next`)e.setSelectedIndex(e=>qr(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 Ti(e){let{showPopup:t,isDisabled:n,isQueueCancellationDisabled:r,pendingPrompt:i,searchOpen:a}=e;wi(e),Z(`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=Wr(e.value,e.promptHistory,e.historyState,r);e.setValue(i.value),e.setCursorHint(i.cursorHint),e.setHistoryState(i.state)},{isActive:!t&&!n&&!i&&!a}),Z(`queued-prompt`,t=>{t.includes(`cancel`)&&i&&e.onCancelQueue?.()},{isActive:!!i&&!r})}function Ei(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 Di(e){return`[deleted: ${e}]`}function Oi({screenReader:e,innerWidth:t,borderColor:n,sessionName:r}){let i=G();if(e)return null;let a=Ei(t,r);return E(H,{color:n,children:[a.left,a.label?T(H,{backgroundColor:n,color:i.text.onAccent,bold:!0,children:a.label}):null,a.right]})}function ki({screenReader:e,innerWidth:t,borderColor:n}){return e?null:T(H,{color:n,children:`─`.repeat(t)})}function Ai({deleted:e}){return e===null?null:T(H,{children:Di(e)})}function ji(){let{stdout:e}=p(),t=()=>Math.max(40,(e.columns??80)-4),[n,r]=C(t);return y(()=>{let n=()=>r(t());return e.on(`resize`,n),()=>{e.off(`resize`,n)}},[e]),n}function Mi(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e.padEnd(t)}function Ni(e){let t=G(),{cmd:n,isSelected:r,showSlash:a,rowWidth:o,nameColWidth:s,rowNumber:c}=e,l=c===void 0?r?`> `:` `:Un(c),u=r?t.text.accent:void 0,d=!r,f=Mi(n.name,s);return T(i,{width:o,children:T(H,{color:u,dimColor:d,wrap:`truncate-end`,children:a?`${l}/${f} ${n.description??``}`:`${l}${f} ${n.description??``}`})})}function Pi({commands:e,selectedIndex:t,visible:n,isSubcommandMode:r}){let a=G(),o=ji(),s=W(),c=X(`autocomplete-menu`,[[[`previous`,`next`],`Navigate`],[`accept`,`Complete`],[`execute`,`Select`],[`close`,`Close`]]);if(!n||e.length===0)return null;let l=Fi(t,e.length),u=e.slice(l,l+8),d=Math.min(20,Math.max(...u.map(e=>e.name.length)));return E(i,{flexDirection:`column`,...s?{}:{borderStyle:`round`,borderColor:a.border.muted},paddingX:1,children:[u.map((e,n)=>T(Ni,{cmd:e,isSelected:l+n===t,showSlash:!r,rowWidth:o,nameColWidth:d,...s?{rowNumber:l+n}:{}},e.name)),T(J,{hints:c})]})}function Fi(e,t){if(t<=8||e<8)return 0;let n=t-8;return Math.min(e-8+1,n)}const Ii=/\[Pasted text #(\d+)(?: \+\d+ lines)?\]/g;function Li(e,t){return e.replace(Ii,(e,n)=>t.get(Number(n))??``)}function Ri({text:e}){let t=W(),n=G(),r=He(),i=Ue(),[a,o]=C(0);return y(()=>{if(!i)return;let e=setInterval(()=>{o(e=>e+1)},400);return()=>clearInterval(e)},[i]),t?T(H,{children:e}):i?T(H,{children:[...e].map((e,t)=>{let n=Math.floor(t/4),i=(a+n)%r.wave.length;return T(H,{color:r.wave[i],children:e},t)})}):T(H,{color:n.text.muted,children:e})}function zi({onSubmit:e,onCancelQueue:t,isDisabled:n,isQueueCancellationDisabled:r,isAborting:a,pendingPrompt:o,pendingCount:s,commandQueryPort:c,sessionName:l,history:u,onRequestFocusBackgroundList:d,historySearch:f,initialValue:p,consumeInitialValue:h,externalPromptOrigin:g}){let v=G(),[b,w]=C(p??``),[D]=C(g===!0?p??``:``);y(()=>{p!==void 0&&p.length!==0&&h?.()},[p,h]);let[ee,te]=C(null),ne=W(),[re,O]=C(null),[ie,ae]=C(Ur),[oe,se]=C([]),ce=x(()=>Kr(u??[]),[u]),le=x(()=>oe.reduce((e,t)=>Gr(e,t),ce),[ce,oe]),ue=S(new Map),{columns:k}=m(),de=k>0?k:80,A=Math.max(1,de-3),fe=S(0),j=X(`chat-input`,[[`submit`,`Submit`]]),{showPopup:M,filteredCommands:N,selectedIndex:P,setSelectedIndex:pe,isSubcommandMode:me,setShowPopup:F}=ui(b,c),he=_((e,t)=>{fe.current+=1;let n=fe.current;ue.current.set(n,e),w(r=>{let i=Xr(r,t,n,e);return te(i.cursorHint),i.value})},[]),ge=_(()=>{ae(Ur())},[]),_e=_(e=>{se(t=>Gr(t,e))},[]),I=_(t=>{_e(t),ge(),e(t)},[e,_e,ge]),ve=_(e=>{let t=Jr(b,e);t.type===`insert`&&(w(t.value),t.selectedIndex!==void 0&&pe(t.selectedIndex))},[b,pe]),ye=_(e=>{let t=Yr(b,e);if(t.type===`insert`){w(t.value),t.selectedIndex!==void 0&&pe(t.selectedIndex);return}t.type===`submit`&&(w(``),I(t.value))},[b,I,pe]),be=_(e=>{if(!Zr(e))return;if(M&&N[P]){ye(N[P]);return}let t=Li(e.trim(),ue.current);w(``),ue.current.clear(),fe.current=0,I(t)},[M,N,P,ye,I]),L=Ci({historySearch:f,sessionPrompts:le,composerActive:!M&&!n&&!o,setValue:w,setCursorHint:te,submitPrompt:I});Ti({value:b,isDisabled:n,searchOpen:L.open,isQueueCancellationDisabled:r??n,pendingPrompt:o,showPopup:M,setShowPopup:F,filteredCommands:N,selectedIndex:P,setSelectedIndex:pe,tabCompleteCommand:ve,promptHistory:le,historyState:ie,setValue:w,setCursorHint:te,setHistoryState:ae,onRequestFocusBackgroundList:d,onCancelQueue:t});let R=a?v.border.attention:o?v.border.focused:n?v.border.muted:v.border.active,xe=Math.max(1,de-0);return E(i,{flexDirection:`column`,children:[M&&T(Pi,{commands:N,selectedIndex:P,visible:M,isSubcommandMode:me}),T(ci,{view:L}),T(Ai,{deleted:ne?re:null}),T(Oi,{screenReader:ne,innerWidth:xe,borderColor:R,...l===void 0?{}:{sessionName:l}}),T(i,{paddingLeft:1,children:a?T(H,{color:v.text.warning,children:` Interrupting...`}):o?E(H,{color:v.text.accent,children:[` `,`Queued:`,` `,o.length>50?o.slice(0,47)+`...`:o,` `,typeof s==`number`&&s>1&&E(H,{dimColor:!0,children:[`(+`,s-1,` co-driver queued) `]}),T(H,{dimColor:!0,children:`(Backspace to cancel)`})]}):n?T(Ri,{text:` Waiting for response... (ESC to interrupt)`}):E(i,{children:[T(H,{color:v.text.success,bold:!0,children:`> `}),T(Mr,{value:b,onChange:e=>{w(e),ge(),te(null)},onDeletedText:O,onSubmit:be,onPaste:he,placeholder:`Type a message or /help`,availableWidth:A,cursorHint:ee,enableVerticalNavigation:!1,keybindingContext:M?`autocomplete-menu`:`chat-input`,focus:!L.open})]})}),!ne&&!n&&!o&&!L.open&&T(J,{hints:j}),T(ki,{screenReader:ne,innerWidth:xe,borderColor:R}),D.length>0&&b===D&&T(Hr,{value:b})]})}const Bi=new Set([`Shell`,`Bash`,`BackgroundProcess`]);function Vi(e){if(!Bi.has(e.toolName)||!e.toolResultData)return;let t=Hi(e.toolResultData),n=Xi(t,`exitCode`),r=Zi(t,`success`),i=Ki(Gi(Ui(e.toolResultData,t))),a=i.slice(0,4).map(V),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:Wi(s,n),previewLines:a,omittedLineCount:o,transcriptHint:o>0?`... +${o} lines (full output in session transcript)`:void 0}}function Hi(e){try{return JSON.parse(e)}catch{return e}}function Ui(e,t){if(!Ji(t))return e;let n=Yi(t,`output`);if(n!==void 0)return n;let r=Yi(t,`stdout`),i=Yi(t,`stderr`),a=Yi(t,`error`),o=[];return r&&o.push(r),i&&o.push(qi(i,`[stderr] `)),!r&&!i&&a&&o.push(a),o.join(`
16
+ `)}function Wi(e,t){return t!==void 0&&t!==0?`exit ${t}`:e?`error`:`ok`}function Gi(e){return e?e.replace(/\r\n/g,`
17
17
  `).split(`
18
- `):[]}function Ui(e){let t=e.length;for(;t>0&&e[t-1].trim().length===0;)--t;return e.slice(0,t)}function Wi(e,t){return Hi(e).map(e=>`${t}${e}`).join(`
19
- `)}function Gi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Ki(e,t){if(!Gi(e))return;let n=e[t];return typeof n==`string`?n:void 0}function qi(e,t){if(!Gi(e))return;let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ji(e,t){if(!Gi(e))return;let n=e[t];return typeof n==`boolean`?n:void 0}const Yi=` `,Xi=I;function Zi(e){return e===void 0?Ae():e}function Qi(e){return e?.trim().toLowerCase()===`diff`}function $i(e,t,n,r){let i=`${Yi}${e}`.padEnd(t);return n?e.startsWith(`+`)?r.added(i):e.startsWith(`-`)?r.removed(i):i.trimEnd():i.trimEnd()}function ea(e,t,n,r){if(e.startsWith(`+`)||e.startsWith(`-`))return $i(e,n,t,r);let i=`${Yi}${e}`;return t?e.startsWith(`@@`)?r.hunk(i):e.startsWith(`diff `)||e.startsWith(`index `)?r.meta(i):i:i}function ta(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 na(e,t,n,r){let i=e.split(`
20
- `),a=ta(i,n);return`${i.map(e=>ea(e,t,a,r)).join(`
21
- `)}\n\n`}function ra(e){return e.split(``).join(``).split(`\0`).slice(0,-1)}function ia(e){e.tablecell=e=>`${e}`,e.tablerow=e=>`${e}`,e.table=(e,t)=>{let n=ra(e),r=t.split(``).filter(e=>e.length>0).map(e=>ra(`${e}`));return n.length===0||r.length===0?``:`${r.map(e=>n.map((t,n)=>`${t}: ${e[n]??``}`).join(`
18
+ `):[]}function Ki(e){let t=e.length;for(;t>0&&e[t-1].trim().length===0;)--t;return e.slice(0,t)}function qi(e,t){return Gi(e).map(e=>`${t}${e}`).join(`
19
+ `)}function Ji(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Yi(e,t){if(!Ji(e))return;let n=e[t];return typeof n==`string`?n:void 0}function Xi(e,t){if(!Ji(e))return;let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Zi(e,t){if(!Ji(e))return;let n=e[t];return typeof n==`boolean`?n:void 0}const Qi=` `,$i=_e;function ea(e){return e===void 0?Ne():e}function ta(e){return e?.trim().toLowerCase()===`diff`}function na(e,t,n,r){let i=`${Qi}${e}`.padEnd(t);return n?e.startsWith(`+`)?r.added(i):e.startsWith(`-`)?r.removed(i):i.trimEnd():i.trimEnd()}function ra(e,t,n,r){if(e.startsWith(`+`)||e.startsWith(`-`))return na(e,n,t,r);let i=`${Qi}${e}`;return t?e.startsWith(`@@`)?r.hunk(i):e.startsWith(`diff `)||e.startsWith(`index `)?r.meta(i):i:i}function ia(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 aa(e,t,n,r){let i=e.split(`
20
+ `),a=ia(i,n);return`${i.map(e=>ra(e,t,a,r)).join(`
21
+ `)}\n\n`}function oa(e){return e.split(``).join(``).split(`\0`).slice(0,-1)}function sa(e){e.tablecell=e=>`${e}`,e.tablerow=e=>`${e}`,e.table=(e,t)=>{let n=oa(e),r=t.split(``).filter(e=>e.length>0).map(e=>oa(`${e}`));return n.length===0||r.length===0?``:`${r.map(e=>n.map((t,n)=>`${t}: ${e[n]??``}`).join(`
22
22
  `)).join(`
23
23
 
24
- `)}\n\n`}}function aa(e,t,n,r,i){let a=new Xi(tt(r.markdown),{ignoreIllegals:!0,theme:nt(r.syntax)}),o=a.code.bind(a),s=rt(r);return a.code=(n,r,a)=>Qi(r)?na(n,e,t,s):i?o(n,r,a):`${n.split(`
25
- `).map(e=>`${Yi}${e}`).join(`
26
- `)}\n\n`,n&&ia(a),a}function oa(e,t={}){let n=V(e),r=he.parse(n,{renderer:aa(Zi(t.color),t.codeBlockWidth,t.screenReader===!0,De(t.theme),t.syntaxHighlighting!==!1)});return typeof r==`string`?r.trimEnd():n}function sa(){let e=Re(),t=Ve(),n=G();return(r,i={})=>oa(r,{...i,theme:e,syntaxHighlighting:t,screenReader:n})}const ca=/_[0-9a-f]{8}$/;function la(e,t=te){if(!e.startsWith(t))return V(e);let n=e.slice(t.length).replace(ca,``);return V(n.length>0?n:e)}function ua(e){return e===void 0?``:V(e)}const da=g(`Assistant`),fa=g(void 0);function pa({name:e,modelCommandToolPrefix:t,children:n}){return T(da.Provider,{value:e?.trim()||`Assistant`,children:T(fa.Provider,{value:t,children:n})})}function ma(){return v(da)}function ha(){return v(fa)}const ga={user:`you:`,assistant:`assistant:`,thinking:`thinking:`,tool:`tool:`,toolError:`tool error:`,error:`error:`,warning:`warning:`,permissionRequired:`permission required:`,cost:`cost:`};function _a(e){switch(e){case`user`:return ga.user;case`assistant`:return ga.assistant;case`tool`:return ga.tool;case`system`:return ga.warning}}function va(e){return e===L?`You`:e}function ya({role:e,driverId:t}){let n=K(),r=G(),i=ma();if(r)return E(H,{children:[e===`user`&&t!==void 0&&t!==L?`${t}:`:_a(e),` `]});switch(e){case`user`:return E(H,{color:n.text.success,bold:!0,children:[t===void 0?`You`:va(t),`:`,` `]});case`assistant`:return E(H,{color:n.text.accent,bold:!0,children:[i,`:`,` `]});case`system`:return E(H,{color:n.text.warning,bold:!0,children:[`System:`,` `]});case`tool`:return E(H,{color:n.text.emphasis,bold:!0,children:[`Tool:`,` `]})}}function ba(e,t){if(t)return`error`;let n=e.result===`success`||e.result===`error`||e.result===`denied`?e.result:void 0;return Ot({toolName:e.toolName,firstArg:e.firstArg??``,isRunning:e.isRunning??!1,result:n})}function xa(e,t,n){let r=ua(e.firstArg);return`${Et[t]} ${la(e.toolName,n)}${r?`(${r})`:``}`}function Sa({tool:e}){let t=K(),n=Ri(e);if(!n||n.statusLabel===`ok`&&n.previewLines.length===0&&!n.transcriptHint)return null;let r=n.status===`error`?Dt(t,`error`):t.text.emphasis;return E(i,{flexDirection:`column`,marginLeft:4,children:[n.statusLabel!==`ok`&&T(H,{color:r,dimColor:!0,children:n.statusLabel}),n.previewLines.map((e,t)=>T(H,{color:r,dimColor:!0,children:e},`${e}-${t}`)),n.transcriptHint&&T(H,{dimColor:!0,children:n.transcriptHint})]})}function Ca(e){let t=e.lines.length>12?Ta(e.lines):e.lines,n=Math.max(...t.map(e=>e.lineNumber),0).toString().length,r=t.map(e=>wa(e,n)),i=e.lines.length>12;return{file:e.file,markdown:["```diff",...r,"```"].join(`
27
- `),truncated:i,remainingLineCount:i?e.lines.length-t.length:0}}function wa(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 Ta(e){let t=Ea(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 Ea(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 Da({file:e,lines:t}){let n=K(),r=sa(),a=Ca({file:e,lines:t}),o=G()?``:`│ `;return E(i,{flexDirection:`column`,marginLeft:4,children:[a.file&&E(H,{color:n.text.emphasis,dimColor:!0,children:[o,V(a.file)]}),T(U,{children:r(a.markdown)}),a.truncated&&E(H,{color:n.text.emphasis,dimColor:!0,children:[o,`... and `,a.remainingLineCount,` more lines`]})]})}function Oa({entry:e}){let t=K(),n=e.data;if(!n)return T(w,{});let r=n.promptTokens===void 0?`?`:ka(n.promptTokens),a=n.completionTokens===void 0?`?`:ka(n.completionTokens),o=ka(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)}% (${P(n.contextUsedTokens)}/${P(n.contextMaxTokens)})`,u=n.costStatus===`unknown`?`cost unknown`:`cost ${n.costStatus}`;return T(i,{flexDirection:`column`,marginBottom:1,children:E(i,{children:[E(H,{color:t.text.emphasis,bold:!0,children:[c?`Usage (${c}):`:`Usage:`,` `]}),E(H,{dimColor:!0,children:[n.kind,` `,o,` tokens (in `,r,` / out `,a,`)`,l,` · `,u]})]})})}function ka(e){return e<1e3?e.toLocaleString():P(e)}function Aa({kind:e,text:t,color:n}){return G()?E(H,{children:[ga[e],` `]}):T(H,{color:n,bold:!0,children:t})}function ja({message:e}){let t=K(),n=ha();if(!pe(e))return T(w,{});let r=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 E(i,{flexDirection:`column`,marginBottom:1,children:[E(i,{children:[T(Aa,{kind:`tool`,text:`Tool: `,color:t.text.emphasis}),r&&E(H,{color:t.text.emphasis,dimColor:!0,children:[`[`,la(r,n),`]`]})]}),T(H,{children:` `}),o.map((e,n)=>E(i,{flexDirection:`column`,children:[E(H,{color:t.text.success,children:[` `,`✓`,` `,V(e.line)]}),e.diffLines&&e.diffLines.length>0&&T(Da,{file:e.diffFile,lines:e.diffLines})]},n))]});let s=a.split(`
28
- `).filter(e=>e.trim());return E(i,{flexDirection:`column`,marginBottom:1,children:[E(i,{children:[T(Aa,{kind:`tool`,text:`Tool: `,color:t.text.emphasis}),r&&E(H,{color:t.text.emphasis,dimColor:!0,children:[`[`,V(r),`]`]})]}),T(H,{children:` `}),s.map((e,n)=>E(H,{color:t.text.success,children:[` `,`✓`,` `,V(e)]},n))]})}function Ma({message:e}){let t=K(),n=V((e.content??``).replace(/^Error:\s*/,``));return E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(Aa,{kind:`error`,text:`✖ Error: `,color:t.text.error})}),E(i,{marginLeft:2,flexDirection:`column`,children:[T(H,{color:t.text.error,wrap:`wrap`,children:n}),T(H,{dimColor:!0,wrap:`wrap`,children:`The session is still alive — type your next prompt when ready.`})]})]})}const Na=h.memo(function({message:e}){let t=sa();if(pe(e))return T(ja,{message:e});if(e.role===`system`&&e.metadata?.kind===`error`)return T(Ma,{message:e});let n=e.content??``,r=e.state===`interrupted`;return E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(ya,{role:e.role,...typeof e.metadata?.driverId==`string`?{driverId:e.metadata.driverId}:{}})}),T(H,{children:` `}),T(i,{marginLeft:2,children:fe(e)?T(U,{wrap:`wrap`,children:t(n+(r?`
24
+ `)}\n\n`}}function ca(e,t,n,r,i){let a=new $i(it(r.markdown),{ignoreIllegals:!0,theme:at(r.syntax)}),o=a.code.bind(a),s=ot(r);return a.code=(n,r,a)=>ta(r)?aa(n,e,t,s):i?o(n,r,a):`${n.split(`
25
+ `).map(e=>`${Qi}${e}`).join(`
26
+ `)}\n\n`,n&&sa(a),a}function la(e,t={}){let n=V(e),r=ge.parse(n,{renderer:ca(ea(t.color),t.codeBlockWidth,t.screenReader===!0,je(t.theme),t.syntaxHighlighting!==!1)});return typeof r==`string`?r.trimEnd():n}function ua(){let e=Ve(),t=We(),n=W();return(r,i={})=>la(r,{...i,theme:e,syntaxHighlighting:t,screenReader:n})}const da=/_[0-9a-f]{8}$/;function fa(e,t=ne){if(!e.startsWith(t))return V(e);let n=e.slice(t.length).replace(da,``);return V(n.length>0?n:e)}function pa(e){return e===void 0?``:V(e)}const ma=g(`Assistant`),ha=g(void 0);function ga({name:e,modelCommandToolPrefix:t,children:n}){return T(ma.Provider,{value:e?.trim()||`Assistant`,children:T(ha.Provider,{value:t,children:n})})}function _a(){return v(ma)}function va(){return v(ha)}const ya={user:`you:`,assistant:`assistant:`,thinking:`thinking:`,tool:`tool:`,toolError:`tool error:`,error:`error:`,warning:`warning:`,permissionRequired:`permission required:`,cost:`cost:`};function ba(e){switch(e){case`user`:return ya.user;case`assistant`:return ya.assistant;case`tool`:return ya.tool;case`system`:return ya.warning}}function xa(e){return e===I?`You`:e}function Sa({role:e,driverId:t}){let n=G(),r=W(),i=_a();if(r)return E(H,{children:[e===`user`&&t!==void 0&&t!==I?`${t}:`:ba(e),` `]});switch(e){case`user`:return E(H,{color:n.text.success,bold:!0,children:[t===void 0?`You`:xa(t),`:`,` `]});case`assistant`:return E(H,{color:n.text.accent,bold:!0,children:[i,`:`,` `]});case`system`:return E(H,{color:n.text.warning,bold:!0,children:[`System:`,` `]});case`tool`:return E(H,{color:n.text.emphasis,bold:!0,children:[`Tool:`,` `]})}}function Ca(e,t){if(t)return`error`;let n=e.result===`success`||e.result===`error`||e.result===`denied`?e.result:void 0;return jt({toolName:e.toolName,firstArg:e.firstArg??``,isRunning:e.isRunning??!1,result:n})}function wa(e,t,n){let r=pa(e.firstArg);return`${kt[t]} ${fa(e.toolName,n)}${r?`(${r})`:``}`}function Ta({tool:e}){let t=G(),n=Vi(e);if(!n||n.statusLabel===`ok`&&n.previewLines.length===0&&!n.transcriptHint)return null;let r=n.status===`error`?At(t,`error`):t.text.emphasis;return E(i,{flexDirection:`column`,marginLeft:4,children:[n.statusLabel!==`ok`&&T(H,{color:r,dimColor:!0,children:n.statusLabel}),n.previewLines.map((e,t)=>T(H,{color:r,dimColor:!0,children:e},`${e}-${t}`)),n.transcriptHint&&T(H,{dimColor:!0,children:n.transcriptHint})]})}function Ea(e){let t=e.lines.length>12?Oa(e.lines):e.lines,n=Math.max(...t.map(e=>e.lineNumber),0).toString().length,r=t.map(e=>Da(e,n)),i=e.lines.length>12;return{file:e.file,markdown:["```diff",...r,"```"].join(`
27
+ `),truncated:i,remainingLineCount:i?e.lines.length-t.length:0}}function Da(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 Oa(e){let t=ka(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 ka(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 Aa({file:e,lines:t}){let n=G(),r=ua(),a=Ea({file:e,lines:t}),o=W()?``:`│ `;return E(i,{flexDirection:`column`,marginLeft:4,children:[a.file&&E(H,{color:n.text.emphasis,dimColor:!0,children:[o,V(a.file)]}),T(Ee,{children:r(a.markdown)}),a.truncated&&E(H,{color:n.text.emphasis,dimColor:!0,children:[o,`... and `,a.remainingLineCount,` more lines`]})]})}function ja({entry:e}){let t=G(),n=e.data;if(!n)return T(w,{});let r=n.promptTokens===void 0?`?`:Ma(n.promptTokens),a=n.completionTokens===void 0?`?`:Ma(n.completionTokens),o=Ma(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)}% (${P(n.contextUsedTokens)}/${P(n.contextMaxTokens)})`,u=n.costStatus===`unknown`?`cost unknown`:`cost ${n.costStatus}`;return T(i,{flexDirection:`column`,marginBottom:1,children:E(i,{children:[E(H,{color:t.text.emphasis,bold:!0,children:[c?`Usage (${c}):`:`Usage:`,` `]}),E(H,{dimColor:!0,children:[n.kind,` `,o,` tokens (in `,r,` / out `,a,`)`,l,` · `,u]})]})})}function Ma(e){return e<1e3?e.toLocaleString():P(e)}function Na({kind:e,text:t,color:n}){return W()?E(H,{children:[ya[e],` `]}):T(H,{color:n,bold:!0,children:t})}function Pa({message:e}){let t=G(),n=va();if(!me(e))return T(w,{});let r=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 E(i,{flexDirection:`column`,marginBottom:1,children:[E(i,{children:[T(Na,{kind:`tool`,text:`Tool: `,color:t.text.emphasis}),r&&E(H,{color:t.text.emphasis,dimColor:!0,children:[`[`,fa(r,n),`]`]})]}),T(H,{children:` `}),o.map((e,n)=>E(i,{flexDirection:`column`,children:[E(H,{color:t.text.success,children:[` `,`✓`,` `,V(e.line)]}),e.diffLines&&e.diffLines.length>0&&T(Aa,{file:e.diffFile,lines:e.diffLines})]},n))]});let s=a.split(`
28
+ `).filter(e=>e.trim());return E(i,{flexDirection:`column`,marginBottom:1,children:[E(i,{children:[T(Na,{kind:`tool`,text:`Tool: `,color:t.text.emphasis}),r&&E(H,{color:t.text.emphasis,dimColor:!0,children:[`[`,V(r),`]`]})]}),T(H,{children:` `}),s.map((e,n)=>E(H,{color:t.text.success,children:[` `,`✓`,` `,V(e)]},n))]})}function Fa({message:e}){let t=G(),n=V((e.content??``).replace(/^Error:\s*/,``));return E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(Na,{kind:`error`,text:`✖ Error: `,color:t.text.error})}),E(i,{marginLeft:2,flexDirection:`column`,children:[T(H,{color:t.text.error,wrap:`wrap`,children:n}),T(H,{dimColor:!0,wrap:`wrap`,children:`The session is still alive — type your next prompt when ready.`})]})]})}const Ia=h.memo(function({message:e}){let t=ua();if(me(e))return T(Pa,{message:e});if(e.role===`system`&&e.metadata?.kind===`error`)return T(Fa,{message:e});let n=e.content??``,r=e.state===`interrupted`;return E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(Sa,{role:e.role,...typeof e.metadata?.driverId==`string`?{driverId:e.metadata.driverId}:{}})}),T(H,{children:` `}),T(i,{marginLeft:2,children:pe(e)?T(Ee,{wrap:`wrap`,children:t(n+(r?`
29
29
 
30
- _(interrupted)_`:``))}):T(H,{wrap:`wrap`,children:n})})]})});function Pa({entry:e}){let t=K(),n=ha(),r=e.data,a=r?.tools,o=r?.summary?.split(`
31
- `)??[];return a&&a.length>0?E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(Aa,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),T(H,{children:` `}),a.map((e,r)=>{let a=ba(e,Ri(e)?.status===`error`);return E(i,{flexDirection:`column`,children:[E(H,{color:Dt(t,a),children:[` `,xa(e,a,n)]}),T(Sa,{tool:e}),e.diffLines&&e.diffLines.length>0&&T(Da,{file:e.diffFile,lines:e.diffLines})]},r)})]}):E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(Aa,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),T(H,{children:` `}),o.map((e,n)=>E(H,{color:t.text.success,children:[` `,V(e)]},n))]})}function Fa({entry:e}){let t=K(),n=e.data,r=typeof n?.message==`string`?n.message:typeof n?.content==`string`?n.content:void 0;if(r===void 0)return T(w,{});let a=V(r);return E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(Aa,{kind:`warning`,text:`System: `,color:t.text.warning})}),T(H,{children:` `}),T(i,{marginLeft:2,children:T(H,{wrap:`wrap`,children:a})})]})}function Ia({entry:e}){if(e.category===`chat`){let t=e.data;return T(Na,{message:t})}return e.type===`tool-summary`?T(Pa,{entry:e}):e.type===`usage-summary`?T(Oa,{entry:e}):e.type===`tool-start`||e.type===`tool-end`?T(w,{}):T(Fa,{entry:e})}const La=[{keys:`↑↓`,label:`Navigate`},{keys:`Enter`,label:`Select`},{keys:`Esc`,label:`Cancel`}];function Ra({items:e,renderItem:t,onSelect:n,onCancel:r,maxVisible:a=3,footerHints:o=La,initialIndex:s=0}){let[c,l]=C(()=>{let t=s>=0&&s<e.length?s:0;return{...Qt(t),scrollOffset:Math.max(0,t-a+1)}}),u=S(c),d=_(t=>{let i=tn(u.current,t,{itemCount:e.length,maxVisible:a});if(u.current=i.state,l(i.state),i.effect.type===`cancel`)r();else if(i.effect.type===`select`){let t=e[i.effect.index];t!==void 0&&n(t)}},[e,a,r,n]),f=G(),p=un({enabled:f&&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(d),{isActive:!f});let m=Z(`list-picker`,[[[`previous`,`next`],`Navigate`],[`select`,`Select`],[`cancel`,`Cancel`]]);if(e.length===0)return T(i,{});if(f){let n=zn(e.length,!0);return E(i,{flexDirection:`column`,children:[e.map((e,n)=>E(i,{children:[T(H,{children:Bn(n)}),t(e,!1)]},n)),E(H,{children:[n,p.buffer.length>0?` ${p.buffer}`:``]}),p.invalid&&T(H,{children:n})]})}let h=nn(c,{itemCount:e.length,maxVisible:a});h!==c&&(u.current=h);let{selectedIndex:g,scrollOffset:v}=h,y=e.slice(v,v+a),b=v+a<e.length;return E(i,{flexDirection:`column`,children:[v>0&&E(H,{dimColor:!0,children:[` ↑ `,v,` more above`]}),y.map((e,n)=>T(i,{marginBottom:1,children:t(e,v+n===g)},v+n)),b&&E(H,{dimColor:!0,children:[` ↓ `,e.length-v-a,` more below`]}),T(Y,{hints:o===La?m:o})]})}function za({label:e,index:t,isCursor:n,isChecked:r,screenReader:i}){let a=K(),o=r?`[x] `:`[ ] `;return i?E(H,{children:[Bn(t),o,e]}):E(H,{color:n?a.text.accent:void 0,children:[n?`> `:` `,o,e]})}function Ba(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 Va(e){let t=Z(`multi-select`,[[[`previous`,`next`],`Navigate`],[`toggle`,`Toggle`],[`confirm`,e.canConfirm?`Confirm`:`Confirm (min ${e.minSelect})`],[`cancel`,`Cancel`]]);return e.screenReader?T(Vn,{itemCount:e.itemCount,cancellable:!0,buffer:e.numbered.buffer,invalid:e.numbered.invalid}):T(Y,{hints:t})}function Ha(e){let t=K(),{title:n,description:r,options:a,cursor:o,selected:s,screenReader:c,numbered:l}=e;return E(i,{flexDirection:`column`,...c?{}:{borderStyle:`round`,borderColor:t.border.attention},paddingX:1,children:[T(H,{color:t.text.warning,bold:!0,children:n}),r!==void 0&&r.length>0&&T(H,{dimColor:!0,children:r}),a.map((e,t)=>T(za,{label:e.label,index:t,isCursor:t===o,isChecked:s.has(e.value),screenReader:c},e.value)),T(Va,{screenReader:c,itemCount:a.length,numbered:l,canConfirm:e.canConfirm,minSelect:e.minSelect})]})}function Ua(e){let{options:t,minSelect:n,maxSelect:r,defaultValues:i,onConfirm:a}=e,[o,s]=C(0),[c,l]=C(()=>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 Wa({title:e,description:t,options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o,onCancel:s}){let c=G(),{cursor:l,setCursor:u,selected:d,toggleAt:f,confirmIfAllowed:p}=Ua({options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o}),m=un({enabled:c,itemCount:n.length,cancellable:!0,multi:!0,onSelect:f,onConfirm:p,onCancel:s});Ba({active:!c,itemCount:n.length,setCursor:u,onToggleAtCursor:()=>f(l),onConfirm:p,onCancel:s});let h=d.size>=r;return T(Ha,{title:e,...t===void 0?{}:{description:t},options:n,cursor:l,selected:d,screenReader:c,canConfirm:h,minSelect:r,numbered:m})}function Ga(){return{value:``,resolved:!1}}function Ka(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`}}:qa(e,n)}function qa(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 Ja({title:e,description:t,placeholder:n,onSubmit:r,onCancel:a,validate:o,allowEmpty:s=!1,masked:c=!1}){let l=K(),[u,d]=C(()=>Ga()),f=S(u),p=_(e=>{let t=Ka(f.current,e,{allowEmpty:s,validate:o});f.current=t.state,d(t.state),t.effect.type===`cancel`?a():t.effect.type===`submit`&&r(t.effect.value)},[s,o,a,r]),m=G();Q(`text-prompt`,(e,t,n,r)=>{for(let t of e)t===`submit`?p({type:`submit`}):t===`cancel`?p({type:`cancel`}):t===`delete-backward`&&p({type:`delete`});e.length===0&&!r&&t&&n.ctrl!==!0&&n.meta!==!0&&p({type:`insert`,value:t})});let h=Z(`text-prompt`,[[`submit`,`Submit`],[`cancel`,`Cancel`]]);return E(i,{flexDirection:`column`,...m?{}:{borderStyle:`round`,borderColor:l.border.attention},paddingX:1,children:[T(H,{color:l.text.warning,bold:!0,children:e}),T(Ya,{description:t}),E(i,{marginTop:1,children:[T(H,{color:l.text.accent,children:`> `}),u.value?T(H,{children:c?`*`.repeat(u.value.length):u.value}):n?T(H,{dimColor:!0,children:n}):null,T(H,{color:l.text.accent,children:`█`})]}),u.error&&T(H,{color:l.text.error,children:u.error}),T(Y,{hints:h})]})}function Ya({description:e}){return e===void 0||e.length===0?null:T(H,{dimColor:!0,children:e})}const Xa={value:``,label:`Type a custom answer…`};function Za({request:e,onAnswer:t}){let n=K(),[r,a]=C(!1),o=e.options??[],s=o.length>0,c=e.maxSelect??1,l=()=>t({type:`cancelled`});if(!s||r)return T(Ja,{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?()=>a(!1):l},`text:${e.id}`);if(c>1)return T(Wa,{title:e.title,description:e.description,options:o,minSelect:e.minSelect??1,maxSelect:c,defaultValues:e.default?.values,onConfirm:e=>t({type:`answer`,values:e}),onCancel:l});let u=e.allowFreeText?[...o,Xa]:[...o],d=e.default?.values?.[0],f=d===void 0?0:Math.max(0,u.findIndex(e=>e.value===d));return E(i,{flexDirection:`column`,children:[T(H,{bold:!0,children:e.title}),e.description!==void 0&&e.description.length>0&&T(H,{dimColor:!0,children:e.description}),T(Ra,{items:u,initialIndex:f,maxVisible:e.maxVisible,renderItem:(e,t)=>E(H,{color:t?n.text.accent:void 0,children:[t?`> `:` `,e.label]}),onSelect:e=>{e===Xa?a(!0):t({type:`answer`,values:[e.value]})},onCancel:l})]})}const Qa=[`Allow [y]`,`Allow always (this session) [s]`,`Allow always (this project) [p]`,`Deny [n]`];function $a(e,t=!0){return[Qa[0],`Allow ${e} always (this session) [s]`,t?`Allow ${e} always (this project) [p]`:`Project-wide approval unavailable`,Qa[3]]}function eo(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`}}:no(e,t.index);let r=tn(e,t,{itemCount:Qa.length});return r.effect.type!==`select`||r.effect.index===2&&!n?{state:r.state,effect:{type:`none`}}:{state:r.state,effect:{type:`resolve`,decision:to(r.effect.index)}}}function to(e){return e===0?!0:e===1?`allow-session`:e===2&&`allow-project`}function no(e,t){return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`resolve`,decision:to(t)}}}function ro(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 io({request:e}){let t=K(),n=e.canPersistProjectPermission!==!1,[r,a]=h.useState(()=>Qt()),o=h.useRef(r),s=h.useRef(e);if(s.current!==e){s.current=e;let t=Qt();o.current=t,a(t)}let c=h.useCallback(t=>{let r=eo(o.current,t,n);o.current=r.state,a(r.state),r.effect.type===`resolve`&&e.resolve(r.effect.decision)},[e,n]),l=G(),u=$a(re(e.toolName,e.toolArgs),n),d=un({enabled:l,itemCount:u.length,onSelect:t=>{let r=eo(o.current,{type:`shortcut`,index:t},n);o.current=r.state,a(r.state),r.effect.type===`resolve`&&e.resolve(r.effect.decision)}});Q(`permission-prompt`,e=>{let t={"allow-once":0,"allow-session":1,"allow-project":2,deny:3};for(let n of e)n in t?c({type:`shortcut`,index:t[n]}):(n===`previous`||n===`next`||n===`confirm`)&&c(n===`confirm`?`select`:n)},{isActive:!l});let f=Z(`permission-prompt`,[[[`previous`,`next`],`Navigate`],[`confirm`,`Confirm`]]);return l?T(Hn,{title:ga.permissionRequired,description:`${e.toolName} — ${ro(e.toolArgs)}${e.requestedByPeer===void 0?``:` (requested by another session: ${e.requestedByPeer})`}`,options:u,buffer:d.buffer,invalid:d.invalid}):E(i,{flexDirection:`column`,borderStyle:`round`,borderColor:t.border.attention,paddingX:1,children:[T(H,{color:t.text.warning,bold:!0,children:`[Permission Required]`}),E(H,{children:[`Tool:`,` `,T(H,{color:t.text.accent,bold:!0,children:e.toolName})]}),E(H,{dimColor:!0,children:[` `,ro(e.toolArgs)]}),e.requestedByPeer===void 0?null:E(H,{color:t.text.warning,children:[`Requested by another session: `,e.requestedByPeer]}),T(i,{marginTop:1,flexDirection:`column`,children:u.map((e,n)=>T(i,{children:E(H,{color:n===r.selectedIndex?t.text.accent:void 0,bold:n===r.selectedIndex,children:[n===r.selectedIndex?`> `:` `,e]})},e))}),T(Y,{hints:f})]})}function ao(){return{buffer:``,resolved:!1}}const oo=[`y`,`yes`],so=[`n`,`no`];function co(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}}:so.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 lo(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:typeof t==`string`?tn(e,t,{itemCount:n}):{state:{...e,selectedIndex:t.index,resolved:!0},effect:{type:`select`,index:t.index}}}function uo({message:e,options:t=[`Yes`,`No`],onSelect:n}){let r=K(),[a,o]=C(()=>Qt()),s=S(a),c=_(e=>{let r=lo(s.current,e,t.length);s.current=r.state,o(r.state),r.effect.type===`select`&&n(r.effect.index)},[n,t.length]),l=G(),[u,f]=C(ao),p=S(u);d((e,t)=>{let r=co(p.current,e,t);p.current=r.state,f(r.state),r.effect.type===`select`&&n(r.effect.index)},{isActive:l}),Q(`confirm-prompt`,e=>{for(let n of e)n===`choose-yes`&&t.length===2?c({type:`shortcut`,index:0}):n===`choose-no`&&t.length===2?c({type:`shortcut`,index:1}):(n===`previous`||n===`next`||n===`confirm`)&&c(n===`confirm`?`select`:n)},{isActive:!l});let m=Z(`confirm-prompt`,[[[`previous`,`next`],`Navigate`],[`confirm`,`Confirm`]]);return l?E(i,{flexDirection:`column`,children:[T(H,{children:e}),E(H,{children:[`Answer y or n and press Enter`,u.buffer.length>0?` ${u.buffer}`:``]})]}):E(i,{flexDirection:`column`,borderStyle:`round`,borderColor:r.border.attention,paddingX:1,children:[T(H,{color:r.text.warning,children:e}),T(i,{marginTop:1,children:t.map((e,t)=>T(i,{marginRight:2,children:E(H,{color:t===a.selectedIndex?r.text.accent:void 0,bold:t===a.selectedIndex,children:[t===a.selectedIndex?`> `:` `,e]})},e))}),T(Y,{hints:m})]})}function fo(e,t,n,r,i){let[a,o]=C([]),[s,c]=C(!1),[l,u]=C();return y(()=>{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:a,error:o}){let s=K(),[c,l]=C(()=>Qt()),u=S(c),d=!a&&!o,f=G(),p=un({enabled:f&&d,itemCount:t.length,cancellable:!0,onSelect:e=>{let r=t[e];r!==void 0&&n(r.value)},onCancel:r}),m=_(e=>{let i=tn(u.current,e,{itemCount:t.length,enabled:d});if(u.current=i.state,l(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)}},[d,t,r,n]);Q(`menu-select`,e=>e.forEach(e=>m(e===`back`?`cancel`:e)),{isActive:!f});let h=Z(`menu-select`,[[[`previous`,`next`],`Navigate`],[`select`,`Select`],[`back`,`Back`]]),g=Z(`menu-select`,[[`back`,`Back`]]),v=nn(c,{itemCount:t.length});v!==c&&(u.current=v);let y=v.selectedIndex;return f?T(Hn,{title:e,options:a||o?[]:t.map(e=>e.label),description:a?`Loading...`:o,cancellable:!0,buffer:p.buffer,invalid:p.invalid}):E(i,{flexDirection:`column`,borderStyle:`round`,borderColor:s.border.attention,paddingX:1,children:[T(H,{color:s.text.warning,bold:!0,children:e}),a&&T(i,{marginTop:1,children:T(H,{dimColor:!0,children:`Loading...`})}),o&&T(i,{marginTop:1,children:T(H,{color:s.text.error,children:o})}),!a&&!o&&T(i,{flexDirection:`column`,marginTop:1,children:t.map((e,t)=>E(i,{children:[E(H,{color:t===y?s.text.accent:void 0,bold:t===y,children:[t===y?`> `:` `,e.label]}),e.hint&&E(H,{dimColor:!0,children:[` `,e.hint]})]},e.value))}),T(Y,{hints:a?[]:o?g:h})]})}function mo(e,t){e===`marketplace`?t.push({screen:`marketplace-list`}):e===`installed`&&t.push({screen:`installed-list`})}function ho(e,t){e===`__add__`?t.push({screen:`marketplace-add`}):t.push({screen:`marketplace-action`,context:{marketplace:e}})}function go(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 _o(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 vo(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 yo(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 bo(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 xo({callbacks:e,onClose:t,addMessage:n}){let[r,i]=C([{screen:`main`}]),[a,o]=C(),[s,c]=C(0),l=r[r.length-1]??{screen:`main`},u=_(e=>{i(t=>[...t,e])},[]),d=_(()=>{i(e=>e.length<=1?(t(),e):e.slice(0,-1))},[t]),f=_(e=>{i(n=>{let r=n.slice(0,Math.max(1,n.length-e));return r.length===0?(t(),n):r})},[t]),p=_(e=>{n?.({role:`system`,content:e})},[n]),m=_(()=>{c(e=>e+1)},[]),h=_(e=>o(e),[o]),g={push:_(e=>u({screen:e.screen,context:e.context}),[u]),pop:d,popN:f,notify:p,setConfirm:h,refresh:m},{items:v,loading:y,error:b}=fo(l.screen,l.context?.marketplace,e,s,r.length),x=_(t=>{let n=l.screen,r=l.context;n===`main`?mo(t,g):n===`marketplace-list`?ho(t,g):n===`marketplace-action`?go(t,r?.marketplace??``,e,g):n===`marketplace-browse`?_o(t,r?.marketplace??``,v,g):n===`marketplace-install-scope`?vo(t,r?.pluginId??``,e,g):n===`installed-list`?yo(t,e,g):n===`installed-action`&&bo(t,r?.pluginId??``,e,g)},[l,v,e,u,d,f,p,o,m]),S=_(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 T(uo,{message:a.message,onSelect:e=>{e===0?a.onConfirm():a.onCancel()}});let w=l.screen;return w===`marketplace-add`?T(Ja,{title:`Add Marketplace Source`,placeholder:`owner/repo or git URL`,onSubmit:S,onCancel:d,validate:e=>e.includes(`/`)?void 0:`Must be owner/repo or a git URL`}):w===`marketplace-action`?T(po,{title:`Marketplace: ${l.context?.marketplace??``}`,items:[{label:`Browse plugins`,value:`browse`},{label:`Update`,value:`update`},{label:`Remove`,value:`remove`}],onSelect:x,onBack:d},r.length):w===`marketplace-install-scope`?T(po,{title:`Install scope for "${l.context?.pluginId??``}"`,items:[{label:`User scope`,value:`user`},{label:`Project scope`,value:`project`}],onSelect:x,onBack:d},r.length):w===`installed-action`?T(po,{title:`Plugin: ${l.context?.pluginId??``}`,items:[{label:`Uninstall`,value:`uninstall`}],onSelect:x,onBack:d},r.length):T(po,{title:{main:`Plugin Management`,"marketplace-list":`Marketplace`,"marketplace-browse":`Browse: ${l.context?.marketplace??``}`,"installed-list":`Installed Plugins`}[w]??`Plugin Management`,items:{main:[{label:`Marketplace`,value:`marketplace`},{label:`Installed Plugins`,value:`installed`}]}[w]??v,onSelect:x,onBack:d,loading:y,error:b},`${w}-${r.length}-${s}`)}function So({notices:e}){let t=K();return e.length===0?null:T(i,{flexDirection:`column`,paddingX:1,children:e.map(e=>T(H,{color:t.text.muted,children:e.message},e.id))})}function Co({sessions:e,onSelect:t,onCancel:n}){return E(i,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[T(H,{bold:!0,color:K().text.accent,children:`Select a session to resume:`}),T(Ra,{items:[...e],renderItem:(e,t)=>{let n=e.preview?e.preview.slice(0,60)+(e.preview.length>60?`...`:``):``;return E(H,{children:[t?`> `:` `,T(H,{bold:!0,children:e.name??e.id.slice(0,8)}),` `,T(H,{dimColor:!0,children:new Date(e.updatedAt).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}),` `,E(H,{dimColor:!0,children:[`msgs: `,e.messageCount]}),n?E(w,{children:[`
32
- `,T(H,{dimColor:!0,children:n})]}):null]})},onSelect:e=>t(e.id),onCancel:n})]})}function wo(e){let t=To(e),n=e.hasPendingPrompt&&t.kind!==`queued`?[`queued`]:[],r=[t.label,...n].join(` · `);return{...t,segments:n,text:r}}function To(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 Eo=` | `;function Do(e,t){return e>=90?t.text.error:e>=70?t.text.warning:t.text.success}function Oo({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r}){let i=K(),a=wo({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r});return T(H,{color:i.text[a.tone],bold:a.kind!==`idle`,children:a.text})}function ko({percentage:e,usedTokens:t,maxTokens:n}){return E(H,{color:Do(e,K()),children:[`Context: `,Math.round(e),`% (`,P(t),`/`,P(n),` tokens)`]})}function Ao({permissionMode:e}){return E(w,{children:[T(H,{color:K().text.accent,bold:!0,children:`Mode:`}),` `,T(H,{children:e})]})}function jo(e,t){return t||e!=="default"}function Mo({activePresetId:e}){return E(w,{children:[T(H,{color:K().text.accent,bold:!0,children:`Preset:`}),` `,T(H,{children:e})]})}function No(e){return e!==void 0&&e!=="default"}function Po({modelName:e,providerDisplayName:t,effort:n}){return E(H,{dimColor:!0,children:[t===void 0?e:`${t} ${e}`,n===void 0?``:` Effort: ${n}`]})}function Fo(e){let t=K(),n=e.showGitBranch&&e.gitBranch!==void 0&&e.gitBranch.length>0,r=G(),i=jo(e.permissionMode,r),a=e.activePresetId,o=No(a);return E(H,{children:[!r&&T(Oo,{isThinking:e.isThinking,activeToolCount:e.activeToolCount,activeBackgroundTaskCount:e.activeBackgroundTaskCount,hasPendingPrompt:e.hasPendingPrompt}),i&&E(w,{children:[Eo,T(Ao,{permissionMode:e.permissionMode})]}),o&&E(w,{children:[Eo,T(Mo,{activePresetId:a})]}),e.sessionName&&E(w,{children:[Eo,T(H,{color:t.text.session,children:e.sessionName})]}),n&&E(w,{children:[Eo,E(H,{dimColor:!0,children:[`git: `,e.gitBranch]})]}),Eo,T(Po,{modelName:e.modelName,providerDisplayName:e.providerDisplayName,effort:e.effort}),!r&&E(w,{children:[Eo,T(ko,{percentage:e.contextPercentage,usedTokens:e.contextUsedTokens,maxTokens:e.contextMaxTokens})]})]})}function Io({permissionMode:e,modelName:t,providerDisplayName:n,sessionId:r,isThinking:a,activeToolCount:o=0,activeBackgroundTaskCount:s=0,hasPendingPrompt:c=!1,contextPercentage:l,contextUsedTokens:u,contextMaxTokens:d,sessionName:f,gitBranch:p,showGitBranch:m=!0,activeAgentLabel:h,activePresetId:g,effort:_}){let v=K();return E(i,{paddingLeft:1,paddingRight:1,justifyContent:`space-between`,children:[T(Fo,{permissionMode:e,modelName:t,providerDisplayName:n,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextPercentage:l,contextUsedTokens:u,contextMaxTokens:d,sessionName:f,gitBranch:p,showGitBranch:m,activePresetId:g,effort:_}),h!==void 0&&E(H,{color:v.text.warning,bold:!0,children:[`[`,h,`]`]})]})}const Lo=g(null),Ro=Lo.Provider;function zo(){let e=v(Lo);if(!e)throw Error(`TuiCliAdapterContext not provided`);return e}function Bo({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}){let g=zo(),_=x(()=>g.getGitBranch(e),[g,e,h]),v=x(()=>r===void 0?void 0:g.getProviderDisplayName(r),[g,r]);return d.enabled?T(Io,{permissionMode:t,modelName:n??``,providerDisplayName:v,sessionId:i,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextPercentage:l.percentage,contextUsedTokens:l.usedTokens,contextMaxTokens:l.maxTokens,sessionName:u,gitBranch:_,showGitBranch:d.gitBranch,activeAgentLabel:f,activePresetId:p,effort:m}):null}function Vo(e,t){let n=Ot(e);return{color:Dt(t,n),icon:Et[n],strikethrough:n===`error`||n===`denied`}}function Ho({isThinking:e}){let t=K();return e?T(i,{marginBottom:1,children:T(H,{color:t.text.warning,children:`Thinking...`})}):T(w,{})}function Uo({activeTools:e}){let t=K(),n=ha();return E(i,{flexDirection:`column`,marginBottom:1,children:[T(H,{color:t.text.emphasis,bold:!0,children:`Tools:`}),T(H,{children:` `}),e.map((e,r)=>{let{color:a,icon:o,strikethrough:s}=Vo(e,t);return E(i,{flexDirection:`column`,children:[E(H,{color:a,strikethrough:s,children:[` `,o,` `,la(e.toolName,n),`(`,ua(e.firstArg),`)`]}),e.diffLines&&e.diffLines.length>0&&T(Da,{file:e.diffFile,lines:e.diffLines})]},`${e.toolName}-${r}`)})]})}function Wo(e,t,n,r){let i=t.map(e=>la(e.toolName,r)).join(`, `),a=[i.length>0?`${ga.tool} ${i}`:void 0,e.length>0?e:n?ga.thinking:void 0].filter(e=>e!==void 0);return a.length===0?T(w,{}):T(H,{children:a.join(` — `)})}function Go({text:e,activeTools:t,isThinking:n=!1}){let r=K(),a=sa(),o=t.length>0,s=e.length>0,c=G(),l=ma(),u=ha();return c?Wo(e,t,n,u):!o&&!s?T(Ho,{isThinking:n}):E(i,{flexDirection:`column`,children:[o&&T(Uo,{activeTools:t}),s&&E(i,{flexDirection:`column`,marginBottom:1,children:[E(H,{color:r.text.accent,bold:!0,children:[l,`:`]}),T(H,{children:` `}),T(i,{marginLeft:2,children:T(U,{wrap:`wrap`,children:a(e)})})]})]})}function Ko(e,t){let n=t?` (current)`:``;return`${e.name} — ${e.appearance}, ${e.source}${n}`}function qo({theme:e,isFocused:t,isActive:n,rowNumber:r}){let i=K(),a=r===void 0?t?`> `:` `:Bn(r);return E(H,{...t&&r===void 0?{color:i.text.accent,bold:!0}:{},children:[a,Ko(e,n)]})}function Jo({itemCount:e,buffer:t,invalid:n}){let r=zn(e,!0);return E(i,{flexDirection:`column`,children:[E(H,{children:[r,t.length>0?` ${t}`:``]}),n&&T(H,{children:r})]})}function Yo(e,t){let n=e.findIndex(e=>e.id===t);return n<0?0:n}function Xo(e){let[t,n]=h.useState(()=>({syntaxHighlighting:e.syntaxHighlighting,reducedMotion:e.reducedMotion}));return{toggles:t,setToggles:n}}function Zo(e){let{themes:t,activeThemeId:n,preview:r}=e,[i,a]=h.useState(()=>Yo(t,n));return{focusedIndex:i,move:h.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 Qo(e,t){let{themes:n,select:r,cancel:i}=e,{focusedIndex:a,move:o}=Zo(e),{toggles:s,setToggles:c}=Xo(e),l=h.useRef(s);l.current=s;let u=h.useCallback(e=>{let t=n[e];t&&r(t.id,l.current)},[r,n]),d=un({enabled:t&&n.length>0,itemCount:n.length,cancellable:!0,onSelect:u,onCancel:i}),f=h.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 $o({themes:e,activeThemeId:t,focusedIndex:n,screenReader:r}){return e.length===0?T(H,{dimColor:!0,children:`No themes installed`}):T(w,{children:e.map((e,i)=>T(qo,{theme:e,isFocused:i===n,isActive:e.id===t,...r?{rowNumber:i}:{}},e.id))})}function es(){return Ae()?T(w,{}):T(H,{dimColor:!0,children:`Colour is off for this terminal — themes apply, previews cannot show.`})}function ts({skipped:e}){return e.length===0?T(w,{}):T(i,{flexDirection:`column`,marginTop:1,children:e.map((e,t)=>T(H,{dimColor:!0,children:` Skipped "${e.fileName}" — ${e.reason}`},t))})}function ns({toggles:e,reducedMotionPin:t,screenReader:n}){let r=e=>e?`on`:`off`,a=t===void 0?``:` (this run: motion ${r(!t.reducedMotion)}, pinned by ${t.tier})`;return E(i,{flexDirection:`column`,children:[T(H,{dimColor:!0,children:`syntax ${r(e.syntaxHighlighting)} · motion ${r(!e.reducedMotion)}${a}`}),n&&T(H,{dimColor:!0,children:`Change with /theme syntax on|off or /theme motion on|off`})]})}function rs({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?T(Jo,{itemCount:t,buffer:n.buffer,invalid:n.invalid}):T(Y,{hints:r})}function is({picker:e}){let t=K(),n=G(),{themes:r,activeThemeId:a}=e,{focusedIndex:o,toggles:s,numbered:c}=Qo(e,n);return E(i,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.focused},paddingX:1,children:[T(H,{color:t.text.accent,bold:!0,children:`Theme`}),T(es,{}),T(ns,{toggles:s,reducedMotionPin:e.reducedMotionPin,screenReader:n}),T(i,{flexDirection:`column`,marginTop:1,children:T($o,{themes:r,activeThemeId:a,focusedIndex:o,screenReader:n})}),T(ts,{skipped:e.skipped}),T(rs,{screenReader:n,itemCount:r.length,numbered:c})]})}function as({entry:e,selected:t}){let n=K(),r=e.config.enabled,a=r?`●`:`○`,o=r?`[on] `:`[off]`,s=e.config.options?.port,c=typeof s==`number`?`port: ${s}`:``;return T(i,{children:T(H,{color:t?n.text.accent:void 0,bold:t,children:`${a} ${e.transport.name.padEnd(18)} ${o} ${c}`})})}function os(e,t,n,r,i,a,o,s,c){Q(`transport-settings`,_(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 ss({registry:e,onClose:t}){let n=K(),r=ma(),[a,o]=C(()=>e.getAll()),[s,c]=C(0),[l,u]=C(!1),[d,f]=C(void 0),p=_(()=>{o(e.getAll())},[e]),m=Z(`transport-settings`,[[[`previous`,`next`],`Select`],[`toggle`,`Toggle`],[`close`,`Close`]]);return os(a,s,l,e,c,u,f,t,p),E(i,{flexDirection:`column`,paddingX:2,paddingY:1,children:[T(H,{bold:!0,children:`Settings › Transports`}),T(i,{marginTop:1,flexDirection:`column`,children:a.map((e,t)=>T(as,{entry:e,selected:t===s},e.transport.name))}),E(i,{marginTop:1,flexDirection:`column`,children:[T(Y,{hints:m}),E(H,{dimColor:!0,children:[`A toggle is saved now and applies the next time `,r,` starts.`]})]}),l&&T(i,{marginTop:1,children:T(H,{color:n.text.warning,children:`Saving…`})}),d!==void 0&&T(i,{marginTop:1,children:T(H,{color:n.text.error,children:`Not saved — ${d}`})})]})}function cs({message:e}){return T(i,{paddingX:1,marginBottom:1,children:T(H,{color:K().text.warning,children:e})})}function ls({model:e}){return T(a,{items:e.staticItems,children:e=>e.kind===`banner`?T(Ct,{version:e.version},`logo`):T(Ia,{entry:e.entry},e.entry.id)})}function us({model:e}){let t=K(),{background:n,stream:r}=e;return E(i,{flexDirection:`column`,paddingX:1,flexGrow:1,children:[n.selectedEntry&&n.selectedEntry.kind!==`main_thread`&&T(Xt,{entry:n.selectedEntry,page:n.detail.page,loading:n.detail.loading,error:n.detail.error}),e.isShuttingDown&&T(H,{color:t.text.warning,children:`Shutting down...`}),(r.isThinking||r.activeTools.length>0)&&E(i,{flexDirection:`column`,marginBottom:1,children:[T(Go,{text:r.text,activeTools:r.activeTools,isThinking:r.isThinking}),r.isStalled&&T(H,{color:t.text.warning,children:`⚠ Still waiting on the provider — the network may be stalled. Esc to interrupt.`})]}),!r.isThinking&&r.lastErrorMessage&&T(H,{color:t.text.error,children:`✖ Last turn failed — the session is alive; type your next prompt when ready.`}),T(Jt,{entries:n.entries,focusedIndex:n.focusedIndex})]})}function ds({model:e}){if(e.coordinationError!==void 0||e.coordinationPending)return T(w,{});let{background:t,plugin:n,sessionPicker:r,transport:i}=e,a=e.pendingUserAction;return E(w,{children:[t.switcherVisible&&T(Wn,{snapshot:t.snapshot,selectedEntryId:t.selectedEntryId,onSelect:t.select,onClose:t.closeSwitcher,onAttach:t.attachToFork}),e.permissionRequest&&T(io,{request:e.permissionRequest}),a&&T(Za,{request:a,onAnswer:t=>e.resolveUserAction(a,t)}),n.visible&&T(xo,{callbacks:n.callbacks,onClose:n.close,addMessage:e=>n.addMessage(e.content)}),i.visible&&i.registry&&T(ss,{registry:i.registry,onClose:i.close}),r.visible&&T(Co,{sessions:r.sessions,onSelect:r.select,onCancel:r.cancel}),e.theme.picker.visible&&T(is,{picker:e.theme.picker})]})}function fs({model:e}){let{input:t}=e;return E(w,{children:[T(Yt,{percentage:e.contextPercentage}),T(Ii,{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}),T(Bo,{...e.status})]})}function ps({viewModel:e}){let t=K(),n=Rn();return E(i,{flexDirection:`column`,children:[T(ls,{model:e}),!e.handoffSuspended&&E(w,{children:[e.updateNotice&&T(cs,{message:e.updateNotice}),e.coordinationError&&E(H,{color:t.text.error,children:[e.coordinationError,` Press Enter to retry.`]}),n.diagnostic&&T(H,{color:t.text.error,children:`Keybindings ${n.diagnostic.file} ${n.diagnostic.path}: ${n.diagnostic.message} Last valid bindings remain active.`}),n.warnings.map(e=>T(H,{color:t.text.warning,children:`Keybindings ${e.path}: ${e.message}`},`${e.path}:${e.code}`)),e.theme.unknownThemeNotice!==void 0&&T(H,{color:t.text.warning,children:e.theme.unknownThemeNotice}),T(So,{notices:e.sessionEventNotices}),T(us,{model:e}),T(ds,{model:e}),T(fs,{model:e})]})]})}function ms(e){return[...e.screenReader?[]:[{kind:`banner`,version:e.version??`0.0.0`}],...e.history.map(e=>({kind:`entry`,entry:e}))]}function hs(e){let t=e.forceExit??(e=>process.exit(e));if(e.isShuttingDown){t(130);return}e.graceful()}function gs(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 _s={promptStart:`A`,promptEnd:`B`,turnStart:`C`,turnEnd:`D`};function vs(e){return`\x1b]133;${_s[e]}\x07`}function ys(e){let t=e.write??(e=>{process.stdout.write(e)});return{emit(n){!e.enabled||!e.supported()||t(vs(n))}}}function bs(e,t){return e.executionId??`${e.toolName}#${t}`}function xs(e){let t=new Set;return e.forEach((e,n)=>{e.isRunning&&t.add(bs(e,n))}),t}function Ss(e){let{enabled:t,isThinking:n,activeTools:r,awaitingAnswer:i}=e,a=x(()=>gs({enabled:t}),[t]),o=Tr(),s=Or(),c=x(()=>ys({enabled:t,supported:()=>Me({override:s.turnMarks}),write:e=>o.write(e)}),[t,o,s.turnMarks]),l=S(!1),u=S(new Set);y(()=>{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]),y(()=>{c.emit(`promptStart`)},[c]),y(()=>{i&&a.promptMounted()},[i,a]),y(()=>{let e=xs(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 Cs(e){return!!(e.permissionRequest||e.pendingUserAction||e.pluginVisible||e.transportVisible||e.sessionPickerVisible||e.workspaceSwitcherVisible||e.historySearchOpen||e.themePickerVisible||e.coordinationBlocked)}function ws(e){Q(e.isThinking?`thinking`:`background-detail`,t=>{if(Cs(e))return;if(t.includes(`abort`)&&e.isThinking){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.stopWaitingLoop()})}function Ts(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 Es(e){Q(`recovery`,t=>{e.recoveryError!==void 0&&!e.recoveryPending&&t.includes(`retry`)&&e.retryRecovery()})}function Ds(e){let{exit:t}=c(),n=n=>{hs({isShuttingDown:e.isShuttingDown,graceful:()=>void e.shutdown(n).finally(()=>t())})};d((e,t)=>{t.ctrl&&e===`c`&&n(`prompt_input_exit`)}),y(()=>{let e=()=>n(`other`);return process.on(`SIGINT`,e),process.on(`SIGTERM`,e),()=>{process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}})}function Os(e){ws(e),Es(e),Ts(e),Ds(e);let t=G();return Ss({enabled:t,isThinking:e.isThinking,activeTools:e.activeTools,awaitingAnswer:e.permissionRequest!==null||e.pendingUserAction!==null}),t}function $(){return Promise.reject(Error(`Plugin management is unavailable in this host.`))}function ks(){return{listInstalled:$,listAvailablePlugins:$,install:$,uninstall:$,enable:$,disable:$,marketplaceAdd:$,marketplaceRemove:$,marketplaceUpdate:$,marketplaceList:$,reloadPlugins:$}}function As(e){return e??ks()}function js(e){return x(()=>As(e),[e])}function Ms(e){let t=js(e.pluginAdapter),n=_(t=>e.addEntry(F(M(t))),[e.addEntry]),r=_(t=>{e.setSessionPickerVisible(!1),e.onSessionSwitch(t)},[e.onSessionSwitch,e.setSessionPickerVisible]),i=_(()=>{e.setSessionPickerVisible(!1),e.addEntry(F(M(`Session resume cancelled.`)))},[e.addEntry,e.setSessionPickerVisible]);return{plugin:{visible:e.pluginVisible,callbacks:t,close:()=>e.setPluginVisible(!1),addMessage:n},transport:{visible:e.transportVisible,registry:e.transportRegistry,close:()=>e.setTransportVisible(!1)},sessionPicker:{visible:e.sessionPickerVisible,sessions:A(e.sessionStore,e.cwd),select:r,cancel:i}}}function Ns(e){let[t,n]=C(0),r=_(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=_(async e=>{n(e=>e+1),await r(e)},[r]),a=S(!1);return y(()=>{a.current&&!e.isThinking&&n(e=>e+1),a.current=e.isThinking},[e.isThinking]),{submit:i,gitRefreshToken:t}}function Ps(e){let{screens:t,workspace:n}=e.shell,r=Ns({selectedEntry:n.background.selectedEntry,submit:t.handleSubmit,sendAgentJob:e.state.sendAgentJob,isThinking:e.state.isThinking}),i=Os({isThinking:e.state.isThinking,isShuttingDown:e.state.isShuttingDown,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:Ms({cwd:e.cwd,pluginAdapter:e.pluginAdapter,pluginVisible:t.showPluginTUI,setPluginVisible:t.setShowPluginTUI,transportRegistry:e.transportRegistry,transportVisible:t.showTransportTUI,setTransportVisible:t.setShowTransportTUI,sessionStore:e.sessionStore,sessionPickerVisible:t.showSessionPicker,setSessionPickerVisible:t.setShowSessionPicker,onSessionSwitch:e.onSessionSwitch,addEntry:e.state.addEntry}),screenReader:i}}function Fs(e){let t=ma();y(()=>{let n=V(e??``),r=V(t),i=n?`${r} — ${n}`:r;process.stdout.write(`\x1b]0;${i}\x07`)},[e,t])}function Is(e){let[t,n]=C(!1);return y(()=>{if(e)return e.registerSuspendHooks({suspend:async()=>{n(!0),await new Promise(e=>setTimeout(e,50))},resume:()=>n(!1)})},[e]),t}function Ls(e){let[t,n]=C(),[r,i]=C(!0),a=_(()=>{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 y(()=>{a()},[e,a]),{startError:t,startPending:r,retryStart:a}}function Rs(e){let[t,n]=C();return y(()=>{let t=!0;return e?.then(e=>{t&&e!==void 0&&n(e)}).catch(()=>{}),()=>{t=!1}},[e]),t}function zs(e,t){let n=Ls(e),[r,i]=C(e.sessionName);return y(()=>{e.sessionName!==void 0&&e.sessionName!==r&&i(e.sessionName)},[e,e.sessionName,r]),Fs(r),{sessionName:r,setSessionName:i,handoffSuspended:Is(e.terminalHandoffController),updateNotice:Rs(t),...n}}function Bs(e){return se(e.readSettings(e.getUserSettingsPath()))}function Vs(){let e=zo(),[t,n]=C(()=>Bs(e));return[t,_(()=>{n(Bs(e))},[e])]}function Hs(e){let[t,n]=C(null),[r,i]=C(),[a,o]=C(!1),{entry:s,snapshot:c,read:l}=e;return y(()=>{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 Us(e,t){let n=ce(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 Ws({sessionStore:e,onSessionSwitch:t,addEntry:n}){let r=zo();return _(i=>{let a=e=>n(F(M(e)));if(e===void 0){a(`This surface has no session store, so it cannot attach to a forked session.`);return}Us(i,{hasSessionRecord:t=>e.load(t).status===`valid`,switchSession:t,notify:a,...r.formatResumeCommand===void 0?{}:{formatResumeCommand:r.formatResumeCommand}})},[n,r,t,e])}function Gs(e){let{snapshot:t,selectedEntryId:n}=e,r=x(()=>t?.entries.find(e=>e.id===n),[t,n]);return{entry:r,detail:Hs({entry:r,snapshot:t,read:e.read}),attachToFork:Ws({sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.addEntry})}}function Ks(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 qs(e,t,n,r,i){Q(`background-list`,i=>{if(e===null)return;let a=Ks(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 Js(e,t,n){let[r,i]=C(null);return y(()=>{i(t=>t===null||e.length===0?null:Math.min(t,e.length-1))},[e.length]),qs(r,e,i,t,n),{focusedIndex:r,focusList:_(()=>{e.length>0&&i(0)},[e.length])}}function Ys(e){return{open:_(()=>e(!0),[e]),toggle:_(()=>e(e=>!e),[e]),close:_(()=>e(!1),[e])}}function Xs(e){let t=x(()=>Nt(e.snapshot),[e.snapshot]),{focusedIndex:n,focusList:r}=Js(t.map(e=>e.id),e.select,e.navigationEnabled),i=Gs({selectedEntryId:e.selectedEntryId,snapshot:e.snapshot,read:e.read,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.addEntry}),a=Ys(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:Pt(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 Zs(e,t,n){let r=e=>{if(e.requesterDriverId===L)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 Qs(e){let t=S(e);return t.current=e,t}function $s({uiEventPort:e,baseHandleSubmit:t,setSessionName:n,refreshStatusLineSettings:r,refreshAppearanceSettings:i,showSessionPickerOnStart:a,openAgentSwitcher:o}){let[s,c]=C(!1),[l,u]=C(a??!1),[d,f]=C(!1),[p,m]=C(!1),h=Qs({setSessionName:n,refreshStatusLineSettings:r,refreshAppearanceSettings:i,openAgentSwitcher:o});return b(()=>Zs(e,{setShowPluginTUI:c,setShowTransportTUI:f,setShowSessionPicker:u,setShowThemePicker:m},h),[e]),{handleSubmit:_(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={...O},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 nc(e){return ec(e.readSettings(e.getUserSettingsPath()))}function rc(){let e=zo(),[t,n]=C(()=>nc(e));return[t,_(()=>{n(nc(e))},[e])]}function ic(e){let[t,n]=C(!1),[r,i]=C(!1),[a,o]=rc(),[s,c]=Vs(),l=$s({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:Xs({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 ac(e=Ee(),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===Te)return{theme:De(n.get(Te))};let t=n.get(e);return t?{theme:t}:{theme:De(n.get(Te)),unknownId:e}}}}function oc(e){return`Theme "${e}" is not installed — using "${Te}".`}function sc(e){return{id:e.id,name:e.name,appearance:e.appearance,source:e.source}}function cc(e){return{listThemes:()=>e.registry.list().map(sc),getTheme:t=>{let n=e.registry.get(t);return n?sc(n):void 0},getAppearance:()=>({settings:e.readAppearance(),...e.reducedMotionPin===void 0?{}:{reducedMotionPin:e.reducedMotionPin}})}}function lc(e){let t=x(()=>e.registry??ac(),[e.registry]),[n,r]=C(void 0),i=x(()=>t.resolve(n??e.appearance.theme),[t,n,e.appearance.theme]),{setVisible:a,submit:o}=e,s=_(()=>{r(void 0),a(!1)},[a]),{syntaxHighlighting:c,reducedMotion:l}=e.appearance,u=_((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:oc(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 uc(e){let[,t]=C(0);y(()=>e.subscribe(()=>t(e=>e+1)),[e]);let n=e.getSnapshot(),r=_(t=>e.selectExecutionWorkspaceEntry(t),[e]),i=_(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,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 dc(e,t){let n=e.sessionSwitchError??t.startError,r=!!(e.sessionSwitchPending||t.startPending);return{error:n,pending:r,blocked:n!==void 0||r}}function fc(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 pc(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,isAborting:r.isAborting,pendingPrompt:r.pendingPrompt,pendingCount:r.pendingCount,commandQueryPort:r.commandQueryPort,sessionName:e.lifecycle.sessionName,history:r.history,focusBackgroundList:n.focusBackgroundList,historySearch:fc(e)}}function mc(e){let{props:t,runtime:n,state:r}=e,i=e.shell.workspace;return{cwd:t.cwd,permissionMode:n.permissionMode,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}}function hc(e){let{interaction:t,lifecycle:n,shell:r,state:i}=e;return{staticItems:e.staticItems,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:pc(e),status:mc(e)}}function gc(e,t){return lc({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 _c(e,t){let[n,r]=C(e);return{initialValue:n,consumeInitialValue:_(()=>r(void 0),[]),externalPromptOrigin:t===`external-link`}}function vc(e,t,n){return x(()=>ms({history:e,version:t,screenReader:n}),[e,n,t])}function yc(e){let t=_c(e.initialInput,e.initialInputOrigin),n=uc(e.channel),r=zs(e.channel,e.startupUpdateNotice),i=dc(e,r),a=ic({state:n,setSessionName:r.setSessionName,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,showSessionPickerOnStart:e.showSessionPickerOnStart,coordinationBlocked:i.blocked}),o=Ps({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=hc({props:e,state:n,lifecycle:r,shell:a,interaction:o,staticItems:vc(n.history,e.version,o.screenReader),runtime:n.getRuntimeStatusSnapshot(e.permissionMode??`default`),coordination:i,theme:gc(e,a)});return{...s,input:{...s.input,...t}}}function bc(e){let t=yc(e);return T(Le,{theme:t.theme.resolved,reducedMotion:t.theme.reducedMotion,syntaxHighlighting:t.theme.syntaxHighlighting,children:T(ps,{viewModel:t})})}function xc(e){let[t,n]=C(()=>({channel:e.createChannel(e.resumeSessionId),sessionId:e.resumeSessionId})),[r,i]=C(e.showSessionPickerOnStart??!1),[a,o]=C(),[s,c]=C(!1),[l,u]=C(),d=S(!1),f=S(!0);y(()=>()=>{f.current=!1},[]);let p=_(async r=>{if(!d.current){d.current=!0,c(!0);try{if(i(!1),await t.channel.stop(),!f.current)return;n({channel:e.createChannel(r),sessionId:r}),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,t.channel]);return{state:t,showPicker:r,error:a,switching:s,switchSession:p,retrySwitch:_(()=>{l!==void 0&&p(l)},[l,p])}}function Sc(e){let t=xc(e);return T(Ro,{value:e.cliAdapter,children:T(bc,{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 Cc=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 wc(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 Tc=class extends R{source;hooks;onData=e=>{let t=wc(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 Ec(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 Dc(e,t=e=>{process.stdout.write(e)}){let n=Ec(e);n!==void 0&&t(`${n}\n`)}function Oc(e){return e??(e=>{process.stderr.write(`${e}\n`)})}function kc(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 Ac(e){if(!e.enabled)return{startupQuietMs:0,preparkMs:0};let t=Oc(e.warn);return{startupQuietMs:kc(e.overrides?.startupQuiet?.raw,e.overrides?.startupQuiet?.label??`startup quiet period`,900,6e5,t),preparkMs:kc(e.overrides?.prepark?.raw,e.overrides?.prepark?.label??`pre-write park`,50,5e3,t)}}function jc(e){return e?.isTTY!==!0||typeof e.setRawMode!=`function`?()=>{}:(e.setRawMode(!0),()=>{e.setRawMode?.(!1)})}async function Mc(e,t){if(e<=0)return`elapsed`;let n=jc(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 Nc(e){return typeof e==`string`?e:Buffer.from(e).toString(`utf8`)}function Pc(e){return V(e).trim().length>0}var Fc=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=Nc(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&&Pc(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 Ic(e){return new Fc(e)}function Lc(e){return{armEchoRelease:()=>e.armEchoRelease(),write:t=>{e.write(t)}}}function Rc(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 zc=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 Bc=new Set([`completed`,`failed`,`stopped`]);var Vc=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 Wc(`While away ${Uc(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&&Bc.has(n);if(!Bc.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} ${Hc(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} ${Hc(this.errorCount,`error`)}`),e}reset(){this.turnsFinished=0,this.wakeTurnsFinished=0,this.needsInputCount=0,this.errorCount=0,this.reachedTerminal.clear()}};function Hc(e,t){return e===1?t:`${t}s`}function Uc(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 Wc(e){return e.length<=120?e:`${e.slice(0,119)}…`}var Gc=class{options;recap=new Vc;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 Kc(e){return/not initialized/i.test(e.message)}function qc(e){let t=e.isBenignError??Kc,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 Jc(e,t,n,r,i){if(e.data?.pluginRegistryReloaded===!0&&i?.(n),r.addEntry(F(M(e.message))),t.isInitialized){let e=t.getContextState();r.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})}}var Yc=class extends AggregateError{},Xc=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 Yc&&(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)}},Zc=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()}}},Qc=class{onChange;entries=[];processing=!1;currentRequest=null;constructor(e){this.onChange=e}get current(){return this.currentRequest}enqueue(e,t,n,r,i){return new Promise(a=>{this.entries.push({toolName:e,toolArgs:t,resolve:a,...n===void 0?{}:{id:n},...r===void 0?{}:{canPersistProjectPermission:r},...i===void 0?{}:{requestedByPeer:i}}),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},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 $c(e,t){let n=null;try{n=t.getActiveDriverId?.()??null}catch{n=null}return F(de(e,n?{metadata:{driverId:n}}:{}))}function el(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 tl(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 nl=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=>{this.options.onUserMessage(n),t.addUserEcho($c(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)),el(this.bind.bind(this),t),this.bind(`permission_request`,({id:t,toolName:r,toolArgs:i,canPersistProjectPermission:a,requesterDriverId:o})=>{n?.onNeedsInput();let s=o?.startsWith(`peer:`)?me(o):void 0;this.options.requestPermission(r,i,t,a,s).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){tl(this.options.session,e,t,t=>{let n=this.options.onDeliveryError;n?n(t,e):this.options.manager.addSessionEventDeliveryError(t,e)},this.bindings)}};function rl(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.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,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},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 il(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(il(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 ol(e,t){let n=null;return{schedule(){n||=setTimeout(()=>{n=null,e()},t)},flush(){n&&=(clearTimeout(n),null)}}}var sl=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=ol(()=>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=this.activeTools.findLastIndex(t=>t.toolName===e.toolName&&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){if(e.length===0)return;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++]);this.history=t,this.notify()}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}};const cl=15e3;var ll=class{stateManager;interactiveSession;registry;opts;submitHandler=null;userActions;permissions;eventProjector;attention;lifecycle;availableCommands=[];sessionName;autoNameTriggered=!1;initPoller=null;get terminalHandoffController(){return this.opts.terminalHandoff}onChange=null;constructor(e){this.opts=e,this.sessionName=e.sessionName,this.stateManager=new sl,this.stateManager.onChange=()=>this.onChange?.(),this.userActions=new Zc(()=>this.onChange?.()),this.permissions=new Qc(()=>this.onChange?.()),this.interactiveSession=this.createSession(),this.registry=this.createRegistry(),this.attention=this.createAttention(e.attention),this.eventProjector=new nl({session:this.interactiveSession,manager:this.stateManager,...this.attention?{attention:this.attention}:{},onUserMessage:e=>this.handleAutoNaming(e),requestPermission:(e,t,n,r,i)=>this.permissions.enqueue(e,t,n,r,i),askUser:(e,t)=>this.askUser(e,t),dismissPrompt:e=>this.dismissPromptById(e),...e.onSessionEventDeliveryError?{onDeliveryError:e.onSessionEventDeliveryError}:{}}),this.lifecycle=new Xc({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(F(M(`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 Yc([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 ne(rl(this.opts))}createRegistry(){let e=new ee;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=this.interactiveSession.listSelfPacedLoops().filter(e=>e.phase===`waiting`);if(e.length===0)return;if(e.length>1){this.addEntry(F(M(`Several self-paced loops are waiting. Use /loop list and /loop stop <id> to choose one.`)));return}let t=e[0].loopId;try{await this.interactiveSession.stopSelfPacedLoop(t,`Loop stopped by Esc`),this.addEntry(F(M(`Loop ${t} stopped by Esc.`)))}catch(e){this.addEntry(F(M(`Could not stop loop ${t}: ${e instanceof Error?e.message:String(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 t=e.slice(1).split(/\s+/),n=t[0]?.toLowerCase()??``,r=t.slice(1).join(` `),i=await this.interactiveSession.executeCommand(n,r);if(i){if(i.data?.sessionExecution===!0){this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}Jc(i,this.interactiveSession,this.registry,this.stateManager,this.opts.reloadPluginCommandSource);return}this.stateManager.addEntry(F(M(`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()}handleAutoNaming(e){this.autoNameTriggered||this.opts.sessionName||this.interactiveSession.getName()||(this.autoNameTriggered=!0,ae(this.opts.provider,e).then(e=>{this.interactiveSession.setName(e),this.sessionName=e,this.opts.onAutoNamed?.(e),this.onChange?.()}).catch(()=>{this.autoNameTriggered=!1}))}syncRestoredHistory(){if(this.stateManager.history.length===0){let e=this.interactiveSession.getFullHistory();e.length>0&&this.stateManager.syncHistory(e)}}startInitCheck(){this.stopInitCheck(),this.initPoller=qc({check:()=>this.runInitCheck(),intervalMs:200,timeoutMs:cl,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 Gc({source:e,onRecap:e=>this.stateManager.addAttentionRecap(e)})}onInitFailure(e){let t=e.kind===`timeout`?`Session initialization timed out after ${cl/wt}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 ul(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.editCheckpointStore===void 0?{}:{editCheckpointStore:e.editCheckpointStore},...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},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 dl(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 fl(e){try{await e.keybindingsSource?.start(),await pl(e)}finally{e.keybindingsSource?.dispose()}}async function pl(t){let n=t.screenReader===!0;Dc({enabled:n,channel:t.screenReaderChannel,hint:t.screenReaderHint});let r=Ac({enabled:n,overrides:t.screenReaderPacing}),i=n&&r.preparkMs>0?Ic({stdout:process.stdout,preparkMs:r.preparkMs}):void 0;Ae()||(e.level=0);let a=new zc,o=Ne({override:t.focusReporting}),c=Rc({supported:()=>o}),l=new Cc({focusReporting:o,now:Date.now});a.setTerminalModeHooks({preSuspend:async()=>{c.disable(),await i?.drain()},postResume:()=>c.enable()});let u,d=t.workspaceMovedFrom,f=e=>{let n=d;d=void 0;let r=new ll({...ul(t,e),...n===void 0?{}:{workspaceMovedFrom:n},terminalHandoff:a,attention:l});return t.onChannelReady?.(r),u=r,r};await Mc(r.startupQuietMs,process.stdin);let p=new Tc(process.stdin,{negotiated:()=>c.negotiated,onFocusIn:()=>l.focusIn(),onFocusOut:()=>l.focusOut(),onKeystroke:()=>l.keystroke()});process.stdin.resume(),c.enable(),l.start();let m=i===void 0?void 0:Lc(i),h=T(pa,{name:t.productDisplayName,modelCommandToolPrefix:t.modelCommandToolPrefix,children:T(Ln,{source:t.keybindingsSource,children:T(ke,{enabled:n,children:T(Dr,{overrides:t.terminalCapabilities,children:T(Sc,{cwd:t.cwd,createChannel:f,providerOverride:t.providerOverride,providerType:t.providerType,modelId:t.modelId,permissionMode:t.permissionMode,version:t.version,sessionStore:t.sessionStore,resumeSessionId:t.resumeSessionId,showSessionPickerOnStart:t.showSessionPickerOnStart,initialInput:t.initialInput,initialInputOrigin:t.initialInputOrigin,startupUpdateNotice:t.startupUpdateNotice,transportRegistry:t.transportRegistry,pluginAdapter:t.commandHostAdapters?.plugin,cliAdapter:t.cliAdapter,promptHistorySource:t.promptHistorySource,promptHistoryProject:t.promptHistoryProject,themeRegistry:t.themeRegistry,reducedMotion:t.reducedMotion,reducedMotionOverride:t.reducedMotionOverride})})})})}),g=s(m===void 0?h:T(wr,{port:m,children:h}),{exitOnCtrlC:!1,isScreenReaderEnabled:n,stdin:p.asInkStdin(),...i===void 0?{}:{stdout:i.asInkStdout()}});a.setInkInstance(g);try{await dl(()=>g.waitUntilExit(),()=>u)}finally{await i?.flush(),a.setTerminalModeHooks(void 0),c.disable(),l.dispose(),p.detach(),process.stdin.pause()}}const ml=[`needs-input`,`working`,`idle`,`unknown`,`unverified`,`dead`];function hl(e){return e.liveness===`dead`?`dead`:e.liveness!==`alive`||e.control!==`available`?`unverified`:e.activity}function gl(e){return[...e].sort((e,t)=>ml.indexOf(hl(e))-ml.indexOf(hl(t))||e.id.localeCompare(t.id))}function _l(e){return[...e].sort((e,t)=>(e.cwd===void 0)-+(t.cwd===void 0)||(e.cwd??``).localeCompare(t.cwd??``)||ml.indexOf(hl(e))-ml.indexOf(hl(t))||e.id.localeCompare(t.id))}function vl(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 D(bl(c))<=n?c:e.slice(o)}function yl(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 bl(e){return yl(e).join(``)}function xl(e,t){let n=yl(e);if(D(n.join(``))<=t)return n.join(``);let r=Math.ceil((t-1)/2),i=t-r-1,a=``;for(let e of n){if(D(a)+D(e)>r)break;a+=e}let o=``;for(let e of[...n].reverse()){if(D(o)+D(e)>i)break;o=e+o}return`${a}…${o}`}function Sl(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})}function Cl(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 wl({loadRows:e,onStop:t,onStart:n,onOpenPr:r,filteredByCwd:a=!1,filteredByName:o=!1,filteredByPr:s=!1,stateFilter:l,refreshMs:u=2e3}){let{exit:f}=c(),{stdout:m}=p(),h=Math.max(12,m.columns??80),g=G(),[_,v]=C([]),[b,ee]=C(Date.now),[O,te]=C(`loading`),[k,ne]=C(),[re,ie]=C(!1),[ae,oe]=C(!1),[A,se]=C(),[j,ce]=C(`idle`),[le,ue]=C(),M=S(!1),[de,N]=C(`idle`),[P,fe]=C(),pe=S(!1),[F,me]=C(`idle`),he=S(!1),I=S(!0),L=x(()=>{let e=_.filter(e=>l===void 0||hl(e)===l);return ae?_l(e):gl(e)},[_,l,ae]),R=x(()=>{let e=[],t=[...new Set(L.map(e=>e.cwd).filter(e=>e!==void 0))],n,r=0;return L.forEach((i,a)=>{let o=ae?i.cwd??`unverified`:hl(i);if(o!==n){let n=ae?i.cwd===void 0?`Directory: unverified`:(()=>{let e=`Dir ${++r}: `,n=Math.max(4,h-e.length),a=xl(vl(i.cwd,t,n),n),o=`${e}${a} — ${bl(i.cwd)}`;return g||D(o)<=h?o:`${e}${a}`})():`${o}:`;e.push({kind:`group`,label:n})}e.push({kind:`row`,row:i,index:a}),n=o}),e},[L,ae,h,g]);y(()=>{let t=new AbortController,n=!0,r,i=async()=>{try{let r=gl(await e(t.signal));if(!n||t.signal.aborted)return;let i=Date.now();v(e=>Sl(e,r)?e:r),ee(e=>r.some(t=>t.nextLoopAt!==void 0&&Cl(t.nextLoopAt,e)!==Cl(t.nextLoopAt,i))?i:e),te(`ready`)}catch{n&&!t.signal.aborted&&te(`unavailable`)}finally{n&&!t.signal.aborted&&(r=setTimeout(()=>{i()},u))}};return i(),()=>{n=!1,r!==void 0&&clearTimeout(r),t.abort()}},[e,u]),y(()=>(I.current=!0,()=>{I.current=!1}),[]),y(()=>{ne(e=>e!==void 0&&L.some(t=>t.id===e)?e:L[0]?.id)},[L]),d((e,i)=>{if(!M.current&&!(he.current&&e!==`q`&&!(!g&&i.escape)&&!(i.ctrl&&e===`c`))&&!(pe.current&&e!==`q`&&!(!g&&i.escape)&&!(i.ctrl&&e===`c`))){if(A!==void 0){if(e===`n`||i.escape){se(void 0);return}if(e===`y`){let e=L.find(e=>e.id===A);if(se(void 0),O!==`ready`||e?.liveness!==`alive`||e.control!==`available`||t===void 0){ce(`unavailable`);return}M.current=!0,ce(`stopping`),t(A).then(()=>{I.current&&(ue(A),ce(`stopped`))}).catch(()=>{I.current&&ce(`failed`)}).finally(()=>{M.current=!1})}return}if(e===`q`||!g&&i.escape||i.ctrl&&e===`c`){f();return}if(e===`?`){ie(e=>!e);return}if(e===`g`){ge.clear(),oe(e=>!e);return}if(e===`n`&&n!==void 0){pe.current=!0,N(`starting`),Promise.resolve().then(n).then(e=>{I.current&&(fe(e),N(`started`))}).catch(()=>{I.current&&N(`failed`)}).finally(()=>{pe.current=!1});return}if(e===`p`&&r!==void 0){let e=L.find(e=>e.id===k);if(O!==`ready`||e?.liveness!==`alive`||e.control!==`available`||!e.pr){me(`unavailable`);return}he.current=!0,me(`opening`),r(e.id,e.pr.url).then(()=>{I.current&&me(`opened`)}).catch(()=>{I.current&&me(`failed`)}).finally(()=>{he.current=!1});return}if(e===`s`&&t!==void 0){let e=L.find(e=>e.id===k);O!==`ready`||e?.liveness!==`alive`||e.control!==`available`?ce(`unavailable`):(ce(`idle`),se(e.id));return}if(!(g||L.length===0)&&(i.upArrow||i.downArrow)){let e=Math.max(0,L.findIndex(e=>e.id===k)),t=Math.max(0,Math.min(L.length-1,e+(i.downArrow?1:-1)));ne(L[t]?.id)}}});let ge=un({enabled:g&&A===void 0&&j!==`stopping`,itemCount:L.length,cancellable:!0,repeatable:!0,onSelect:e=>{ne(L[e]?.id),ce(`idle`)},onCancel:()=>{M.current||f()}}),z=L.find(e=>e.id===k),_e=O===`ready`&&z?.liveness===`alive`&&z.control===`available`?z.name:void 0,ve=O===`ready`&&z?.liveness===`alive`&&z.control===`available`&&z.activity===`idle`&&z.nextLoopAt?Cl(z.nextLoopAt,b):``,B=O===`ready`&&z?.liveness===`alive`&&z.control===`available`?z.pr:void 0,ye=Math.max(8,m.rows??24),be=[`Keys:`,g?`Number+Enter Select`:`↑/↓ Select`,`s Request stop`,`g Group state/dir`,...n===void 0?[]:[`n New session`],...r===void 0?[]:[`p Open linked PR`],`y Confirm stop`,`n/Esc Cancel stop`,`q/Esc/Ctrl+C Close`,`? Toggle help`,`Activity ≠ liveness`,`Idle ≠ attach-ready`,`Close keeps sessions`],xe=re&&A===void 0&&j!==`stopping`,Se=2+(l===void 0?0:1)+ +(O===`loading`||O===`unavailable`||O===`ready`&&L.length===0)+(k===void 0?0:1)+(_e===void 0?0:1)+(B===void 0?0:2)+ +!!ve+(F===`idle`?0:1)+(de===`idle`?0:1)+(A===void 0?j===`idle`?0:1:g?1:2)+1+(xe?be.length:0)+2,V=Math.max(1,ye-Se),Ce=Math.max(0,R.findIndex(e=>e.kind===`row`&&e.row.id===k)),U=Math.min(Math.max(0,Ce-Math.floor(V/2)),Math.max(0,R.length-V)),we=g?R:R.slice(U,U+V),W=g?{}:{wrap:`truncate-end`},Te=j===`stopping`?`Stop in progress; wait for result.`:A===void 0?g?`Type a number and Enter to select; s Stop;${n?` n New;`:``}${r?` p Open PR;`:``} g Group; Escape to close; ? Help.`:`↑↓ Navigate s Stop${n?` n New`:``}${r?` p Open PR`:``} g Group ? Help q/Esc Close`:`Confirm stop or cancel before closing.`;return E(i,{flexDirection:`column`,...g?{}:{height:ye},children:[E(H,{...W,children:[a?`Background sessions in selected directory`:`Background sessions across projects`,o?` · name filter active`:``,s?` · PR filter active`:``]}),E(H,{...W,children:[L.length,` supervised session(s). Foreground peers and saved records are separate.`]}),l!==void 0&&E(H,{...W,children:[`State: `,l]}),O===`loading`&&T(H,{...W,children:`Loading supervised sessions...`}),O===`unavailable`&&T(H,{...W,children:`Supervised session discovery unavailable; last verified rows remain below.`}),O===`ready`&&L.length===0&&T(H,{...W,children:`No supervised sessions.`}),U>0&&!g&&E(H,{children:[U,` more above`]}),we.map(e=>e.kind===`group`?T(H,{...W,children:e.label},`group-${e.label}`):E(H,{...g?{}:{wrap:`truncate-end`},children:[g?Bn(e.index):e.row.id===k?`> `:` `,e.row.name&&e.row.liveness===`alive`&&e.row.control===`available`?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,O===`ready`&&e.row.liveness===`alive`&&e.row.control===`available`&&e.row.activity===`idle`&&e.row.nextLoopAt?` ${Cl(e.row.nextLoopAt,b)}`:``,e.row.problem?` ${e.row.problem}`:``,O===`ready`&&e.row.liveness===`alive`&&e.row.control===`available`&&e.row.pr?` ${e.row.pr.host} ${e.row.pr.kind===`pull`?`#`:`!`}${e.row.pr.number}`:``]},`row-${e.row.id}`)),!g&&U+we.length<R.length&&E(H,{children:[R.length-U-we.length,` more below`]}),k!==void 0&&E(H,{...W,children:[`Selected `,k]}),_e!==void 0&&E(H,{...W,children:[`Name: `,_e]}),B!==void 0&&E(H,{...W,children:[`PR: `,B.host,` `,B.kind===`pull`?`#`:`!`,B.number]}),B!==void 0&&E(H,{...W,children:[`URL: `,B.url]}),ve&&T(H,{...W,children:ve}),F===`opening`&&T(H,{...W,children:`Opening linked PR...`}),F===`opened`&&T(H,{...W,children:`Opened linked PR.`}),F===`failed`&&T(H,{...W,children:`PR link changed or could not be opened.`}),F===`unavailable`&&T(H,{...W,children:`No verified PR link is available.`}),de===`starting`&&T(H,{...W,children:`Starting a background session...`}),de===`started`&&E(H,{...W,children:[`Started `,P,o||l!==void 0?` (may be hidden by filter)`:``]}),de===`failed`&&T(H,{...W,children:`Start failed; check workspace trust or run session start --background for details.`}),A!==void 0&&(g?E(H,{children:[`Stop `,A,`? y Yes / n No`]}):E(w,{children:[E(H,{...W,children:[`Stop …`,A.slice(-8),`?`]}),T(H,{...W,children:`y Yes / n No`})]})),A===void 0&&j===`unavailable`&&T(H,{...W,children:`This session cannot be stopped from the view.`}),j===`stopping`&&T(H,{...W,children:`Stopping selected session; wait for confirmation.`}),j===`stopped`&&E(H,{...W,children:[`Stopped `,le]}),j===`failed`&&T(H,{...W,children:`Stop failed; session remains listed until verified otherwise.`}),g&&L.length>0&&A===void 0&&j!==`stopping`&&E(H,{children:[zn(L.length,!0),ge.buffer?` ${ge.buffer}`:``]}),g&&ge.invalid&&T(H,{children:`Selection out of range.`}),T(H,{...W,children:Te}),xe&&be.map(e=>T(H,{...W,children:e},e))]})}async function Tl(e){Dc({enabled:e.screenReader,channel:e.screenReaderChannel,hint:e.screenReaderHint});let t=s(T(ke,{enabled:e.screenReader,children:T(wl,{loadRows:e.loadRows,onStop:e.onStop,onStart:e.onStart,onOpenPr:e.onOpenPr,filteredByCwd:e.filteredByCwd,filteredByName:e.filteredByName,filteredByPr:e.filteredByPr,stateFilter:e.stateFilter,refreshMs:e.refreshMs})}),{isScreenReaderEnabled:e.screenReader,exitOnCtrlC:!1});try{await t.waitUntilExit()}finally{t.unmount()}}function El({providerDefinitions:e,reloadPluginCommandSource:t,userSettingsPath:n,settingsSources:r,formatResumeCommand:i}){return{getUserSettingsPath:()=>n,readSettings:e=>j(e),reloadPluginCommandSource:e=>{t(e)},applyActiveModelChange:(e,t,i)=>(k(r,[ie(`user`,n)],t,i),{applied:!0}),getGitBranch:e=>le(e),getProviderDisplayName:t=>N(e,t)?.displayName??t,...i===void 0?{}:{formatResumeCommand:i}}}function Dl(e){return{$schema:e,version:1,bindings:{}}}function Ol(e,t){let n=kn(JSON.stringify(Dl(t)),e);if(!n.ok)throw Error(n.diagnostic.message);return n.snapshot}var kl=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=Ol(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=ye(this.filePath);if(await z(e,{recursive:!0}),await this.#u(),this.#s)throw Error(`Keybindings source is disposed.`);this.#i=ge(e,{persistent:!1},(e,t)=>{(t===null||t.toString()===B(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 z(ye(this.filePath),{recursive:!0});try{await ve(this.filePath,`${JSON.stringify(Dl(this.#e),null,2)}\n`,{encoding:`utf8`,flag:`wx`,mode:384})}catch(e){if(!jl(e))throw e}return this.filePath}dispose(){this.#s=!0,this.#a!==void 0&&clearTimeout(this.#a),this.#a=void 0,this.#i?.close(),this.#i=void 0,this.#n.clear()}#l(){this.#s||(this.#a!==void 0&&clearTimeout(this.#a),this.#a=setTimeout(()=>{this.#a=void 0,this.#u()},10))}async#u(){let e;try{e=await _e(this.filePath,`utf8`)}catch(e){if(Al(e))return;this.#d({file:this.filePath,path:`$`,message:Nl(e)});return}let t=kn(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 Al(e){return Ml(e)&&e.code===`ENOENT`}function jl(e){return Ml(e)&&e.code===`EEXIST`}function Ml(e){return e instanceof Error&&`code`in e}function Nl(e){return e instanceof Error?e.message:String(e)}function Pl(e){return new kl(e)}export{ll as TuiInteractionChannel,El as createDefaultTuiCliAdapter,Pl as createNodeKeybindingsSource,cc as createThemeCataloguePort,ac as createThemeRegistry,lt as escapeThemeText,Ee as listBuiltInThemes,St as parseThemeDocument,ct as quoteThemeText,fl as renderApp,Tl as renderSupervisedSessionView,ut as sanitizeThemeProse};
30
+ _(interrupted)_`:``))}):T(H,{wrap:`wrap`,children:n})})]})});function La({entry:e}){let t=G(),n=va(),r=e.data,a=r?.tools,o=r?.summary?.split(`
31
+ `)??[];return a&&a.length>0?E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(Na,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),T(H,{children:` `}),a.map((e,r)=>{let a=Ca(e,Vi(e)?.status===`error`);return E(i,{flexDirection:`column`,children:[E(H,{color:At(t,a),children:[` `,wa(e,a,n)]}),T(Ta,{tool:e}),e.diffLines&&e.diffLines.length>0&&T(Aa,{file:e.diffFile,lines:e.diffLines})]},r)})]}):E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(Na,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),T(H,{children:` `}),o.map((e,n)=>E(H,{color:t.text.success,children:[` `,V(e)]},n))]})}function Ra({entry:e}){let t=G(),n=e.data,r=typeof n?.message==`string`?n.message:typeof n?.content==`string`?n.content:void 0;if(r===void 0)return T(w,{});let a=V(r);return E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(Na,{kind:`warning`,text:`System: `,color:t.text.warning})}),T(H,{children:` `}),T(i,{marginLeft:2,children:T(H,{wrap:`wrap`,children:a})})]})}function za({entry:e}){if(e.category===`chat`){let t=e.data;return T(Ia,{message:t})}return e.type===`tool-summary`?T(La,{entry:e}):e.type===`usage-summary`?T(ja,{entry:e}):e.type===`tool-start`||e.type===`tool-end`?T(w,{}):T(Ra,{entry:e})}const Ba=[{keys:`↑↓`,label:`Navigate`},{keys:`Enter`,label:`Select`},{keys:`Esc`,label:`Cancel`}];function Va({items:e,renderItem:t,onSelect:n,onCancel:r,maxVisible:a=3,footerHints:o=Ba,initialIndex:s=0}){let[c,l]=C(()=>{let t=s>=0&&s<e.length?s:0;return{...tn(t),scrollOffset:Math.max(0,t-a+1)}}),u=S(c),d=_(t=>{let i=an(u.current,t,{itemCount:e.length,maxVisible:a});if(u.current=i.state,l(i.state),i.effect.type===`cancel`)r();else if(i.effect.type===`select`){let t=e[i.effect.index];t!==void 0&&n(t)}},[e,a,r,n]),f=W(),p=pn({enabled:f&&e.length>0,itemCount:e.length,cancellable:!0,onSelect:t=>{let r=e[t];r!==void 0&&n(r)},onCancel:r});Z(`list-picker`,e=>e.forEach(d),{isActive:!f});let m=X(`list-picker`,[[[`previous`,`next`],`Navigate`],[`select`,`Select`],[`cancel`,`Cancel`]]);if(e.length===0)return T(i,{});if(f){let n=Hn(e.length,!0);return E(i,{flexDirection:`column`,children:[e.map((e,n)=>E(i,{children:[T(H,{children:Un(n)}),t(e,!1)]},n)),E(H,{children:[n,p.buffer.length>0?` ${p.buffer}`:``]}),p.invalid&&T(H,{children:n})]})}let h=on(c,{itemCount:e.length,maxVisible:a});h!==c&&(u.current=h);let{selectedIndex:g,scrollOffset:v}=h,y=e.slice(v,v+a),b=v+a<e.length;return E(i,{flexDirection:`column`,children:[v>0&&E(H,{dimColor:!0,children:[` ↑ `,v,` more above`]}),y.map((e,n)=>T(i,{marginBottom:1,children:t(e,v+n===g)},v+n)),b&&E(H,{dimColor:!0,children:[` ↓ `,e.length-v-a,` more below`]}),T(J,{hints:o===Ba?m:o})]})}function Ha({label:e,index:t,isCursor:n,isChecked:r,screenReader:i}){let a=G(),o=r?`[x] `:`[ ] `;return i?E(H,{children:[Un(t),o,e]}):E(H,{color:n?a.text.accent:void 0,children:[n?`> `:` `,o,e]})}function Ua(e){let{active:t,itemCount:n,setCursor:r}=e;Z(`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 Wa(e){let t=X(`multi-select`,[[[`previous`,`next`],`Navigate`],[`toggle`,`Toggle`],[`confirm`,e.canConfirm?`Confirm`:`Confirm (min ${e.minSelect})`],[`cancel`,`Cancel`]]);return e.screenReader?T(Wn,{itemCount:e.itemCount,cancellable:!0,buffer:e.numbered.buffer,invalid:e.numbered.invalid}):T(J,{hints:t})}function Ga(e){let t=G(),{title:n,description:r,options:a,cursor:o,selected:s,screenReader:c,numbered:l}=e;return E(i,{flexDirection:`column`,...c?{}:{borderStyle:`round`,borderColor:t.border.attention},paddingX:1,children:[T(H,{color:t.text.warning,bold:!0,children:n}),r!==void 0&&r.length>0&&T(H,{dimColor:!0,children:r}),a.map((e,t)=>T(Ha,{label:e.label,index:t,isCursor:t===o,isChecked:s.has(e.value),screenReader:c},e.value)),T(Wa,{screenReader:c,itemCount:a.length,numbered:l,canConfirm:e.canConfirm,minSelect:e.minSelect})]})}function Ka(e){let{options:t,minSelect:n,maxSelect:r,defaultValues:i,onConfirm:a}=e,[o,s]=C(0),[c,l]=C(()=>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 qa({title:e,description:t,options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o,onCancel:s}){let c=W(),{cursor:l,setCursor:u,selected:d,toggleAt:f,confirmIfAllowed:p}=Ka({options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o}),m=pn({enabled:c,itemCount:n.length,cancellable:!0,multi:!0,onSelect:f,onConfirm:p,onCancel:s});Ua({active:!c,itemCount:n.length,setCursor:u,onToggleAtCursor:()=>f(l),onConfirm:p,onCancel:s});let h=d.size>=r;return T(Ga,{title:e,...t===void 0?{}:{description:t},options:n,cursor:l,selected:d,screenReader:c,canConfirm:h,minSelect:r,numbered:m})}function Ja(){return{value:``,resolved:!1}}function Ya(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`}}:Xa(e,n)}function Xa(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 Za({title:e,description:t,placeholder:n,onSubmit:r,onCancel:a,validate:o,allowEmpty:s=!1,masked:c=!1}){let l=G(),[u,d]=C(()=>Ja()),f=S(u),p=_(e=>{let t=Ya(f.current,e,{allowEmpty:s,validate:o});f.current=t.state,d(t.state),t.effect.type===`cancel`?a():t.effect.type===`submit`&&r(t.effect.value)},[s,o,a,r]),m=W();Z(`text-prompt`,(e,t,n,r)=>{for(let t of e)t===`submit`?p({type:`submit`}):t===`cancel`?p({type:`cancel`}):t===`delete-backward`&&p({type:`delete`});e.length===0&&!r&&t&&n.ctrl!==!0&&n.meta!==!0&&p({type:`insert`,value:t})});let h=X(`text-prompt`,[[`submit`,`Submit`],[`cancel`,`Cancel`]]);return E(i,{flexDirection:`column`,...m?{}:{borderStyle:`round`,borderColor:l.border.attention},paddingX:1,children:[T(H,{color:l.text.warning,bold:!0,children:e}),T(Qa,{description:t}),E(i,{marginTop:1,children:[T(H,{color:l.text.accent,children:`> `}),u.value?T(H,{children:c?`*`.repeat(u.value.length):u.value}):n?T(H,{dimColor:!0,children:n}):null,T(H,{color:l.text.accent,children:`█`})]}),u.error&&T(H,{color:l.text.error,children:u.error}),T(J,{hints:h})]})}function Qa({description:e}){return e===void 0||e.length===0?null:T(H,{dimColor:!0,children:e})}const $a={value:``,label:`Type a custom answer…`};function eo({request:e,onAnswer:t}){let n=G(),[r,a]=C(!1),o=e.options??[],s=o.length>0,c=e.maxSelect??1,l=()=>t({type:`cancelled`});if(!s||r)return T(Za,{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?()=>a(!1):l},`text:${e.id}`);if(c>1)return T(qa,{title:e.title,description:e.description,options:o,minSelect:e.minSelect??1,maxSelect:c,defaultValues:e.default?.values,onConfirm:e=>t({type:`answer`,values:e}),onCancel:l});let u=e.allowFreeText?[...o,$a]:[...o],d=e.default?.values?.[0],f=d===void 0?0:Math.max(0,u.findIndex(e=>e.value===d));return E(i,{flexDirection:`column`,children:[T(H,{bold:!0,children:e.title}),e.description!==void 0&&e.description.length>0&&T(H,{dimColor:!0,children:e.description}),T(Va,{items:u,initialIndex:f,maxVisible:e.maxVisible,renderItem:(e,t)=>E(H,{color:t?n.text.accent:void 0,children:[t?`> `:` `,e.label]}),onSelect:e=>{e===$a?a(!0):t({type:`answer`,values:[e.value]})},onCancel:l})]})}const to=[`Allow [y]`,`Allow always (this session) [s]`,`Allow always (this project) [p]`,`Deny [n]`];function no(e,t=!0){return[to[0],`Allow ${e} always (this session) [s]`,t?`Allow ${e} always (this project) [p]`:`Project-wide approval unavailable`,to[3]]}function ro(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`}}:ao(e,t.index);let r=an(e,t,{itemCount:to.length});return r.effect.type!==`select`||r.effect.index===2&&!n?{state:r.state,effect:{type:`none`}}:{state:r.state,effect:{type:`resolve`,decision:io(r.effect.index)}}}function io(e){return e===0?!0:e===1?`allow-session`:e===2&&`allow-project`}function ao(e,t){return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`resolve`,decision:io(t)}}}function oo(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 so({request:e,armDelayMs:t=450}){let n=G(),r=e.canPersistProjectPermission!==!1,[a,o]=h.useState(()=>tn()),s=h.useRef(a),c=h.useRef(e);if(c.current!==e){c.current=e;let t=tn();s.current=t,o(t)}let[l,u]=h.useState();h.useEffect(()=>{if(t<=0)return;let n=setTimeout(()=>u(e),t);return()=>clearTimeout(n)},[e,t]);let d=t<=0||l===e,f=h.useCallback(t=>{let n=ro(s.current,t,r);s.current=n.state,o(n.state),n.effect.type===`resolve`&&e.resolve(n.effect.decision)},[e,r]),p=W(),m=no(ae(e.toolName,e.toolArgs),r),g=pn({enabled:p&&d,itemCount:m.length,onSelect:t=>{let n=ro(s.current,{type:`shortcut`,index:t},r);s.current=n.state,o(n.state),n.effect.type===`resolve`&&e.resolve(n.effect.decision)}}),_=g.clear;h.useEffect(()=>_(),[e,_]),Z(`permission-prompt`,e=>{if(!d)return;let t={"allow-once":0,"allow-session":1,"allow-project":2,deny:3};for(let n of e)n in t?f({type:`shortcut`,index:t[n]}):(n===`previous`||n===`next`||n===`confirm`)&&f(n===`confirm`?`select`:n)},{isActive:!p});let v=X(`permission-prompt`,[[[`previous`,`next`],`Navigate`],[`confirm`,`Confirm`]]);return p?T(Gn,{title:ya.permissionRequired,description:`${e.toolName} — ${oo(e.toolArgs)}${e.requestedByPeer===void 0?``:` (requested by another session: ${e.requestedByPeer})`}`,options:m,buffer:g.buffer,invalid:g.invalid}):E(i,{flexDirection:`column`,borderStyle:`round`,borderColor:d?n.border.attention:n.border.muted,paddingX:1,children:[E(i,{children:[T(H,{color:n.text.warning,bold:!0,children:`[Permission Required]`}),d?null:T(H,{dimColor:!0,children:` keys answer in a moment`})]}),E(H,{children:[`Tool:`,` `,T(H,{color:n.text.accent,bold:!0,children:e.toolName})]}),E(H,{dimColor:!0,children:[` `,oo(e.toolArgs)]}),e.requestedByPeer===void 0?null:E(H,{color:n.text.warning,children:[`Requested by another session: `,e.requestedByPeer]}),T(i,{marginTop:1,flexDirection:`column`,children:m.map((e,t)=>{let r=d&&t===a.selectedIndex;return T(i,{children:E(H,{color:r?n.text.accent:void 0,bold:r,dimColor:!d,children:[r?`> `:` `,e]})},e)})}),T(J,{hints:v})]})}function co(){return{buffer:``,resolved:!1}}const lo=[`y`,`yes`],uo=[`n`,`no`];function fo(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 lo.includes(t)?{state:{buffer:``,resolved:!0},effect:{type:`select`,index:0}}:uo.includes(t)?{state:{buffer:``,resolved:!0},effect:{type:`select`,index:1}}:{state:{...e,buffer:``},effect:{type:`none`}}}return/^[a-zA-Z]+$/.test(t)?{state:{...e,buffer:e.buffer+t},effect:{type:`none`}}:{state:e,effect:{type:`none`}}}function po(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:typeof t==`string`?an(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=G(),[a,o]=C(()=>tn()),s=S(a),c=_(e=>{let r=po(s.current,e,t.length);s.current=r.state,o(r.state),r.effect.type===`select`&&n(r.effect.index)},[n,t.length]),l=W(),[u,f]=C(co),p=S(u);d((e,t)=>{let r=fo(p.current,e,t);p.current=r.state,f(r.state),r.effect.type===`select`&&n(r.effect.index)},{isActive:l}),Z(`confirm-prompt`,e=>{for(let n of e)n===`choose-yes`&&t.length===2?c({type:`shortcut`,index:0}):n===`choose-no`&&t.length===2?c({type:`shortcut`,index:1}):(n===`previous`||n===`next`||n===`confirm`)&&c(n===`confirm`?`select`:n)},{isActive:!l});let m=X(`confirm-prompt`,[[[`previous`,`next`],`Navigate`],[`confirm`,`Confirm`]]);return l?E(i,{flexDirection:`column`,children:[T(H,{children:e}),E(H,{children:[`Answer y or n and press Enter`,u.buffer.length>0?` ${u.buffer}`:``]})]}):E(i,{flexDirection:`column`,borderStyle:`round`,borderColor:r.border.attention,paddingX:1,children:[T(H,{color:r.text.warning,children:e}),T(i,{marginTop:1,children:t.map((e,t)=>T(i,{marginRight:2,children:E(H,{color:t===a.selectedIndex?r.text.accent:void 0,bold:t===a.selectedIndex,children:[t===a.selectedIndex?`> `:` `,e]})},e))}),T(J,{hints:m})]})}function ho(e,t,n,r,i){let[a,o]=C([]),[s,c]=C(!1),[l,u]=C();return y(()=>{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 go({title:e,items:t,onSelect:n,onBack:r,loading:a,error:o}){let s=G(),[c,l]=C(()=>tn()),u=S(c),d=!a&&!o,f=W(),p=pn({enabled:f&&d,itemCount:t.length,cancellable:!0,onSelect:e=>{let r=t[e];r!==void 0&&n(r.value)},onCancel:r}),m=_(e=>{let i=an(u.current,e,{itemCount:t.length,enabled:d});if(u.current=i.state,l(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)}},[d,t,r,n]);Z(`menu-select`,e=>e.forEach(e=>m(e===`back`?`cancel`:e)),{isActive:!f});let h=X(`menu-select`,[[[`previous`,`next`],`Navigate`],[`select`,`Select`],[`back`,`Back`]]),g=X(`menu-select`,[[`back`,`Back`]]),v=on(c,{itemCount:t.length});v!==c&&(u.current=v);let y=v.selectedIndex;return f?T(Gn,{title:e,options:a||o?[]:t.map(e=>e.label),description:a?`Loading...`:o,cancellable:!0,buffer:p.buffer,invalid:p.invalid}):E(i,{flexDirection:`column`,borderStyle:`round`,borderColor:s.border.attention,paddingX:1,children:[T(H,{color:s.text.warning,bold:!0,children:e}),a&&T(i,{marginTop:1,children:T(H,{dimColor:!0,children:`Loading...`})}),o&&T(i,{marginTop:1,children:T(H,{color:s.text.error,children:o})}),!a&&!o&&T(i,{flexDirection:`column`,marginTop:1,children:t.map((e,t)=>E(i,{children:[E(H,{color:t===y?s.text.accent:void 0,bold:t===y,children:[t===y?`> `:` `,e.label]}),e.hint&&E(H,{dimColor:!0,children:[` `,e.hint]})]},e.value))}),T(J,{hints:a?[]:o?g:h})]})}function _o(e,t){e===`marketplace`?t.push({screen:`marketplace-list`}):e===`installed`&&t.push({screen:`installed-list`})}function vo(e,t){e===`__add__`?t.push({screen:`marketplace-add`}):t.push({screen:`marketplace-action`,context:{marketplace:e}})}function yo(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 bo(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 xo(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 So(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 Co(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 wo({callbacks:e,onClose:t,addMessage:n}){let[r,i]=C([{screen:`main`}]),[a,o]=C(),[s,c]=C(0),l=r[r.length-1]??{screen:`main`},u=_(e=>{i(t=>[...t,e])},[]),d=_(()=>{i(e=>e.length<=1?(t(),e):e.slice(0,-1))},[t]),f=_(e=>{i(n=>{let r=n.slice(0,Math.max(1,n.length-e));return r.length===0?(t(),n):r})},[t]),p=_(e=>{n?.({role:`system`,content:e})},[n]),m=_(()=>{c(e=>e+1)},[]),h=_(e=>o(e),[o]),g={push:_(e=>u({screen:e.screen,context:e.context}),[u]),pop:d,popN:f,notify:p,setConfirm:h,refresh:m},{items:v,loading:y,error:b}=ho(l.screen,l.context?.marketplace,e,s,r.length),x=_(t=>{let n=l.screen,r=l.context;n===`main`?_o(t,g):n===`marketplace-list`?vo(t,g):n===`marketplace-action`?yo(t,r?.marketplace??``,e,g):n===`marketplace-browse`?bo(t,r?.marketplace??``,v,g):n===`marketplace-install-scope`?xo(t,r?.pluginId??``,e,g):n===`installed-list`?So(t,e,g):n===`installed-action`&&Co(t,r?.pluginId??``,e,g)},[l,v,e,u,d,f,p,o,m]),S=_(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 T(mo,{message:a.message,onSelect:e=>{e===0?a.onConfirm():a.onCancel()}});let w=l.screen;return w===`marketplace-add`?T(Za,{title:`Add Marketplace Source`,placeholder:`owner/repo or git URL`,onSubmit:S,onCancel:d,validate:e=>e.includes(`/`)?void 0:`Must be owner/repo or a git URL`}):w===`marketplace-action`?T(go,{title:`Marketplace: ${l.context?.marketplace??``}`,items:[{label:`Browse plugins`,value:`browse`},{label:`Update`,value:`update`},{label:`Remove`,value:`remove`}],onSelect:x,onBack:d},r.length):w===`marketplace-install-scope`?T(go,{title:`Install scope for "${l.context?.pluginId??``}"`,items:[{label:`User scope`,value:`user`},{label:`Project scope`,value:`project`}],onSelect:x,onBack:d},r.length):w===`installed-action`?T(go,{title:`Plugin: ${l.context?.pluginId??``}`,items:[{label:`Uninstall`,value:`uninstall`}],onSelect:x,onBack:d},r.length):T(go,{title:{main:`Plugin Management`,"marketplace-list":`Marketplace`,"marketplace-browse":`Browse: ${l.context?.marketplace??``}`,"installed-list":`Installed Plugins`}[w]??`Plugin Management`,items:{main:[{label:`Marketplace`,value:`marketplace`},{label:`Installed Plugins`,value:`installed`}]}[w]??v,onSelect:x,onBack:d,loading:y,error:b},`${w}-${r.length}-${s}`)}function To({notices:e}){let t=G();return e.length===0?null:T(i,{flexDirection:`column`,paddingX:1,children:e.map(e=>T(H,{color:t.text.muted,children:e.message},e.id))})}function Eo(e){let t=e.startsWith(`session_`)?e.slice(8):e;return t===``?e:t.slice(0,8)}function Do(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 Oo({sessions:e,onSelect:t,onCancel:n}){let r=G();return E(i,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[T(H,{bold:!0,color:r.text.accent,children:`Select a session to resume:`}),T(Va,{items:[...e],renderItem:(e,t)=>{let n=Do(e),i=e.preview?e.preview.slice(0,60)+(e.preview.length>60?`...`:``):``;return E(H,{children:[t?`> `:` `,T(H,{bold:!0,children:e.name??Eo(e.id)}),` `,T(H,{dimColor:!0,children:new Date(e.updatedAt).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}),` `,E(H,{dimColor:!0,children:[`msgs: `,e.messageCount]}),n===null?null:E(w,{children:[` `,T(H,{color:r.text.success,children:n})]}),i?E(w,{children:[`
32
+ `,T(H,{dimColor:!0,children:i})]}):null]})},onSelect:e=>t(e.id),onCancel:n})]})}function ko(e){let t=Ao(e),n=e.hasPendingPrompt&&t.kind!==`queued`?[`queued`]:[],r=[t.label,...n].join(` · `);return{...t,segments:n,text:r}}function Ao(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 jo=` | `;function Mo(e,t){return e>=90?t.text.error:e>=70?t.text.warning:t.text.success}function No({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r}){let i=G(),a=ko({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r});return T(H,{color:i.text[a.tone],bold:a.kind!==`idle`,children:a.text})}function Po({percentage:e,usedTokens:t,maxTokens:n}){return E(H,{color:Mo(e,G()),children:[`Context: `,Math.round(e),`% (`,P(t),`/`,P(n),` tokens)`]})}function Fo(){return T(H,{color:G().text.warning,bold:!0,children:`Observing — read only`})}function Io({permissionMode:e}){return E(w,{children:[T(H,{color:G().text.accent,bold:!0,children:`Mode:`}),` `,T(H,{children:e})]})}function Lo(e,t){return t||e!=="default"}function Ro({activePresetId:e}){return E(w,{children:[T(H,{color:G().text.accent,bold:!0,children:`Preset:`}),` `,T(H,{children:e})]})}function zo(e){return e!==void 0&&e!=="default"}function Bo({modelName:e,providerDisplayName:t,effort:n}){return E(H,{dimColor:!0,children:[t===void 0?e:`${t} ${e}`,n===void 0?``:` Effort: ${n}`]})}function Vo(e){let t=G(),n=e.showGitBranch&&e.gitBranch!==void 0&&e.gitBranch.length>0,r=W(),i=Lo(e.permissionMode,r),a=e.activePresetId,o=zo(a);return E(H,{children:[e.readOnly&&E(w,{children:[T(Fo,{}),!r&&jo]}),!r&&T(No,{isThinking:e.isThinking,activeToolCount:e.activeToolCount,activeBackgroundTaskCount:e.activeBackgroundTaskCount,hasPendingPrompt:e.hasPendingPrompt}),i&&E(w,{children:[jo,T(Io,{permissionMode:e.permissionMode})]}),o&&E(w,{children:[jo,T(Ro,{activePresetId:a})]}),e.sessionName&&E(w,{children:[jo,T(H,{color:t.text.session,children:e.sessionName})]}),n&&E(w,{children:[jo,E(H,{dimColor:!0,children:[`git: `,e.gitBranch]})]}),jo,T(Bo,{modelName:e.modelName,providerDisplayName:e.providerDisplayName,effort:e.effort}),!r&&E(w,{children:[jo,T(Po,{percentage:e.contextPercentage,usedTokens:e.contextUsedTokens,maxTokens:e.contextMaxTokens})]})]})}function Ho({permissionMode:e,modelName:t,providerDisplayName:n,sessionId:r,isThinking:a,activeToolCount:o=0,activeBackgroundTaskCount:s=0,hasPendingPrompt:c=!1,contextPercentage:l,contextUsedTokens:u,contextMaxTokens:d,sessionName:f,gitBranch:p,showGitBranch:m=!0,activeAgentLabel:h,activePresetId:g,effort:_,readOnly:v=!1}){let y=G();return E(i,{paddingLeft:1,paddingRight:1,justifyContent:`space-between`,children:[T(Vo,{permissionMode:e,modelName:t,providerDisplayName:n,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextPercentage:l,contextUsedTokens:u,contextMaxTokens:d,sessionName:f,gitBranch:p,showGitBranch:m,activePresetId:g,effort:_,readOnly:v}),h!==void 0&&E(H,{color:y.text.warning,bold:!0,children:[`[`,h,`]`]})]})}const Uo=g(null),Wo=Uo.Provider;function Go(){let e=v(Uo);if(!e)throw Error(`TuiCliAdapterContext not provided`);return e}function Ko({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 _=Go(),v=x(()=>_.getGitBranch(e),[_,e,h]),y=x(()=>r===void 0?void 0:_.getProviderDisplayName(r),[_,r]);return d.enabled?T(Ho,{permissionMode:t,modelName:n??``,providerDisplayName:y,sessionId:i,isThinking:a,activeToolCount:o,activeBackgroundTaskCount:s,hasPendingPrompt:c,contextPercentage:l.percentage,contextUsedTokens:l.usedTokens,contextMaxTokens:l.maxTokens,sessionName:u,gitBranch:v,showGitBranch:d.gitBranch,activeAgentLabel:f,activePresetId:p,effort:m,readOnly:g}):g?T(Fo,{}):null}function qo(e,t){let n=jt(e);return{color:At(t,n),icon:kt[n],strikethrough:n===`error`||n===`denied`}}function Jo({isThinking:e}){let t=G();return e?T(i,{marginBottom:1,children:T(H,{color:t.text.warning,children:`Thinking...`})}):T(w,{})}function Yo({activeTools:e}){let t=G(),n=va();return E(i,{flexDirection:`column`,marginBottom:1,children:[T(H,{color:t.text.emphasis,bold:!0,children:`Tools:`}),T(H,{children:` `}),e.map((e,r)=>{let{color:a,icon:o,strikethrough:s}=qo(e,t);return E(i,{flexDirection:`column`,children:[E(H,{color:a,strikethrough:s,children:[` `,o,` `,fa(e.toolName,n),`(`,pa(e.firstArg),`)`]}),e.diffLines&&e.diffLines.length>0&&T(Aa,{file:e.diffFile,lines:e.diffLines})]},`${e.toolName}-${r}`)})]})}function Xo(e,t,n,r){let i=t.map(e=>fa(e.toolName,r)).join(`, `),a=[i.length>0?`${ya.tool} ${i}`:void 0,e.length>0?e:n?ya.thinking:void 0].filter(e=>e!==void 0);return a.length===0?T(w,{}):T(H,{children:a.join(` — `)})}function Zo({text:e,activeTools:t,isThinking:n=!1}){let r=G(),a=ua(),o=t.length>0,s=e.length>0,c=W(),l=_a(),u=va();return c?Xo(e,t,n,u):!o&&!s?T(Jo,{isThinking:n}):E(i,{flexDirection:`column`,children:[o&&T(Yo,{activeTools:t}),s&&E(i,{flexDirection:`column`,marginBottom:1,children:[E(H,{color:r.text.accent,bold:!0,children:[l,`:`]}),T(H,{children:` `}),T(i,{marginLeft:2,children:T(Ee,{wrap:`wrap`,children:a(e)})})]})]})}function Qo(e,t){let n=t?` (current)`:``;return`${e.name} — ${e.appearance}, ${e.source}${n}`}function $o({theme:e,isFocused:t,isActive:n,rowNumber:r}){let i=G(),a=r===void 0?t?`> `:` `:Un(r);return E(H,{...t&&r===void 0?{color:i.text.accent,bold:!0}:{},children:[a,Qo(e,n)]})}function es({itemCount:e,buffer:t,invalid:n}){let r=Hn(e,!0);return E(i,{flexDirection:`column`,children:[E(H,{children:[r,t.length>0?` ${t}`:``]}),n&&T(H,{children:r})]})}function ts(e,t){let n=e.findIndex(e=>e.id===t);return n<0?0:n}function ns(e){let[t,n]=h.useState(()=>({syntaxHighlighting:e.syntaxHighlighting,reducedMotion:e.reducedMotion}));return{toggles:t,setToggles:n}}function rs(e){let{themes:t,activeThemeId:n,preview:r}=e,[i,a]=h.useState(()=>ts(t,n));return{focusedIndex:i,move:h.useCallback(e=>{t.length!==0&&a(n=>{let i=(n+e+t.length)%t.length,a=t[i];return a&&r(a.id),i})},[r,t])}}function is(e,t){let{themes:n,select:r,cancel:i}=e,{focusedIndex:a,move:o}=rs(e),{toggles:s,setToggles:c}=ns(e),l=h.useRef(s);l.current=s;let u=h.useCallback(e=>{let t=n[e];t&&r(t.id,l.current)},[r,n]),d=pn({enabled:t&&n.length>0,itemCount:n.length,cancellable:!0,onSelect:u,onCancel:i}),f=h.useCallback(e=>{c(t=>({...t,[e]:!t[e]}))},[c]);return Z(`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 as({themes:e,activeThemeId:t,focusedIndex:n,screenReader:r}){return e.length===0?T(H,{dimColor:!0,children:`No themes installed`}):T(w,{children:e.map((e,i)=>T($o,{theme:e,isFocused:i===n,isActive:e.id===t,...r?{rowNumber:i}:{}},e.id))})}function os(){return Ne()?T(w,{}):T(H,{dimColor:!0,children:`Colour is off for this terminal — themes apply, previews cannot show.`})}function ss({skipped:e}){return e.length===0?T(w,{}):T(i,{flexDirection:`column`,marginTop:1,children:e.map((e,t)=>T(H,{dimColor:!0,children:` Skipped "${e.fileName}" — ${e.reason}`},t))})}function cs({toggles:e,reducedMotionPin:t,screenReader:n}){let r=e=>e?`on`:`off`,a=t===void 0?``:` (this run: motion ${r(!t.reducedMotion)}, pinned by ${t.tier})`;return E(i,{flexDirection:`column`,children:[T(H,{dimColor:!0,children:`syntax ${r(e.syntaxHighlighting)} · motion ${r(!e.reducedMotion)}${a}`}),n&&T(H,{dimColor:!0,children:`Change with /theme syntax on|off or /theme motion on|off`})]})}function ls({screenReader:e,itemCount:t,numbered:n}){let r=X(`theme-picker`,[[[`previous`,`next`],`Preview`],[`select`,`Apply`],[`toggle-syntax`,`Syntax`],[`toggle-motion`,`Motion`],[`cancel`,`Cancel`]]);return e?T(es,{itemCount:t,buffer:n.buffer,invalid:n.invalid}):T(J,{hints:r})}function us({picker:e}){let t=G(),n=W(),{themes:r,activeThemeId:a}=e,{focusedIndex:o,toggles:s,numbered:c}=is(e,n);return E(i,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.focused},paddingX:1,children:[T(H,{color:t.text.accent,bold:!0,children:`Theme`}),T(os,{}),T(cs,{toggles:s,reducedMotionPin:e.reducedMotionPin,screenReader:n}),T(i,{flexDirection:`column`,marginTop:1,children:T(as,{themes:r,activeThemeId:a,focusedIndex:o,screenReader:n})}),T(ss,{skipped:e.skipped}),T(ls,{screenReader:n,itemCount:r.length,numbered:c})]})}function ds({entry:e,selected:t}){let n=G(),r=e.config.enabled,a=r?`●`:`○`,o=r?`[on] `:`[off]`,s=e.config.options?.port,c=typeof s==`number`?`port: ${s}`:``;return T(i,{children:T(H,{color:t?n.text.accent:void 0,bold:t,children:`${a} ${e.transport.name.padEnd(18)} ${o} ${c}`})})}function fs(e,t,n,r,i,a,o,s,c){Z(`transport-settings`,_(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 ps({registry:e,onClose:t}){let n=G(),r=_a(),[a,o]=C(()=>e.getAll()),[s,c]=C(0),[l,u]=C(!1),[d,f]=C(void 0),p=_(()=>{o(e.getAll())},[e]),m=X(`transport-settings`,[[[`previous`,`next`],`Select`],[`toggle`,`Toggle`],[`close`,`Close`]]);return fs(a,s,l,e,c,u,f,t,p),E(i,{flexDirection:`column`,paddingX:2,paddingY:1,children:[T(H,{bold:!0,children:`Settings › Transports`}),T(i,{marginTop:1,flexDirection:`column`,children:a.map((e,t)=>T(ds,{entry:e,selected:t===s},e.transport.name))}),E(i,{marginTop:1,flexDirection:`column`,children:[T(J,{hints:m}),E(H,{dimColor:!0,children:[`A toggle is saved now and applies the next time `,r,` starts.`]})]}),l&&T(i,{marginTop:1,children:T(H,{color:n.text.warning,children:`Saving…`})}),d!==void 0&&T(i,{marginTop:1,children:T(H,{color:n.text.error,children:`Not saved — ${d}`})})]})}function ms({message:e}){return T(i,{paddingX:1,marginBottom:1,children:T(H,{color:G().text.warning,children:e})})}function hs({model:e}){return T(a,{items:e.staticItems,children:e=>e.kind===`banner`?T(Et,{version:e.version},`logo`):T(za,{entry:e.entry},e.entry.id)},e.transcriptKey)}function gs({model:e}){let t=G(),{background:n,stream:r}=e;return E(i,{flexDirection:`column`,paddingX:1,flexGrow:1,children:[n.selectedEntry&&n.selectedEntry.kind!==`main_thread`&&T($t,{entry:n.selectedEntry,page:n.detail.page,loading:n.detail.loading,error:n.detail.error}),e.isShuttingDown&&T(H,{color:t.text.warning,children:`Shutting down...`}),(r.isThinking||r.activeTools.length>0)&&E(i,{flexDirection:`column`,marginBottom:1,children:[T(Zo,{text:r.text,activeTools:r.activeTools,isThinking:r.isThinking}),r.isStalled&&T(H,{color:t.text.warning,children:`⚠ Still waiting on the provider — the network may be stalled. Esc to interrupt.`})]}),!r.isThinking&&r.lastErrorMessage&&T(H,{color:t.text.error,children:`✖ Last turn failed — the session is alive; type your next prompt when ready.`}),T(Zt,{entries:n.entries,focusedIndex:n.focusedIndex})]})}function _s({model:e}){if(e.coordinationError!==void 0||e.coordinationPending)return T(w,{});let{background:t,plugin:n,sessionPicker:r,transport:i}=e,a=e.pendingUserAction;return E(w,{children:[t.switcherVisible&&T(qn,{snapshot:t.snapshot,selectedEntryId:t.selectedEntryId,onSelect:t.select,onClose:t.closeSwitcher,onAttach:t.attachToFork}),e.permissionRequest&&T(so,{request:e.permissionRequest}),a&&T(eo,{request:a,onAnswer:t=>e.resolveUserAction(a,t)}),n.visible&&T(wo,{callbacks:n.callbacks,onClose:n.close,addMessage:e=>n.addMessage(e.content)}),i.visible&&i.registry&&T(ps,{registry:i.registry,onClose:i.close}),r.visible&&T(Oo,{sessions:r.sessions,onSelect:r.select,onCancel:r.cancel}),e.theme.picker.visible&&T(us,{picker:e.theme.picker})]})}function vs({model:e}){let{input:t}=e;return E(w,{children:[T(Qt,{percentage:e.contextPercentage}),T(zi,{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}),T(Ko,{...e.status})]})}function ys({viewModel:e}){let t=G(),n=Vn();return E(i,{flexDirection:`column`,children:[T(hs,{model:e}),!e.handoffSuspended&&E(w,{children:[e.updateNotice&&T(ms,{message:e.updateNotice}),e.coordinationError&&E(H,{color:t.text.error,children:[e.coordinationError,` Press Enter to retry.`]}),n.diagnostic&&T(H,{color:t.text.error,children:`Keybindings ${n.diagnostic.file} ${n.diagnostic.path}: ${n.diagnostic.message} Last valid bindings remain active.`}),n.warnings.map(e=>T(H,{color:t.text.warning,children:`Keybindings ${e.path}: ${e.message}`},`${e.path}:${e.code}`)),e.theme.unknownThemeNotice!==void 0&&T(H,{color:t.text.warning,children:e.theme.unknownThemeNotice}),T(To,{notices:e.sessionEventNotices}),T(gs,{model:e}),T(_s,{model:e}),T(vs,{model:e})]})]})}function bs(e){return[...e.screenReader?[]:[{kind:`banner`,version:e.version??`0.0.0`}],...e.history.map(e=>({kind:`entry`,entry:e}))]}function xs(e){let t=e.forceExit??(e=>process.exit(e));if(e.isShuttingDown){t(130);return}e.graceful()}function Ss(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 Cs={promptStart:`A`,promptEnd:`B`,turnStart:`C`,turnEnd:`D`};function ws(e){return`\x1b]133;${Cs[e]}\x07`}function Ts(e){let t=e.write??(e=>{process.stdout.write(e)});return{emit(n){!e.enabled||!e.supported()||t(ws(n))}}}function Es(e,t){return e.executionId??`${e.toolName}#${t}`}function Ds(e){let t=new Set;return e.forEach((e,n)=>{e.isRunning&&t.add(Es(e,n))}),t}function Os(e){let{enabled:t,isThinking:n,activeTools:r,awaitingAnswer:i}=e,a=x(()=>Ss({enabled:t}),[t]),o=Or(),s=jr(),c=x(()=>Ts({enabled:t,supported:()=>Fe({override:s.turnMarks}),write:e=>o.write(e)}),[t,o,s.turnMarks]),l=S(!1),u=S(new Set);y(()=>{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]),y(()=>{c.emit(`promptStart`)},[c]),y(()=>{i&&a.promptMounted()},[i,a]),y(()=>{let e=Ds(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 ks(e){return!!(e.permissionRequest||e.pendingUserAction||e.pluginVisible||e.transportVisible||e.sessionPickerVisible||e.workspaceSwitcherVisible||e.historySearchOpen||e.themePickerVisible||e.coordinationBlocked)}function As(e){Z(e.isThinking?`thinking`:`background-detail`,t=>{if(ks(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 js(e){Z(`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 Ms(e){Z(`recovery`,t=>{e.recoveryError!==void 0&&!e.recoveryPending&&t.includes(`retry`)&&e.retryRecovery()})}function Ns(e,t){return e===``||t&&e===`]`}function Ps(e){let{exit:t}=c(),n=n=>{xs({isShuttingDown:e.isShuttingDown,graceful:()=>void e.shutdown(n).finally(()=>t())})};d((t,r)=>{(r.ctrl&&t===`c`||e.attached&&Ns(t,r.ctrl))&&n(`prompt_input_exit`)}),y(()=>{let e=()=>n(`other`);return process.on(`SIGINT`,e),process.on(`SIGTERM`,e),()=>{process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}})}function Fs(e){As(e),Ms(e),js(e),Ps(e);let t=W();return Os({enabled:t,isThinking:e.isThinking,activeTools:e.activeTools,awaitingAnswer:e.permissionRequest!==null||e.pendingUserAction!==null}),t}function Q(){return Promise.reject(Error(`Plugin management is unavailable in this host.`))}function Is(){return{listInstalled:Q,listAvailablePlugins:Q,install:Q,uninstall:Q,enable:Q,disable:Q,marketplaceAdd:Q,marketplaceRemove:Q,marketplaceUpdate:Q,marketplaceList:Q,reloadPlugins:Q}}function Ls(e){return e??Is()}function Rs(e){return x(()=>Ls(e),[e])}function zs(e){let t=Rs(e.pluginAdapter),n=_(t=>e.addEntry(F(j(t))),[e.addEntry]),r=_(t=>{e.setSessionPickerVisible(!1),e.onSessionSwitch(t)},[e.onSessionSwitch,e.setSessionPickerVisible]),i=_(()=>{e.setSessionPickerVisible(!1),e.addEntry(F(j(`Session resume cancelled.`)))},[e.addEntry,e.setSessionPickerVisible]),a=e.hostSessions??le(e.sessionStore,e.cwd),o=e.sessionPickerVisible&&a.length===0;return y(()=>{o&&(e.setSessionPickerVisible(!1),e.addEntry(F(j(`No saved sessions to resume in this workspace.`))))},[o,e.addEntry,e.setSessionPickerVisible]),{plugin:{visible:e.pluginVisible,callbacks:t,close:()=>e.setPluginVisible(!1),addMessage:n},transport:{visible:e.transportVisible,registry:e.transportRegistry,close:()=>e.setTransportVisible(!1)},sessionPicker:{visible:e.sessionPickerVisible&&!o,sessions:a,select:r,cancel:i}}}function Bs(e){let[t,n]=C(0),r=_(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=_(async e=>{n(e=>e+1),await r(e)},[r]),a=S(!1);return y(()=>{a.current&&!e.isThinking&&n(e=>e+1),a.current=e.isThinking},[e.isThinking]),{submit:i,gitRefreshToken:t}}function Vs(e){let{screens:t,workspace:n}=e.shell,r=Bs({selectedEntry:n.background.selectedEntry,submit:t.handleSubmit,sendAgentJob:e.state.sendAgentJob,isThinking:e.state.isThinking}),i=Fs({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:zs({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 Hs(e){let t=_a();y(()=>{let n=V(e??``),r=V(t),i=n?`${r} — ${n}`:r;process.stdout.write(`\x1b]0;${i}\x07`)},[e,t])}function Us(e){let[t,n]=C(!1);return y(()=>{if(e)return e.registerSuspendHooks({suspend:async()=>{n(!0),await new Promise(e=>setTimeout(e,50))},resume:()=>n(!1)})},[e]),t}function Ws(e){let[t,n]=C(),[r,i]=C(!0),a=_(()=>{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 y(()=>{a()},[e,a]),{startError:t,startPending:r,retryStart:a}}function Gs(e){let[t,n]=C();return y(()=>{let t=!0;return e?.then(e=>{t&&e!==void 0&&n(e)}).catch(()=>{}),()=>{t=!1}},[e]),t}function Ks(e,t){let n=Ws(e),[r,i]=C(e.sessionName);return y(()=>{e.sessionName!==void 0&&e.sessionName!==r&&i(e.sessionName)},[e,e.sessionName,r]),Hs(r),{sessionName:r,setSessionName:i,handoffSuspended:Us(e.terminalHandoffController),updateNotice:Gs(t),...n}}function qs(e){return ue(e.readSettings(e.getUserSettingsPath()))}function Js(){let e=Go(),[t,n]=C(()=>qs(e));return[t,_(()=>{n(qs(e))},[e])]}function Ys(e){let[t,n]=C(null),[r,i]=C(),[a,o]=C(!1),{entry:s,snapshot:c,read:l}=e;return y(()=>{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 Xs(e,t){let n=de(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 Zs({sessionStore:e,onSessionSwitch:t,addEntry:n}){let r=Go();return _(i=>{let a=e=>n(F(j(e)));if(e===void 0){a(`This surface has no session store, so it cannot attach to a forked session.`);return}Xs(i,{hasSessionRecord:t=>e.load(t).status===`valid`,switchSession:t,notify:a,...r.formatResumeCommand===void 0?{}:{formatResumeCommand:r.formatResumeCommand}})},[n,r,t,e])}function Qs(e){let{snapshot:t,selectedEntryId:n}=e,r=x(()=>t?.entries.find(e=>e.id===n),[t,n]);return{entry:r,detail:Ys({entry:r,snapshot:t,read:e.read}),attachToFork:Zs({sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.addEntry})}}function $s(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 ec(e,t,n,r,i){Z(`background-list`,i=>{if(e===null)return;let a=$s(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 tc(e,t,n){let[r,i]=C(null);return y(()=>{i(t=>t===null||e.length===0?null:Math.min(t,e.length-1))},[e.length]),ec(r,e,i,t,n),{focusedIndex:r,focusList:_(()=>{e.length>0&&i(0)},[e.length])}}function nc(e){return{open:_(()=>e(!0),[e]),toggle:_(()=>e(e=>!e),[e]),close:_(()=>e(!1),[e])}}function rc(e){let t=x(()=>It(e.snapshot),[e.snapshot]),{focusedIndex:n,focusList:r}=tc(t.map(e=>e.id),e.select,e.navigationEnabled),i=Qs({selectedEntryId:e.selectedEntryId,snapshot:e.snapshot,read:e.read,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,addEntry:e.addEntry}),a=nc(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:Lt(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 ic(e,t,n){let r=e=>{if(e.requesterDriverId===I)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 ac(e){let t=S(e);return t.current=e,t}function oc({uiEventPort:e,baseHandleSubmit:t,setSessionName:n,refreshStatusLineSettings:r,refreshAppearanceSettings:i,showSessionPickerOnStart:a,openAgentSwitcher:o}){let[s,c]=C(!1),[l,u]=C(a??!1),[d,f]=C(!1),[p,m]=C(!1),h=ac({setSessionName:n,refreshStatusLineSettings:r,refreshAppearanceSettings:i,openAgentSwitcher:o});return b(()=>ic(e,{setShowPluginTUI:c,setShowTransportTUI:f,setShowSessionPicker:u,setShowThemePicker:m},h),[e]),{handleSubmit:_(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 sc(e){let t={...te},n=e.statusline;return cc(n)?{enabled:typeof n.enabled==`boolean`?n.enabled:t.enabled,gitBranch:typeof n.gitBranch==`boolean`?n.gitBranch:t.gitBranch}:t}function cc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function lc(e){return sc(e.readSettings(e.getUserSettingsPath()))}function uc(){let e=Go(),[t,n]=C(()=>lc(e));return[t,_(()=>{n(lc(e))},[e])]}function dc(e){let[t,n]=C(!1),[r,i]=C(!1),[a,o]=uc(),[s,c]=Js(),l=oc({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:rc({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 fc(e=Ae(),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===ke)return{theme:je(n.get(ke))};let t=n.get(e);return t?{theme:t}:{theme:je(n.get(ke)),unknownId:e}}}}function pc(e){return`Theme "${e}" is not installed — using "${ke}".`}function mc(e){return{id:e.id,name:e.name,appearance:e.appearance,source:e.source}}function hc(e){return{listThemes:()=>e.registry.list().map(mc),getTheme:t=>{let n=e.registry.get(t);return n?mc(n):void 0},getAppearance:()=>({settings:e.readAppearance(),...e.reducedMotionPin===void 0?{}:{reducedMotionPin:e.reducedMotionPin}})}}function gc(e){let t=x(()=>e.registry??fc(),[e.registry]),[n,r]=C(void 0),i=x(()=>t.resolve(n??e.appearance.theme),[t,n,e.appearance.theme]),{setVisible:a,submit:o}=e,s=_(()=>{r(void 0),a(!1)},[a]),{syntaxHighlighting:c,reducedMotion:l}=e.appearance,u=_((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:pc(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 _c(e){let[,t]=C(0);y(()=>e.subscribe(()=>t(e=>e+1)),[e]);let n=e.getSnapshot(),r=_(t=>e.selectExecutionWorkspaceEntry(t),[e]),i=_(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 vc(e,t){let n=e.sessionSwitchError??t.startError,r=!!(e.sessionSwitchPending||t.startPending);return{error:n,pending:r,blocked:n!==void 0||r}}function yc(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 bc(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:yc(e)}}function xc(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 Sc(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:bc(e),status:xc(e)}}function Cc(e,t){return gc({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 wc(e,t){let[n,r]=C(e);return{initialValue:n,consumeInitialValue:_(()=>r(void 0),[]),externalPromptOrigin:t===`external-link`}}function Tc(e,t,n){return x(()=>bs({history:e,version:t,screenReader:n}),[e,n,t])}function Ec(e){let t=wc(e.initialInput,e.initialInputOrigin),n=_c(e.channel),r=Ks(e.channel,e.startupUpdateNotice),i=vc(e,r),a=dc({state:n,setSessionName:r.setSessionName,sessionStore:e.sessionStore,onSessionSwitch:e.onSessionSwitch,showSessionPickerOnStart:e.showSessionPickerOnStart,coordinationBlocked:i.blocked}),o=Vs({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=Sc({props:e,state:n,lifecycle:r,shell:a,interaction:o,staticItems:Tc(n.history,e.version,o.screenReader),runtime:n.getRuntimeStatusSnapshot(e.permissionMode??`default`),coordination:i,theme:Cc(e,a)});return{...s,input:{...s.input,...t}}}function Dc(e){let t=Ec(e);return T(Be,{theme:t.theme.resolved,reducedMotion:t.theme.reducedMotion,syntaxHighlighting:t.theme.syntaxHighlighting,children:T(ys,{viewModel:t})})}function Oc(e){let[t,n]=C(()=>({channel:e.createChannel(e.resumeSessionId),sessionId:e.resumeSessionId})),[r,i]=C(e.showSessionPickerOnStart??!1),[a,o]=C(),[s,c]=C(!1),[l,u]=C(),d=S(!1),f=S(!0);y(()=>()=>{f.current=!1},[]);let p=_(async r=>{if(!d.current){d.current=!0,c(!0);try{if(i(!1),e.requestSessionSwitch)await e.requestSessionSwitch(r);else{if(await t.channel.stop(),!f.current)return;n({channel:e.createChannel(r),sessionId:r})}if(!f.current)return;u(void 0),o(void 0)}catch(e){let t=e instanceof Error?e.message:String(e);o(`Session switch failed: ${t}`),u(r)}finally{d.current=!1,c(!1)}}},[e.createChannel,e.requestSessionSwitch,t.channel]);return{state:t,showPicker:r,error:a,switching:s,switchSession:p,retrySwitch:_(()=>{l!==void 0&&p(l)},[l,p])}}function kc(e){let t=Oc(e);return T(Wo,{value:e.cliAdapter,children:T(Dc,{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 Ac=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 Mc=class extends ve{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 Nc(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 Pc(e,t=e=>{process.stdout.write(e)}){let n=Nc(e);n!==void 0&&t(`${n}\n`)}function Fc(e){return e??(e=>{process.stderr.write(`${e}\n`)})}function Ic(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 Lc(e){if(!e.enabled)return{startupQuietMs:0,preparkMs:0};let t=Fc(e.warn);return{startupQuietMs:Ic(e.overrides?.startupQuiet?.raw,e.overrides?.startupQuiet?.label??`startup quiet period`,900,6e5,t),preparkMs:Ic(e.overrides?.prepark?.raw,e.overrides?.prepark?.label??`pre-write park`,50,5e3,t)}}function Rc(e){return e?.isTTY!==!0||typeof e.setRawMode!=`function`?()=>{}:(e.setRawMode(!0),()=>{e.setRawMode?.(!1)})}async function zc(e,t){if(e<=0)return`elapsed`;let n=Rc(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 Bc(e){return typeof e==`string`?e:Buffer.from(e).toString(`utf8`)}function Vc(e){return V(e).trim().length>0}var Hc=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=Bc(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&&Vc(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 Uc(e){return new Hc(e)}function Wc(e){return{armEchoRelease:()=>e.armEchoRelease(),write:t=>{e.write(t)}}}function Gc(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 Kc=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 qc=new Set([`completed`,`failed`,`stopped`]);var Jc=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 Zc(`While away ${Xc(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&&qc.has(n);if(!qc.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} ${Yc(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} ${Yc(this.errorCount,`error`)}`),e}reset(){this.turnsFinished=0,this.wakeTurnsFinished=0,this.needsInputCount=0,this.errorCount=0,this.reachedTerminal.clear()}};function Yc(e,t){return e===1?t:`${t}s`}function Xc(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 Zc(e){return e.length<=120?e:`${e.slice(0,119)}…`}var Qc=class{options;recap=new Jc;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 $c(e){return/not initialized/i.test(e.message)}function el(e){let t=e.isBenignError??$c,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 tl(e,t,n,r,i){if(e.data?.pluginRegistryReloaded===!0&&i?.(n),r.addEntry(F(j(e.message))),t.isInitialized){let e=t.getContextState();r.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})}}function nl(e){let t=e.slice(1).split(/\s+/);return{name:t[0]?.toLowerCase()??``,args:t.slice(1).join(` `)}}var rl=class extends AggregateError{},il=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 rl&&(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)}},al=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()}}},ol=class{onChange;entries=[];processing=!1;currentRequest=null;constructor(e){this.onChange=e}get current(){return this.currentRequest}enqueue(e,t,n,r,i){return new Promise(a=>{this.entries.push({toolName:e,toolArgs:t,resolve:a,...n===void 0?{}:{id:n},...r===void 0?{}:{canPersistProjectPermission:r},...i===void 0?{}:{requestedByPeer:i}}),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},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 sl(e,t){let n=null;try{n=t.getActiveDriverId?.()??null}catch{n=null}return F(M(e,n?{metadata:{driverId:n}}:{}))}function cl(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 ll(e,t,n,r,i){let a=((...e)=>{try{n(...e)}catch(e){let n=e instanceof Error?e:Error(String(e));try{r(n,t)}catch{}}});e.on(t,a),i.push({event:t,handler:a})}var ul=class{options;bindings=[];constructor(e){this.options=e}wire(){if(this.bindings.length>0)return;let{session:e,manager:t,attention:n}=this.options,r=n=>{t.addUserEcho(sl(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)),cl(this.bind.bind(this),t),this.bind(`permission_request`,({id:t,toolName:r,toolArgs:i,canPersistProjectPermission:a,requesterDriverId:o})=>{n?.onNeedsInput();let s=o?.startsWith(`peer:`)?he(o):void 0;this.options.requestPermission(r,i,t,a,s).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){ll(this.options.session,e,t,t=>{let n=this.options.onDeliveryError;n?n(t,e):this.options.manager.addSessionEventDeliveryError(t,e)},this.bindings)}};function dl(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 fl(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 pl=class{sequence=0;notices=[];add(e){this.append(fl(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 ml(e,t){let n=null;return{schedule(){n||=setTimeout(()=>{n=null,e()},t)},flush(){n&&=(clearTimeout(n),null)}}}var hl=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 pl;sessionEventNotices=this.sessionNoticeStore.notices;onChange=null;streamBuf=``;debouncedStreamNotify=ml(()=>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=this.activeTools.findLastIndex(t=>t.toolName===e.toolName&&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 gl(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 _l=15e3;var vl=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 hl,this.stateManager.onChange=()=>this.onChange?.(),this.userActions=new al(()=>this.onChange?.()),this.permissions=new ol(()=>this.onChange?.()),this.interactiveSession=this.createSession(),this.registry=this.createRegistry(),this.attention=this.createAttention(e.attention),this.eventProjector=new ul({session:this.interactiveSession,manager:this.stateManager,...this.attention?{attention:this.attention}:{},requestPermission:(e,t,n,r,i)=>this.permissions.enqueue(e,t,n,r,i),askUser:(e,t)=>this.askUser(e,t),dismissPrompt:e=>this.dismissPromptById(e),...e.onSessionEventDeliveryError?{onDeliveryError:e.onSessionEventDeliveryError}:{}}),this.lifecycle=new il({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(F(j(`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 rl([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 ie(dl(this.opts))}createRegistry(){let e=new ee;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=gl(await this.interactiveSession.stopWaitingSelfPacedLoop(`Loop stopped by Esc`));e!==void 0&&this.addEntry(F(j(e)))}async shutdown(e){await this.lifecycle.shutdown(e)}selectExecutionWorkspaceEntry(e){this.stateManager.selectExecutionWorkspaceEntry(e)}async readExecutionWorkspaceDetail(e){return this.interactiveSession.readExecutionWorkspaceDetail(e)}async sendAgentJob(e,t){await this.interactiveSession.sendAgentJob(e,t)}setSessionName(e){this.sessionName=e,this.interactiveSession.setName(e),this.onChange?.()}async askUser(e,t){return this.userActions.enqueue(e,t)}resolveUserAction(e,t){this.userActions.resolveCurrent(e,t)}cancelAllUserActions(){this.userActions.cancelAll()}async handleInput(e){if(!e.startsWith(`/`)){await this.interactiveSession.submit(e),this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}await this.handleSlashCommand(e)}async handleSlashCommand(e){let{name:t,args:n}=nl(e),r=await this.interactiveSession.executeCommand(t,n);if(r){if(r.data?.sessionExecution===!0){this.stateManager.setPendingPrompt(this.interactiveSession.getPendingPrompt());return}tl(r,this.interactiveSession,this.registry,this.stateManager,this.opts.reloadPluginCommandSource);return}this.stateManager.addEntry(F(j(`Unknown command "/${t}". Type /help for help.`)))}handlePermissionRequest(e,t,n){return this.permissions.enqueue(e,t,n)}dismissPromptById(e){this.userActions.dismissById(e),this.permissions.dismissById(e)}cancelAllPermissions(){this.permissions.cancelAll()}syncRestoredHistory(){if(this.stateManager.history.length===0){let e=this.interactiveSession.getFullHistory();e.length>0&&this.stateManager.syncHistory(e)}}startInitCheck(){this.stopInitCheck(),this.initPoller=el({check:()=>this.runInitCheck(),intervalMs:200,timeoutMs:_l,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 Qc({source:e,onRecap:e=>this.stateManager.addAttentionRecap(e)})}onInitFailure(e){let t=e.kind===`timeout`?`Session initialization timed out after ${_l/Dt}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 yl(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 bl=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&&yl(e,t.content));return r===-1?!0:(e=r+1,!1)})}};const xl=`appearance-settings-patch`;function Sl(e){return e instanceof Error?e.message:String(e)}function Cl(e){return{result:{success:!1,message:e},uiIntents:[]}}function wl(e,t){return e?.commands.find(e=>e.name===t)}async function Tl(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!==xl)return Cl(`Cannot apply '${e.type}' on this terminal.`);if(!se(e.patch))return Cl(`Failed to apply '${xl}': invalid appearance settings patch`);a.push(e.patch)}for(let e of a)try{await r.writeAppearanceSettings(e)}catch(e){return Cl(`Failed to apply '${xl}': ${Sl(e)}`)}return{result:{message:i.message,success:i.success,...i.data===void 0?{}:{data:i.data}},uiIntents:i.uiIntents??[]}}function El(e){let t=new re(e.terminalHandoff),{cwd:n}=e;return{canHandoffTerminal:()=>t.canHandoffTerminal(),runWithTerminal:e=>t.runWithTerminal(e),getCwd:()=>n,getCommandInvocationSource:()=>`user`}}function Dl(e,t){return e!==void 0&&e===t?I:e}function Ol(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kl(e,t){if(!Ol(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&&Ol(r)&&r.driverId===t&&(n={...n,metadata:{...r,driverId:I}}),n}function Al(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 Ml(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 Nl(e,t){let n=t.toLowerCase();return e.find(e=>e.name.toLowerCase()===n&&e.subcommands!==void 0)?.subcommands??[]}function Pl(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>e.name.toLowerCase().startsWith(n))}const Fl=[`get-context`,`get-commands`,`get-status`,`get-executing`,`get-pending`,`get-execution-workspace`],Il=[...Fl,`get-prompts`],Ll=[`get-context`,`get-status`,`get-commands`],Rl=new Set([`exit`,`quit`]),zl=new Set([`show-plugin-manager`,`show-settings`]);function Bl(e){return e instanceof Error?e.message:String(e)}var Vl=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)}},Hl=class{options;sessionName;manager;userActions;permissions;attention;lifecycle;uiEvents=new Vl;clientCommands;commandQueryPort={getCommands:e=>Pl(this.commandCatalog,e),getSubcommands:e=>Nl(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:El({terminalHandoff:e.terminalHandoff,cwd:e.cwd})},this.hostHistory=new bl({request:e=>this.send(e===0?{type:`get-history`}:{type:`get-history`,fromIndex:e}),show:(e,t)=>this.manager.syncHostHistory(e,t),revive:e=>Al(e,this.own)}),this.userActions=new al(()=>this.notify()),this.permissions=new ol(()=>this.notify()),this.attention=e.attention?new Qc({source:e.attention,onRecap:e=>this.manager.addAttentionRecap(e)}):void 0,this.lifecycle=new il({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}=nl(e);if(Rl.has(t)){this.end(`user`);return}let r=wl(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 Tl(e,t,n.host,n.set);for(let e of i)this.uiEvents.emitUiIntent({intent:e,requesterDriverId:I});this.notice(r.message)}catch(t){this.notice(`/${e.name} failed: ${Bl(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:gl(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: ${Bl(t)}`)}}project(e){let t=this.manager;switch(e.type){case`user_message`:{let t=Dl(e.driverId,this.options.driverId)??null;this.hostHistory.echo(sl(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=Ml(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:`)?he(e.requesterDriverId):void 0,n=this.promptGeneration;this.permissions.enqueue(e.toolName,e.toolArgs,e.id,e.canPersistProjectPermission,t).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(zl.has(e.intent.type)){this.notice(`That screen is not available while attached to a daemon.`);return}let t={...e,requesterDriverId:I};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:Eo(e.sessionId));t!==void 0&&t!==this.sessionName&&this.rename(t)}showCommandResult(e){for(let e of Ll)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(Eo(e)),this.requestSnapshot()}requestSnapshot(){this.hostHistory.reload(),this.requestState()}requestState(){for(let e of this.readOnly?Fl:Il)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&&!ye(e.type))return!1;try{return this.options.connection.send(e),!0}catch(e){return this.notice(`Could not reach the session: ${Bl(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 hl;return e.onChange=()=>this.notify(),e}notice(e){this.manager.addEntry(F(j(e)))}notify(){this.onChange?.()}};function Ul(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 Wl(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 Gl(e){try{await e.keybindingsSource?.start(),await Jl(e,t=>({createChannel:ql(e,t)}))}finally{e.keybindingsSource?.dispose()}}async function Kl(e){let t=`user`,n=()=>void 0,r=new Promise(e=>{n=e});try{await e.keybindingsSource?.start(),await Jl(e,i=>{let a;return{createChannel:()=>a??=new Hl({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 ql(e,t){let n=e.workspaceMovedFrom;return r=>{let i=n;n=void 0;let a=new vl({...Ul(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 Jl(t,n){let r=t.screenReader===!0;t.announce!==!1&&Pc({enabled:r,channel:t.screenReaderChannel,hint:t.screenReaderHint});let i=Lc({enabled:r,overrides:t.screenReaderPacing}),a=r&&i.preparkMs>0?Uc({stdout:process.stdout,preparkMs:i.preparkMs}):void 0;Ne()||(e.level=0);let o=new Kc,c=Ie({override:t.focusReporting}),l=Gc({supported:()=>c}),u=new Ac({focusReporting:c,now:Date.now});o.setTerminalModeHooks({preSuspend:async()=>{l.disable(),await a?.drain()},postResume:()=>l.enable()});let d=n({terminalHandoff:o,attention:u}),f,p=e=>(f=d.createChannel(e),f);await zc(i.startupQuietMs,process.stdin);let m=new Mc(process.stdin,{negotiated:()=>l.negotiated,onFocusIn:()=>u.focusIn(),onFocusOut:()=>u.focusOut(),onKeystroke:()=>u.keystroke()});process.stdin.resume(),l.enable(),u.start();let h=a===void 0?void 0:Wc(a),g=T(ga,{name:t.productDisplayName,modelCommandToolPrefix:t.modelCommandToolPrefix,children:T(Bn,{source:t.keybindingsSource,children:T(U,{enabled:r,children:T(Ar,{overrides:t.terminalCapabilities,children:T(kc,{cwd:t.cwd,createChannel:p,...d.requestSessionSwitch===void 0?{}:{requestSessionSwitch:d.requestSessionSwitch},providerOverride:t.providerOverride,providerType:t.providerType,modelId:t.modelId,permissionMode:t.permissionMode,version:t.version,sessionStore:t.sessionStore,resumeSessionId:t.resumeSessionId,showSessionPickerOnStart:t.showSessionPickerOnStart,initialInput:t.initialInput,initialInputOrigin:t.initialInputOrigin,startupUpdateNotice:t.startupUpdateNotice,transportRegistry:t.transportRegistry,pluginAdapter:t.commandHostAdapters?.plugin,cliAdapter:t.cliAdapter,promptHistorySource:t.promptHistorySource,promptHistoryProject:t.promptHistoryProject,themeRegistry:t.themeRegistry,reducedMotion:t.reducedMotion,reducedMotionOverride:t.reducedMotionOverride})})})})}),_=s(h===void 0?g:T(Dr,{port:h,children:g}),{exitOnCtrlC:!1,isScreenReaderEnabled:r,stdin:m.asInkStdin(),...a===void 0?{}:{stdout:a.asInkStdout()}});o.setInkInstance(_),d.ended?.then(()=>_.unmount());try{await Wl(()=>_.waitUntilExit(),()=>f)}finally{await a?.flush(),o.setTerminalModeHooks(void 0),l.disable(),u.dispose(),m.detach(),process.stdin.pause()}}const Yl={drive:`drive (send prompts, answer its questions)`,observe:`observe (read only)`},Xl=[`needs-input`,`working`,`idle`,`unknown`,`unverified`,`dead`];function $(e){return e?.liveness===`alive`&&e.control===`available`&&e.generation!==void 0}function Zl(e){return e.liveness===`dead`?`dead`:$(e)?e.activity:`unverified`}function Ql(e){return[...e].sort((e,t)=>Xl.indexOf(Zl(e))-Xl.indexOf(Zl(t))||e.id.localeCompare(t.id))}function $l(e){return[...e].sort((e,t)=>(e.cwd===void 0)-+(t.cwd===void 0)||(e.cwd??``).localeCompare(t.cwd??``)||Xl.indexOf(Zl(e))-Xl.indexOf(Zl(t))||e.id.localeCompare(t.id))}function eu(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 D(nu(c))<=n?c:e.slice(o)}function tu(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 nu(e){return tu(e).join(``)}function ru(e,t){let n=tu(e);if(D(n.join(``))<=t)return n.join(``);let r=Math.ceil((t-1)/2),i=t-r-1,a=``;for(let e of n){if(D(a)+D(e)>r)break;a+=e}let o=``;for(let e of[...n].reverse()){if(D(o)+D(e)>i)break;o=e+o}return`${a}…${o}`}function iu(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 au(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 ou({loadRows:e,onStop:t,onStart:n,onOpenPr:r,onAttach:a,filteredByCwd:o=!1,filteredByName:s=!1,filteredByPr:l=!1,stateFilter:u,refreshMs:f=2e3,initialSelectedId:m,initialGroupByDirectory:h=!1}){let{exit:g}=c(),{stdout:_}=p(),v=Math.max(12,_.columns??80),b=W(),[ee,te]=C([]),[ne,re]=C(Date.now),[O,ie]=C(`loading`),[ae,oe]=C(m),[se,ce]=C(!1),[le,ue]=C(h),[k,de]=C(),A=k?.id,[fe,j]=C(`idle`),[M,N]=C(`idle`),[P,pe]=C(),me=S(!1),[F,he]=C(`idle`),[ge,_e]=C(),I=S(!1),[ve,ye]=C(`idle`),be=S(!1),L=S(!0),R=x(()=>{let e=ee.filter(e=>u===void 0||Zl(e)===u);return le?$l(e):Ql(e)},[ee,u,le]),xe=x(()=>{let e=[],t=[...new Set(R.map(e=>e.cwd).filter(e=>e!==void 0))],n,r=0;return R.forEach((i,a)=>{let o=le?i.cwd??`unverified`:Zl(i);if(o!==n){let n=le?i.cwd===void 0?`Directory: unverified`:(()=>{let e=`Dir ${++r}: `,n=Math.max(4,v-e.length),a=ru(eu(i.cwd,t,n),n),o=`${e}${a} — ${nu(i.cwd)}`;return b||D(o)<=v?o:`${e}${a}`})():`${o}:`;e.push({kind:`group`,label:n})}e.push({kind:`row`,row:i,index:a}),n=o}),e},[R,le,v,b]);y(()=>{let t=new AbortController,n=!0,r,i=async()=>{try{let r=Ql(await e(t.signal));if(!n||t.signal.aborted)return;let i=Date.now();te(e=>iu(e,r)?e:r),re(e=>r.some(t=>t.nextLoopAt!==void 0&&au(t.nextLoopAt,e)!==au(t.nextLoopAt,i))?i:e),ie(`ready`)}catch{n&&!t.signal.aborted&&ie(`unavailable`)}finally{n&&!t.signal.aborted&&(r=setTimeout(()=>{i()},f))}};return i(),()=>{n=!1,r!==void 0&&clearTimeout(r),t.abort()}},[e,f]),y(()=>(L.current=!0,()=>{L.current=!1}),[]);let z=ae!==void 0&&R.some(e=>e.id===ae)?ae:R[0]?.id;y(()=>{oe(e=>R.length===0||e!==void 0&&R.some(t=>t.id===e)?e:R[0]?.id)},[R]),d((e,i)=>{if(!me.current&&!(be.current&&e!==`q`&&!(!b&&i.escape)&&!(i.ctrl&&e===`c`))&&!(I.current&&e!==`q`&&!(!b&&i.escape)&&!(i.ctrl&&e===`c`))){if(A!==void 0){if(e===`n`||i.escape){de(void 0);return}if(e===`y`&&k?.action===`attach`){let e=k,t=R.find(t=>t.id===e.id);if(de(void 0),O!==`ready`||!$(t)||t.generation!==e.generation||e.mode===void 0||a===void 0){j(`unavailable`);return}a({id:e.id,generation:e.generation,mode:e.mode,groupByDirectory:le}),g();return}if(e===`y`){let e=k,n=R.find(t=>t.id===e?.id);if(de(void 0),O!==`ready`||e===void 0||!$(n)||n.generation!==e.generation||t===void 0){N(`unavailable`);return}me.current=!0,N(`stopping`),t(e.id,e.generation).then(()=>{L.current&&(pe(e.id),N(`stopped`))}).catch(()=>{L.current&&N(`failed`)}).finally(()=>{me.current=!1})}return}if(e===`q`||!b&&i.escape||i.ctrl&&e===`c`){g();return}if(e===`?`){ce(e=>!e);return}if(e===`g`){Se.clear(),ue(e=>!e);return}if(e===`n`&&n!==void 0){I.current=!0,he(`starting`),Promise.resolve().then(n).then(e=>{L.current&&(_e(e),he(`started`))}).catch(()=>{L.current&&he(`failed`)}).finally(()=>{I.current=!1});return}if((e===`a`||e===`p`)&&a!==void 0){let t=R.find(e=>e.id===z);O!==`ready`||!$(t)?j(`unavailable`):(j(`idle`),N(`idle`),de({id:t.id,generation:t.generation,action:`attach`,mode:e===`a`?`drive`:`observe`}));return}if(e===`o`&&r!==void 0){let e=R.find(e=>e.id===z);if(O!==`ready`||!$(e)||!e.pr){ye(`unavailable`);return}be.current=!0,ye(`opening`),r(e.id,e.pr.url,e.generation).then(()=>{L.current&&ye(`opened`)}).catch(()=>{L.current&&ye(`failed`)}).finally(()=>{be.current=!1});return}if(e===`s`&&t!==void 0){let e=R.find(e=>e.id===z);O!==`ready`||!$(e)?N(`unavailable`):(N(`idle`),j(`idle`),de({id:e.id,generation:e.generation,action:`stop`}));return}if(!(b||R.length===0)&&(i.upArrow||i.downArrow)){let e=Math.max(0,R.findIndex(e=>e.id===z)),t=Math.max(0,Math.min(R.length-1,e+(i.downArrow?1:-1)));oe(R[t]?.id)}}});let Se=pn({enabled:b&&A===void 0&&M!==`stopping`,itemCount:R.length,cancellable:!0,repeatable:!0,onSelect:e=>{oe(R[e]?.id),N(`idle`)},onCancel:()=>{me.current||g()}}),B=R.find(e=>e.id===z),Ce=O===`ready`&&$(B)?B.name:void 0,we=O===`ready`&&$(B)&&B.activity===`idle`&&B.nextLoopAt?au(B.nextLoopAt,ne):``,V=O===`ready`&&$(B)?B.pr:void 0,Te=Math.max(8,_.rows??24),Ee=[`Keys:`,b?`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)`],...r===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`],De=se&&A===void 0&&M!==`stopping`,Oe=2+(u===void 0?0:1)+ +(O===`loading`||O===`unavailable`||O===`ready`&&R.length===0)+(z===void 0?0:1)+(Ce===void 0?0:1)+(V===void 0?0:2)+ +!!we+(ve===`idle`?0:1)+(F===`idle`?0:1)+(A===void 0?M===`idle`?0:1:b?1:2)+ +(A===void 0&&fe!==`idle`)+1+(De?Ee.length:0)+2,ke=Math.max(1,Te-Oe),Ae=Math.max(0,xe.findIndex(e=>e.kind===`row`&&e.row.id===z)),je=Math.min(Math.max(0,Ae-Math.floor(ke/2)),Math.max(0,xe.length-ke)),Me=b?xe:xe.slice(je,je+ke),U=b?{}:{wrap:`truncate-end`},Ne=a!==void 0&&O===`ready`&&$(B),Pe=M===`stopping`?`Stop in progress; wait for result.`:A===void 0?b?`Type a number and Enter to select; s Stop;${Ne?` a Attach; p Peek;`:``}${n?` n New;`:``}${r?` o Open PR;`:``} g Group; Escape to close; ? Help.`:`↑↓ Navigate s Stop${Ne?` a Attach p Peek`:``}${n?` n New`:``}${r?` o Open PR`:``} g Group ? Help q/Esc Close`:`Confirm ${k?.action===`attach`?`attach`:`stop`} or cancel before closing.`,Fe=e=>k?.action===`attach`&&k.mode!==void 0?`${k.mode===`drive`?`Attach to`:`Peek at`} ${e} to ${Yl[k.mode]}?`:`Stop ${e}?`;return E(i,{flexDirection:`column`,...b?{}:{height:Te},children:[E(H,{...U,children:[o?`Background sessions in selected directory`:`Background sessions across projects`,s?` · name filter active`:``,l?` · PR filter active`:``]}),E(H,{...U,children:[R.length,` supervised session(s). Foreground peers and saved records are separate.`]}),u!==void 0&&E(H,{...U,children:[`State: `,u]}),O===`loading`&&T(H,{...U,children:`Loading supervised sessions...`}),O===`unavailable`&&T(H,{...U,children:`Supervised session discovery unavailable; last verified rows remain below.`}),O===`ready`&&R.length===0&&T(H,{...U,children:`No supervised sessions.`}),je>0&&!b&&E(H,{children:[je,` more above`]}),Me.map(e=>e.kind===`group`?T(H,{...U,children:e.label},`group-${e.label}`):E(H,{...b?{}:{wrap:`truncate-end`},children:[b?Un(e.index):e.row.id===z?`> `:` `,e.row.name&&$(e.row)?b?`${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,O===`ready`&&$(e.row)&&e.row.activity===`idle`&&e.row.nextLoopAt?` ${au(e.row.nextLoopAt,ne)}`:``,e.row.problem?` ${e.row.problem}`:``,O===`ready`&&$(e.row)&&e.row.pr?` ${e.row.pr.host} ${e.row.pr.kind===`pull`?`#`:`!`}${e.row.pr.number}`:``]},`row-${e.row.id}`)),!b&&je+Me.length<xe.length&&E(H,{children:[xe.length-je-Me.length,` more below`]}),z!==void 0&&E(H,{...U,children:[`Selected `,z]}),Ce!==void 0&&E(H,{...U,children:[`Name: `,Ce]}),V!==void 0&&E(H,{...U,children:[`PR: `,V.host,` `,V.kind===`pull`?`#`:`!`,V.number]}),V!==void 0&&E(H,{...U,children:[`URL: `,V.url]}),we&&T(H,{...U,children:we}),ve===`opening`&&T(H,{...U,children:`Opening linked PR...`}),ve===`opened`&&T(H,{...U,children:`Opened linked PR.`}),ve===`failed`&&T(H,{...U,children:`PR link changed or could not be opened.`}),ve===`unavailable`&&T(H,{...U,children:`No verified PR link is available.`}),F===`starting`&&T(H,{...U,children:`Starting a background session...`}),F===`started`&&E(H,{...U,children:[`Started `,ge,s||u!==void 0?` (may be hidden by filter)`:``]}),F===`failed`&&T(H,{...U,children:`Start failed; check workspace trust or run session start --background for details.`}),A!==void 0&&(b?E(H,{children:[Fe(A),` y Yes / n No`]}):E(w,{children:[T(H,{...U,children:Fe(`…${A.slice(-8)}`)}),T(H,{...U,children:`y Yes / n No`})]})),A===void 0&&M===`unavailable`&&T(H,{...U,children:`This session cannot be stopped from the view.`}),A===void 0&&fe===`unavailable`&&T(H,{...U,children:`This session cannot be attached to from the view.`}),M===`stopping`&&T(H,{...U,children:`Stopping selected session; wait for confirmation.`}),M===`stopped`&&E(H,{...U,children:[`Stopped `,P]}),M===`failed`&&T(H,{...U,children:`Stop failed; session remains listed until verified otherwise.`}),b&&R.length>0&&A===void 0&&M!==`stopping`&&E(H,{children:[Hn(R.length,!0),Se.buffer?` ${Se.buffer}`:``]}),b&&Se.invalid&&T(H,{children:`Selection out of range.`}),T(H,{...U,children:Pe}),De&&Ee.map(e=>T(H,{...U,children:e},e))]})}async function su(e){e.announce!==!1&&Pc({enabled:e.screenReader,channel:e.screenReaderChannel,hint:e.screenReaderHint});let t,n=s(T(U,{enabled:e.screenReader,children:T(ou,{loadRows:e.loadRows,onStop:e.onStop,onStart:e.onStart,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 cu({providerDefinitions:e,reloadPluginCommandSource:t,userSettingsPath:n,settingsSources:r,formatResumeCommand:i}){return{getUserSettingsPath:()=>n,readSettings:e=>k(e),reloadPluginCommandSource:e=>{t(e)},applyActiveModelChange:(e,t,i)=>(O(r,[oe(`user`,n)],t,i),{applied:!0}),getGitBranch:e=>A(e),getProviderDisplayName:t=>N(e,t)?.displayName??t,...i===void 0?{}:{formatResumeCommand:i}}}function lu(e){return{$schema:e,version:1,bindings:{}}}function uu(e,t){let n=Mn(JSON.stringify(lu(t)),e);if(!n.ok)throw Error(n.diagnostic.message);return n.snapshot}var du=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=uu(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=Se(this.filePath);if(await L(e,{recursive:!0}),await this.#u(),this.#s)throw Error(`Keybindings source is disposed.`);this.#i=be(e,{persistent:!1},(e,t)=>{(t===null||t.toString()===z(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 L(Se(this.filePath),{recursive:!0});try{await xe(this.filePath,`${JSON.stringify(lu(this.#e),null,2)}\n`,{encoding:`utf8`,flag:`wx`,mode:384})}catch(e){if(!pu(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 R(this.filePath,`utf8`)}catch(e){if(fu(e))return;this.#d({file:this.filePath,path:`$`,message:hu(e)});return}let t=Mn(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 fu(e){return mu(e)&&e.code===`ENOENT`}function pu(e){return mu(e)&&e.code===`EEXIST`}function mu(e){return e instanceof Error&&`code`in e}function hu(e){return e instanceof Error?e.message:String(e)}function gu(e){return new du(e)}export{vl as TuiInteractionChannel,cu as createDefaultTuiCliAdapter,gu as createNodeKeybindingsSource,hc as createThemeCataloguePort,fc as createThemeRegistry,ft as escapeThemeText,Ae as listBuiltInThemes,Tt as parseThemeDocument,dt as quoteThemeText,Gl as renderApp,Kl as renderAttachedApp,su as renderSupervisedSessionView,pt as sanitizeThemeProse};
33
33
  //# sourceMappingURL=index.js.map