@robota-sdk/agent-ui-terminal 3.0.0-beta.92 → 3.0.0-beta.93
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/dist/node/index.d.ts +3 -1
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -1
- package/dist/node/index.js.map +1 -1
- package/package.json +11 -11
- package/src/render.tsx +5 -0
- package/src/tui-channel-options.ts +1 -0
- package/src/tui-session-options.ts +3 -0
package/dist/node/index.js
CHANGED
|
@@ -29,5 +29,5 @@ import e,{Chalk as t,backgroundColorNames as n,foregroundColorNames as r}from"ch
|
|
|
29
29
|
|
|
30
30
|
_(interrupted)_`:``))}):T(V,{wrap:`wrap`,children:n})})]})});function Ia({entry:e}){let t=K(),n=_a(),r=e.data,a=r?.tools,o=r?.summary?.split(`
|
|
31
31
|
`)??[];return a&&a.length>0?E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(Ma,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),T(V,{children:` `}),a.map((e,r)=>{let a=Sa(e,Bi(e)?.status===`error`);return E(i,{flexDirection:`column`,children:[E(V,{color:kt(t,a),children:[` `,Ca(e,a,n)]}),T(wa,{tool:e}),e.diffLines&&e.diffLines.length>0&&T(ka,{file:e.diffFile,lines:e.diffLines})]},r)})]}):E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(Ma,{kind:`tool`,text:`Tool: `,color:t.text.emphasis})}),T(V,{children:` `}),o.map((e,n)=>E(V,{color:t.text.success,children:[` `,B(e)]},n))]})}function La({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=B(r);return E(i,{flexDirection:`column`,marginBottom:1,children:[T(i,{children:T(Ma,{kind:`warning`,text:`System: `,color:t.text.warning})}),T(V,{children:` `}),T(i,{marginLeft:2,children:T(V,{wrap:`wrap`,children:a})})]})}function Ra({entry:e}){if(e.category===`chat`){let t=e.data;return T(Fa,{message:t})}return e.type===`tool-summary`?T(Ia,{entry:e}):e.type===`usage-summary`?T(Aa,{entry:e}):e.type===`tool-start`||e.type===`tool-end`?T(w,{}):T(La,{entry:e})}const za=[{keys:`↑↓`,label:`Navigate`},{keys:`Enter`,label:`Select`},{keys:`Esc`,label:`Cancel`}];function Ba({items:e,renderItem:t,onSelect:n,onCancel:r,maxVisible:a=3,footerHints:o=za,initialIndex:s=0}){let[c,l]=C(()=>{let t=s>=0&&s<e.length?s:0;return{...en(t),scrollOffset:Math.max(0,t-a+1)}}),u=S(c),d=_(t=>{let i=rn(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=fn({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=Vn(e.length,!0);return E(i,{flexDirection:`column`,children:[e.map((e,n)=>E(i,{children:[T(V,{children:Hn(n)}),t(e,!1)]},n)),E(V,{children:[n,p.buffer.length>0?` ${p.buffer}`:``]}),p.invalid&&T(V,{children:n})]})}let h=an(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(V,{dimColor:!0,children:[` ↑ `,v,` more above`]}),y.map((e,n)=>T(i,{marginBottom:1,children:t(e,v+n===g)},v+n)),b&&E(V,{dimColor:!0,children:[` ↓ `,e.length-v-a,` more below`]}),T(Y,{hints:o===za?m:o})]})}function Va({label:e,index:t,isCursor:n,isChecked:r,screenReader:i}){let a=K(),o=r?`[x] `:`[ ] `;return i?E(V,{children:[Hn(t),o,e]}):E(V,{color:n?a.text.accent:void 0,children:[n?`> `:` `,o,e]})}function Ha(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 Ua(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(Un,{itemCount:e.itemCount,cancellable:!0,buffer:e.numbered.buffer,invalid:e.numbered.invalid}):T(Y,{hints:t})}function Wa(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(V,{color:t.text.warning,bold:!0,children:n}),r!==void 0&&r.length>0&&T(V,{dimColor:!0,children:r}),a.map((e,t)=>T(Va,{label:e.label,index:t,isCursor:t===o,isChecked:s.has(e.value),screenReader:c},e.value)),T(Ua,{screenReader:c,itemCount:a.length,numbered:l,canConfirm:e.canConfirm,minSelect:e.minSelect})]})}function Ga(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 Ka({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}=Ga({options:n,minSelect:r,maxSelect:i,defaultValues:a,onConfirm:o}),m=fn({enabled:c,itemCount:n.length,cancellable:!0,multi:!0,onSelect:f,onConfirm:p,onCancel:s});Ha({active:!c,itemCount:n.length,setCursor:u,onToggleAtCursor:()=>f(l),onConfirm:p,onCancel:s});let h=d.size>=r;return T(Wa,{title:e,...t===void 0?{}:{description:t},options:n,cursor:l,selected:d,screenReader:c,canConfirm:h,minSelect:r,numbered:m})}function qa(){return{value:``,resolved:!1}}function Ja(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`}}:Ya(e,n)}function Ya(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 Xa({title:e,description:t,placeholder:n,onSubmit:r,onCancel:a,validate:o,allowEmpty:s=!1,masked:c=!1}){let l=K(),[u,d]=C(()=>qa()),f=S(u),p=_(e=>{let t=Ja(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();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(V,{color:l.text.warning,bold:!0,children:e}),T(Za,{description:t}),E(i,{marginTop:1,children:[T(V,{color:l.text.accent,children:`> `}),u.value?T(V,{children:c?`*`.repeat(u.value.length):u.value}):n?T(V,{dimColor:!0,children:n}):null,T(V,{color:l.text.accent,children:`█`})]}),u.error&&T(V,{color:l.text.error,children:u.error}),T(Y,{hints:h})]})}function Za({description:e}){return e===void 0||e.length===0?null:T(V,{dimColor:!0,children:e})}const Qa={value:``,label:`Type a custom answer…`};function $a({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(Xa,{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(Ka,{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,Qa]:[...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(V,{bold:!0,children:e.title}),e.description!==void 0&&e.description.length>0&&T(V,{dimColor:!0,children:e.description}),T(Ba,{items:u,initialIndex:f,maxVisible:e.maxVisible,renderItem:(e,t)=>E(V,{color:t?n.text.accent:void 0,children:[t?`> `:` `,e.label]}),onSelect:e=>{e===Qa?a(!0):t({type:`answer`,values:[e.value]})},onCancel:l})]})}const eo=[`Allow [y]`,`Allow always (this session) [s]`,`Allow always (this project) [p]`,`Deny [n]`];function to(e,t=!0){return[eo[0],`Allow ${e} always (this session) [s]`,t?`Allow ${e} always (this project) [p]`:`Project-wide approval unavailable`,eo[3]]}function no(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`}}:io(e,t.index);let r=rn(e,t,{itemCount:eo.length});return r.effect.type!==`select`||r.effect.index===2&&!n?{state:r.state,effect:{type:`none`}}:{state:r.state,effect:{type:`resolve`,decision:ro(r.effect.index)}}}function ro(e){return e===0?!0:e===1?`allow-session`:e===2&&`allow-project`}function io(e,t){return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`resolve`,decision:ro(t)}}}function ao(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 oo({request:e,armDelayMs:t=450}){let n=K(),r=e.canPersistProjectPermission!==!1,[a,o]=h.useState(()=>en()),s=h.useRef(a),c=h.useRef(e);if(c.current!==e){c.current=e;let t=en();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=no(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=to(k(e.toolName,e.toolArgs),r),g=fn({enabled:p&&d,itemCount:m.length,onSelect:t=>{let n=no(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,_]),Q(`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=Z(`permission-prompt`,[[[`previous`,`next`],`Navigate`],[`confirm`,`Confirm`]]),y=e.requester?.kind===`background-agent`?e.requester.label:void 0;return p?T(Wn,{title:va.permissionRequired,description:`${y===void 0?``:`Background agent ${y} wants to run `}${e.toolName} — ${ao(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(V,{color:n.text.warning,bold:!0,children:`[Permission Required]`}),d?null:T(V,{dimColor:!0,children:` keys answer in a moment`})]}),y===void 0?E(V,{children:[`Tool:`,` `,T(V,{color:n.text.accent,bold:!0,children:e.toolName})]}):E(V,{color:n.text.warning,children:[`Background agent `,T(V,{bold:!0,children:y}),` wants to run`,` `,T(V,{color:n.text.accent,bold:!0,children:e.toolName})]}),E(V,{dimColor:!0,children:[` `,ao(e.toolArgs)]}),e.requestedByPeer===void 0?null:E(V,{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(V,{color:r?n.text.accent:void 0,bold:r,dimColor:!d,children:[r?`> `:` `,e]})},e)})}),T(Y,{hints:v})]})}function so(){return{buffer:``,resolved:!1}}const co=[`y`,`yes`],lo=[`n`,`no`];function uo(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 co.includes(t)?{state:{buffer:``,resolved:!0},effect:{type:`select`,index:0}}:lo.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 fo(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:typeof t==`string`?rn(e,t,{itemCount:n}):{state:{...e,selectedIndex:t.index,resolved:!0},effect:{type:`select`,index:t.index}}}function po({message:e,options:t=[`Yes`,`No`],onSelect:n}){let r=K(),[a,o]=C(()=>en()),s=S(a),c=_(e=>{let r=fo(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(so),p=S(u);d((e,t)=>{let r=uo(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(V,{children:e}),E(V,{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(V,{color:r.text.warning,children:e}),T(i,{marginTop:1,children:t.map((e,t)=>T(i,{marginRight:2,children:E(V,{color:t===a.selectedIndex?r.text.accent:void 0,bold:t===a.selectedIndex,children:[t===a.selectedIndex?`> `:` `,e]})},e))}),T(Y,{hints:m})]})}function mo(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 ho({title:e,items:t,onSelect:n,onBack:r,loading:a,error:o}){let s=K(),[c,l]=C(()=>en()),u=S(c),d=!a&&!o,f=W(),p=fn({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=rn(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=an(c,{itemCount:t.length});v!==c&&(u.current=v);let y=v.selectedIndex;return f?T(Wn,{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(V,{color:s.text.warning,bold:!0,children:e}),a&&T(i,{marginTop:1,children:T(V,{dimColor:!0,children:`Loading...`})}),o&&T(i,{marginTop:1,children:T(V,{color:s.text.error,children:o})}),!a&&!o&&T(i,{flexDirection:`column`,marginTop:1,children:t.map((e,t)=>E(i,{children:[E(V,{color:t===y?s.text.accent:void 0,bold:t===y,children:[t===y?`> `:` `,e.label]}),e.hint&&E(V,{dimColor:!0,children:[` `,e.hint]})]},e.value))}),T(Y,{hints:a?[]:o?g:h})]})}function go(e,t){e===`marketplace`?t.push({screen:`marketplace-list`}):e===`installed`&&t.push({screen:`installed-list`})}function _o(e,t){e===`__add__`?t.push({screen:`marketplace-add`}):t.push({screen:`marketplace-action`,context:{marketplace:e}})}function vo(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 yo(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 bo(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 xo(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 So(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 Co({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}=mo(l.screen,l.context?.marketplace,e,s,r.length),x=_(t=>{let n=l.screen,r=l.context;n===`main`?go(t,g):n===`marketplace-list`?_o(t,g):n===`marketplace-action`?vo(t,r?.marketplace??``,e,g):n===`marketplace-browse`?yo(t,r?.marketplace??``,v,g):n===`marketplace-install-scope`?bo(t,r?.pluginId??``,e,g):n===`installed-list`?xo(t,e,g):n===`installed-action`&&So(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(po,{message:a.message,onSelect:e=>{e===0?a.onConfirm():a.onCancel()}});let w=l.screen;return w===`marketplace-add`?T(Xa,{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(ho,{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(ho,{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(ho,{title:`Plugin: ${l.context?.pluginId??``}`,items:[{label:`Uninstall`,value:`uninstall`}],onSelect:x,onBack:d},r.length):T(ho,{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 wo({notices:e}){let t=K();return e.length===0?null:T(i,{flexDirection:`column`,paddingX:1,children:e.map(e=>T(V,{color:t.text.muted,children:e.message},e.id))})}function To(e){let t=e.startsWith(`session_`)?e.slice(8):e;return t===``?e:t.slice(0,8)}function Eo(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 Do({sessions:e,onSelect:t,onCancel:n}){let r=K();return E(i,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[T(V,{bold:!0,color:r.text.accent,children:`Select a session to resume:`}),T(Ba,{items:[...e],renderItem:(e,t)=>{let n=Eo(e),i=e.preview?e.preview.slice(0,60)+(e.preview.length>60?`...`:``):``;return E(V,{children:[t?`> `:` `,T(V,{bold:!0,children:e.name??To(e.id)}),` `,T(V,{dimColor:!0,children:new Date(e.updatedAt).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}),` `,E(V,{dimColor:!0,children:[`msgs: `,e.messageCount]}),n===null?null:E(w,{children:[` `,T(V,{color:r.text.success,children:n})]}),i?E(w,{children:[`
|
|
32
|
-
`,T(V,{dimColor:!0,children:i})]}):null]})},onSelect:e=>t(e.id),onCancel:n})]})}function Oo(e){let t=ko(e),n=e.hasPendingPrompt&&t.kind!==`queued`?[`queued`]:[],r=[t.label,...n].join(` · `);return{...t,segments:n,text:r}}function ko(e){return e.activeToolCount>0?{kind:`tools`,label:`Tools (${e.activeToolCount})`,tone:`accent`}:e.isThinking?{kind:`thinking`,label:`Thinking`,tone:`warning`}:e.activeBackgroundTaskCount>0?{kind:`background`,label:`Background (${e.activeBackgroundTaskCount})`,tone:`accent`}:e.hasPendingPrompt?{kind:`queued`,label:`Queued`,tone:`warning`}:{kind:`idle`,label:`Idle`,tone:`muted`}}const Ao=` | `;function jo(e,t){return e>=90?t.text.error:e>=70?t.text.warning:t.text.success}function Mo({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r}){let i=K(),a=Oo({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r});return T(V,{color:i.text[a.tone],bold:a.kind!==`idle`,children:a.text})}function No({percentage:e,usedTokens:t,maxTokens:n}){return E(V,{color:jo(e,K()),children:[`Context: `,Math.round(e),`% (`,M(t),`/`,M(n),` tokens)`]})}function Po(){return T(V,{color:K().text.warning,bold:!0,children:`Observing — read only`})}function Fo({permissionMode:e}){return E(w,{children:[T(V,{color:K().text.accent,bold:!0,children:`Mode:`}),` `,T(V,{children:e})]})}function Io(e,t){return t||e!=="default"}function Lo({activePresetId:e}){return E(w,{children:[T(V,{color:K().text.accent,bold:!0,children:`Preset:`}),` `,T(V,{children:e})]})}function Ro(e){return e!==void 0&&e!=="default"}function zo({modelName:e,providerDisplayName:t,effort:n}){return E(V,{dimColor:!0,children:[t===void 0?e:`${t} ${e}`,n===void 0?``:` Effort: ${n}`]})}function Bo(e){let t=K(),n=e.showGitBranch&&e.gitBranch!==void 0&&e.gitBranch.length>0,r=W(),i=Io(e.permissionMode,r),a=e.activePresetId,o=Ro(a);return E(V,{children:[e.readOnly&&E(w,{children:[T(Po,{}),!r&&Ao]}),!r&&T(Mo,{isThinking:e.isThinking,activeToolCount:e.activeToolCount,activeBackgroundTaskCount:e.activeBackgroundTaskCount,hasPendingPrompt:e.hasPendingPrompt}),i&&E(w,{children:[Ao,T(Fo,{permissionMode:e.permissionMode})]}),o&&E(w,{children:[Ao,T(Lo,{activePresetId:a})]}),e.sessionName&&E(w,{children:[Ao,T(V,{color:t.text.session,children:e.sessionName})]}),n&&E(w,{children:[Ao,E(V,{dimColor:!0,children:[`git: `,e.gitBranch]})]}),Ao,T(zo,{modelName:e.modelName,providerDisplayName:e.providerDisplayName,effort:e.effort}),!r&&E(w,{children:[Ao,T(No,{percentage:e.contextPercentage,usedTokens:e.contextUsedTokens,maxTokens:e.contextMaxTokens})]})]})}function Vo({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=K();return E(i,{paddingLeft:1,paddingRight:1,justifyContent:`space-between`,children:[T(Bo,{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(V,{color:y.text.warning,bold:!0,children:[`[`,h,`]`]})]})}const Ho=g(null),Uo=Ho.Provider;function Wo(){let e=v(Ho);if(!e)throw Error(`TuiCliAdapterContext not provided`);return e}function Go({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 _=Wo(),v=x(()=>_.getGitBranch(e),[_,e,h]),y=x(()=>r===void 0?void 0:_.getProviderDisplayName(r),[_,r]);return d.enabled?T(Vo,{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(Po,{}):null}function Ko(e,t){let n=At(e);return{color:kt(t,n),icon:Ot[n],strikethrough:n===`error`||n===`denied`}}function qo({isThinking:e}){let t=K();return e?T(i,{marginBottom:1,children:T(V,{color:t.text.warning,children:`Thinking...`})}):T(w,{})}function Jo({activeTools:e}){let t=K(),n=_a();return E(i,{flexDirection:`column`,marginBottom:1,children:[T(V,{color:t.text.emphasis,bold:!0,children:`Tools:`}),T(V,{children:` `}),e.map((e,r)=>{let{color:a,icon:o,strikethrough:s}=Ko(e,t);return E(i,{flexDirection:`column`,children:[E(V,{color:a,strikethrough:s,children:[` `,o,` `,da(e.toolName,n),`(`,fa(e.firstArg),`)`]}),e.diffLines&&e.diffLines.length>0&&T(ka,{file:e.diffFile,lines:e.diffLines})]},`${e.toolName}-${r}`)})]})}function Yo(e,t,n,r){let i=t.map(e=>da(e.toolName,r)).join(`, `),a=[i.length>0?`${va.tool} ${i}`:void 0,e.length>0?e:n?va.thinking:void 0].filter(e=>e!==void 0);return a.length===0?T(w,{}):T(V,{children:a.join(` — `)})}function Xo({text:e,activeTools:t,isThinking:n=!1}){let r=K(),a=la(),o=t.length>0,s=e.length>0,c=W(),l=ga(),u=_a();return c?Yo(e,t,n,u):!o&&!s?T(qo,{isThinking:n}):E(i,{flexDirection:`column`,children:[o&&T(Jo,{activeTools:t}),s&&E(i,{flexDirection:`column`,marginBottom:1,children:[E(V,{color:r.text.accent,bold:!0,children:[l,`:`]}),T(V,{children:` `}),T(i,{marginLeft:2,children:T(H,{wrap:`wrap`,children:a(e)})})]})]})}function Zo(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?`> `:` `:Hn(r);return E(V,{...t&&r===void 0?{color:i.text.accent,bold:!0}:{},children:[a,Zo(e,n)]})}function $o({itemCount:e,buffer:t,invalid:n}){let r=Vn(e,!0);return E(i,{flexDirection:`column`,children:[E(V,{children:[r,t.length>0?` ${t}`:``]}),n&&T(V,{children:r})]})}function es(e,t){let n=e.findIndex(e=>e.id===t);return n<0?0:n}function ts(e){let[t,n]=h.useState(()=>({syntaxHighlighting:e.syntaxHighlighting,reducedMotion:e.reducedMotion}));return{toggles:t,setToggles:n}}function ns(e){let{themes:t,activeThemeId:n,preview:r}=e,[i,a]=h.useState(()=>es(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 rs(e,t){let{themes:n,select:r,cancel:i}=e,{focusedIndex:a,move:o}=ns(e),{toggles:s,setToggles:c}=ts(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=fn({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 is({themes:e,activeThemeId:t,focusedIndex:n,screenReader:r}){return e.length===0?T(V,{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 as(){return Ne()?T(w,{}):T(V,{dimColor:!0,children:`Colour is off for this terminal — themes apply, previews cannot show.`})}function os({skipped:e}){return e.length===0?T(w,{}):T(i,{flexDirection:`column`,marginTop:1,children:e.map((e,t)=>T(V,{dimColor:!0,children:` Skipped "${e.fileName}" — ${e.reason}`},t))})}function ss({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(V,{dimColor:!0,children:`syntax ${r(e.syntaxHighlighting)} · motion ${r(!e.reducedMotion)}${a}`}),n&&T(V,{dimColor:!0,children:`Change with /theme syntax on|off or /theme motion on|off`})]})}function cs({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($o,{itemCount:t,buffer:n.buffer,invalid:n.invalid}):T(Y,{hints:r})}function ls({picker:e}){let t=K(),n=W(),{themes:r,activeThemeId:a}=e,{focusedIndex:o,toggles:s,numbered:c}=rs(e,n);return E(i,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.focused},paddingX:1,children:[T(V,{color:t.text.accent,bold:!0,children:`Theme`}),T(as,{}),T(ss,{toggles:s,reducedMotionPin:e.reducedMotionPin,screenReader:n}),T(i,{flexDirection:`column`,marginTop:1,children:T(is,{themes:r,activeThemeId:a,focusedIndex:o,screenReader:n})}),T(os,{skipped:e.skipped}),T(cs,{screenReader:n,itemCount:r.length,numbered:c})]})}function us({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(V,{color:t?n.text.accent:void 0,bold:t,children:`${a} ${e.transport.name.padEnd(18)} ${o} ${c}`})})}function ds(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 fs({registry:e,onClose:t}){let n=K(),r=ga(),[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 ds(a,s,l,e,c,u,f,t,p),E(i,{flexDirection:`column`,paddingX:2,paddingY:1,children:[T(V,{bold:!0,children:`Settings › Transports`}),T(i,{marginTop:1,flexDirection:`column`,children:a.map((e,t)=>T(us,{entry:e,selected:t===s},e.transport.name))}),E(i,{marginTop:1,flexDirection:`column`,children:[T(Y,{hints:m}),E(V,{dimColor:!0,children:[`A toggle is saved now and applies the next time `,r,` starts.`]})]}),l&&T(i,{marginTop:1,children:T(V,{color:n.text.warning,children:`Saving…`})}),d!==void 0&&T(i,{marginTop:1,children:T(V,{color:n.text.error,children:`Not saved — ${d}`})})]})}function ps({message:e}){return T(i,{paddingX:1,marginBottom:1,children:T(V,{color:K().text.warning,children:e})})}function ms({model:e}){return T(a,{items:e.staticItems,children:e=>e.kind===`banner`?T(Tt,{version:e.version},`logo`):T(Ra,{entry:e.entry},e.entry.id)},e.transcriptKey)}function hs({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(Qt,{entry:n.selectedEntry,page:n.detail.page,loading:n.detail.loading,error:n.detail.error}),e.isShuttingDown&&T(V,{color:t.text.warning,children:`Shutting down...`}),(r.isThinking||r.activeTools.length>0)&&E(i,{flexDirection:`column`,marginBottom:1,children:[T(Xo,{text:r.text,activeTools:r.activeTools,isThinking:r.isThinking}),r.isStalled&&T(V,{color:t.text.warning,children:`⚠ Still waiting on the provider — the network may be stalled. Esc to interrupt.`})]}),!r.isThinking&&r.lastErrorMessage&&T(V,{color:t.text.error,children:`✖ Last turn failed — the session is alive; type your next prompt when ready.`}),T(Xt,{entries:n.entries,focusedIndex:n.focusedIndex})]})}function gs({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(Kn,{snapshot:t.snapshot,selectedEntryId:t.selectedEntryId,onSelect:t.select,onClose:t.closeSwitcher,onAttach:t.attachToFork}),e.permissionRequest&&T(oo,{request:e.permissionRequest}),a&&T($a,{request:a,onAnswer:t=>e.resolveUserAction(a,t)}),n.visible&&T(Co,{callbacks:n.callbacks,onClose:n.close,addMessage:e=>n.addMessage(e.content)}),i.visible&&i.registry&&T(fs,{registry:i.registry,onClose:i.close}),r.visible&&T(Do,{sessions:r.sessions,onSelect:r.select,onCancel:r.cancel}),e.theme.picker.visible&&T(ls,{picker:e.theme.picker})]})}function _s({model:e}){let{input:t}=e;return E(w,{children:[T(Zt,{percentage:e.contextPercentage}),T(Ri,{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(Go,{...e.status})]})}function vs({viewModel:e}){let t=K(),n=Bn();return E(i,{flexDirection:`column`,children:[T(ms,{model:e}),!e.handoffSuspended&&E(w,{children:[e.updateNotice&&T(ps,{message:e.updateNotice}),e.coordinationError&&E(V,{color:t.text.error,children:[e.coordinationError,` Press Enter to retry.`]}),n.diagnostic&&T(V,{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(V,{color:t.text.warning,children:`Keybindings ${e.path}: ${e.message}`},`${e.path}:${e.code}`)),e.theme.unknownThemeNotice!==void 0&&T(V,{color:t.text.warning,children:e.theme.unknownThemeNotice}),T(wo,{notices:e.sessionEventNotices}),T(hs,{model:e}),T(gs,{model:e}),T(_s,{model:e})]})]})}function ys(e){return[...e.screenReader?[]:[{kind:`banner`,version:e.version??`0.0.0`}],...e.history.map(e=>({kind:`entry`,entry:e}))]}function bs(e){let t=e.forceExit??(e=>process.exit(e));if(e.isShuttingDown){t(130);return}e.graceful()}function xs(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 Ss={promptStart:`A`,promptEnd:`B`,turnStart:`C`,turnEnd:`D`};function Cs(e){return`\x1b]133;${Ss[e]}\x07`}function ws(e){let t=e.write??(e=>{process.stdout.write(e)});return{emit(n){!e.enabled||!e.supported()||t(Cs(n))}}}function Ts(e,t){return e.executionId??`${e.toolName}#${t}`}function Es(e){let t=new Set;return e.forEach((e,n)=>{e.isRunning&&t.add(Ts(e,n))}),t}function Ds(e){let{enabled:t,isThinking:n,activeTools:r,awaitingAnswer:i}=e,a=x(()=>xs({enabled:t}),[t]),o=Dr(),s=Ar(),c=x(()=>ws({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=Es(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 Os(e){return!!(e.permissionRequest||e.pendingUserAction||e.pluginVisible||e.transportVisible||e.sessionPickerVisible||e.workspaceSwitcherVisible||e.historySearchOpen||e.themePickerVisible||e.coordinationBlocked)}function ks(e){Q(e.isThinking?`thinking`:`background-detail`,t=>{if(Os(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 As(e){Q(`app`,t=>{t.includes(`open-workspace-switcher`)&&(e.permissionRequest||e.pendingUserAction||e.pluginVisible||e.sessionPickerVisible||e.historySearchOpen||e.themePickerVisible||e.coordinationBlocked||e.isShuttingDown||e.toggleWorkspaceSwitcher())})}function js(e){Q(`recovery`,t=>{e.recoveryError!==void 0&&!e.recoveryPending&&t.includes(`retry`)&&e.retryRecovery()})}function Ms(e,t){return e===``||t&&e===`]`}function Ns(e){let{exit:t}=c(),n=n=>{bs({isShuttingDown:e.isShuttingDown,graceful:()=>void e.shutdown(n).finally(()=>t())})};d((t,r)=>{(r.ctrl&&t===`c`||e.attached&&Ms(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 Ps(e){ks(e),js(e),As(e),Ns(e);let t=W();return Ds({enabled:t,isThinking:e.isThinking,activeTools:e.activeTools,awaitingAnswer:e.permissionRequest!==null||e.pendingUserAction!==null}),t}function Fs(){return Promise.reject(Error(`Plugin management is unavailable in this host.`))}function Is(){return{listInstalled:Fs,listAvailablePlugins:Fs,install:Fs,uninstall:Fs,enable:Fs,disable:Fs,marketplaceAdd:Fs,marketplaceRemove:Fs,marketplaceUpdate:Fs,marketplaceList:Fs,reloadPlugins:Fs}}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(P(j(t))),[e.addEntry]),r=_(t=>{e.setSessionPickerVisible(!1),e.onSessionSwitch(t)},[e.onSessionSwitch,e.setSessionPickerVisible]),i=_(()=>{e.setSessionPickerVisible(!1),e.addEntry(P(j(`Session resume cancelled.`)))},[e.addEntry,e.setSessionPickerVisible]),a=e.hostSessions??ce(e.sessionStore,e.cwd),o=e.sessionPickerVisible&&a.length===0;return y(()=>{o&&(e.setSessionPickerVisible(!1),e.addEntry(P(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=Ps({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=ga();y(()=>{let n=B(e??``),r=B(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 le(e.readSettings(e.getUserSettingsPath()))}function Js(){let e=Wo(),[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=Wo();return _(i=>{let a=e=>n(P(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){Q(`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(()=>Ft(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:It(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===F)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={...O},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=Wo(),[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=ke(),t=[]){let n=new Map(e.map(e=>[e.id,e]));return{list:()=>e,skipped:()=>t,get:e=>n.get(e),resolve:e=>{if(e===void 0||e===U)return{theme:Ae(n.get(U))};let t=n.get(e);return t?{theme:t}:{theme:Ae(n.get(U)),unknownId:e}}}}function pc(e){return`Theme "${e}" is not installed — using "${U}".`}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(()=>ys({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(ze,{theme:t.theme.resolved,reducedMotion:t.theme.reducedMotion,syntaxHighlighting:t.theme.syntaxHighlighting,children:T(vs,{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(Uo,{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 ye{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 B(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(P(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,a){return new Promise(o=>{this.entries.push({toolName:e,toolArgs:t,resolve:o,...n===void 0?{}:{id:n},...r===void 0?{}:{canPersistProjectPermission:r},...i===void 0?{}:{requestedByPeer:i},...a===void 0?{}:{requester:a}}),this.processNext()})}dismissById(e){let t=this.entries.filter(t=>t.id===e);if(t.length===0)return!1;let n=this.entries[0]?.id===e;this.entries=this.entries.filter(t=>t.id!==e);for(let e of t)e.resolve(!1);return n&&(this.processing=!1,this.currentRequest=null,this.processNext()),!0}cancelAll(){let e=this.entries;this.entries=[],this.processing=!1,this.currentRequest=null;for(let t of e)t.resolve(!1);this.onChange()}processNext(){if(this.processing)return;let e=this.entries[0];if(!e){this.currentRequest=null,this.onChange();return}this.processing=!0,this.currentRequest={toolName:e.toolName,toolArgs:e.toolArgs,...e.canPersistProjectPermission===void 0?{}:{canPersistProjectPermission:e.canPersistProjectPermission},...e.requestedByPeer===void 0?{}:{requestedByPeer:e.requestedByPeer},...e.requester===void 0?{}:{requester:e.requester},resolve:t=>{this.entries[0]===e&&(this.entries.shift(),this.processing=!1,this.currentRequest=null,e.resolve(t),setTimeout(()=>this.processNext(),0))}},this.onChange()}};function sl(e,t){let n=null;try{n=t.getActiveDriverId?.()??null}catch{n=null}return P(pe(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,requester:s})=>{n?.onNeedsInput();let c=o?.startsWith(`peer:`)?ge(o):void 0;this.options.requestPermission(r,i,t,a,c,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.environment===void 0?{}:{environment:e.environment},...e.editCheckpointStore===void 0?{}:{editCheckpointStore:e.editCheckpointStore},...e.externalEventVerifierFactory===void 0?{}:{externalEventVerifierFactory:e.externalEventVerifierFactory},...e.externalEventGrantHistory===void 0?{}:{externalEventGrantHistory:e.externalEventGrantHistory},...e.model===void 0?{}:{model:e.model},...e.effort===void 0?{}:{effort:e.effort},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt},...e.responseFormat===void 0?{}:{responseFormat:e.responseFormat},...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},permissionMode:e.permissionMode,maxTurns:e.maxTurns,sessionStore:e.sessionStore,disableSessionLoops:e.disableSessionLoops,resolveDefaultLoopPrompt:e.resolveDefaultLoopPrompt,resumeSessionId:e.resumeSessionId,forkSession:e.forkSession,...e.workspaceMovedFrom===void 0?{}:{workspaceMovedFrom:e.workspaceMovedFrom},sessionName:e.sessionName,autoName:!0,backgroundTaskRunners:e.backgroundTaskRunners,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.agentDefinitions===void 0?{}:{agentDefinitions:e.agentDefinitions},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.pluginDirectories===void 0?{}:{pluginDirectories:e.pluginDirectories},...e.additionalTools===void 0?{}:{additionalTools:e.additionalTools},...e.defaultTools===void 0?{}:{defaultTools:e.defaultTools},...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},...e.sandboxClient===void 0?{}:{sandboxClient:e.sandboxClient},commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,...e.remoteCommandPolicy?{remoteCommandPolicy:e.remoteCommandPolicy}:{},language:e.language,agentName:e.agentName,activePresetId:e.activePresetId,persona:e.persona,systemPrompt:e.systemPrompt,appendSystemPrompt:e.appendSystemPrompt,allowedTools:e.allowedTools,deniedTools:e.deniedTools,enableParallelSubagents:e.enableParallelSubagents,selfVerification:e.selfVerification,terminalHandoff:e.terminalHandoff,...e.providerDefinitions?{providerDefinitions:e.providerDefinitions}:{},...e.memoryStore?{memoryStore:e.memoryStore}:{},...e.automaticMemory?{automaticMemory:e.automaticMemory}:{},...e.recallMemory?{recallMemory:e.recallMemory}:{},...e.promptHistory?{promptHistory:e.promptHistory}:{}}}function 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=e.executionId===void 0?this.activeTools.findLastIndex(t=>t.toolName===e.toolName&&t.isRunning):this.activeTools.findIndex(t=>t.executionId===e.executionId&&t.isRunning);if(t!==-1){let n=[...this.activeTools];n[t]=e,this.activeTools=n}this.isThinking&&!this.activeTools.some(e=>e.isRunning)&&this.armStallTimer(),this.notify()};onThinking=e=>{this.isThinking=e,e?(this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.lastErrorMessage=null,this.armStallTimer()):(this.isAborting=!1,this.activeTools=[],this.clearStallTimer()),this.notify()};onComplete=e=>{this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.contextState={percentage:e.contextState.usedPercentage,usedTokens:e.contextState.usedTokens,maxTokens:e.contextState.maxTokens},this.notify()};onInterrupted=()=>{this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onError=e=>{this.clearStallTimer(),this.lastErrorMessage=e?.message??`Unknown error`,this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onContextUpdate=e=>{this.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})};syncHistory(e){e.length!==0&&(this.history=this.withLocalNotices(e),this.notify())}syncHostHistory(e,t){this.history=[...this.withLocalNotices(e),...t],this.notify()}withLocalNotices(e){let t=[],n=0;for(let r of this.localNotices){let i=Math.min(r.afterSessionEntries,e.length);for(;n<i;)t.push(e[n++]);t.push(r.entry)}for(;n<e.length;)t.push(e[n++]);return t}addEntry(e){this.localNotices.push({entry:e,afterSessionEntries:this.history.length-this.localNotices.length}),this.history=[...this.history,e],this.notify()}addUserEcho(e){this.history=[...this.history,e],this.notify()}clearHistory(){this.history=[],this.localNotices=[],this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()}setPendingPrompt(e){this.pendingPrompt=e,this.notify()}setAborting(e){this.isAborting=e,this.notify()}setContextState(e){this.contextState=e,this.notify()}addSessionEventNotice(e){this.sessionNoticeStore.add(e),this.notify()}addAttentionRecap(e){this.sessionNoticeStore.addAttentionRecap(e),this.notify()}addSessionEventDeliveryError(e,t){this.sessionNoticeStore.addDeliveryError(e,t),this.notify()}syncExecutionWorkspaceSnapshot(e){let t=this.selectedExecutionEntryId,n=t!==void 0&&e.entries.some(e=>e.id===t)?t:e.selectedEntryId??e.entries[0]?.id;this.executionWorkspaceSnapshot={...e,...n?{selectedEntryId:n}:{}},this.selectedExecutionEntryId=n,this.notify()}selectExecutionWorkspaceEntry(e){this.executionWorkspaceSnapshot?.entries.some(t=>t.id===e)&&(this.selectedExecutionEntryId=e,this.executionWorkspaceSnapshot={...this.executionWorkspaceSnapshot,selectedEntryId:e},this.notify())}dispose(){this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.onChange=null}};function 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,a)=>this.permissions.enqueue(e,t,n,r,i,a),askUser:(e,t)=>this.askUser(e,t),dismissPrompt:e=>this.dismissPromptById(e),...e.onSessionEventDeliveryError?{onDeliveryError:e.onSessionEventDeliveryError}:{}}),this.lifecycle=new 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(P(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(P(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(P(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/Et}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(!oe(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 ne(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?F: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:F}}),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:F});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:`)?ge(e.requesterDriverId):void 0,n=this.promptGeneration;this.permissions.enqueue(e.toolName,e.toolArgs,e.id,e.canPersistProjectPermission,t,e.requester).then(t=>this.answer(n,e.id,{type:`permission-response`,id:e.id,result:t}))}askUser(e){if(this.showsPrompt(e.id))return;this.attention?.onNeedsInput();let t=this.promptGeneration;this.userActions.enqueue(e.request,e.id).then(n=>this.answer(t,e.id,{type:`ask-response`,id:e.id,response:n}))}answer(e,t,n){e===this.promptGeneration&&(this.shownPromptIds.delete(t),!this.settledPromptIds.delete(t)&&this.send(n))}dismissPrompt(e){this.settledPromptIds.add(e);let t=this.userActions.dismissById(e),n=this.permissions.dismissById(e);!t&&!n&&this.settledPromptIds.delete(e)}showUiIntent(e){if(e.requesterDriverId===void 0){this.uiEvents.emitUiIntent(e);return}if(zl.has(e.intent.type)){this.notice(`That screen is not available while attached to a daemon.`);return}let t={...e,requesterDriverId:F};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:To(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(To(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&&!I(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(P(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.environment===void 0?{}:{environment:e.environment},...e.orgPolicy===void 0?{}:{orgPolicy:e.orgPolicy},...e.externalEventVerifierFactory===void 0?{}:{externalEventVerifierFactory:e.externalEventVerifierFactory},...e.externalEventGrantHistory===void 0?{}:{externalEventGrantHistory:e.externalEventGrantHistory},...e.providerDefinitions?{providerDefinitions:e.providerDefinitions}:{},...e.modelId===void 0?{}:{model:e.modelId},...e.effort===void 0?{}:{effort:e.effort},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt},...e.appendSystemPrompt===void 0?{}:{appendSystemPrompt:e.appendSystemPrompt},...e.responseFormat===void 0?{}:{responseFormat:e.responseFormat},...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},permissionMode:e.permissionMode,maxTurns:e.maxTurns,allowedTools:e.allowedTools,deniedTools:e.deniedTools,sessionStore:e.sessionStore,disableSessionLoops:e.disableSessionLoops,resolveDefaultLoopPrompt:e.resolveDefaultLoopPrompt,resumeSessionId:t,forkSession:e.forkSession,sessionName:e.sessionName,backgroundTaskRunners:e.backgroundTaskRunners,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.agentDefinitions===void 0?{}:{agentDefinitions:e.agentDefinitions},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.pluginDirectories===void 0?{}:{pluginDirectories:e.pluginDirectories},...e.additionalTools===void 0?{}:{additionalTools:e.additionalTools},...e.defaultTools===void 0?{}:{defaultTools:e.defaultTools},...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},...e.sandboxClient===void 0?{}:{sandboxClient:e.sandboxClient},commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,remoteCommandPolicy:e.remoteCommandPolicy,transportRegistry:e.transportRegistry,bindTransports:e.bindTransports,language:e.language,reloadPluginCommandSource:e.reloadPluginCommandSource,agentName:e.agentName,activePresetId:e.activePresetId,persona:e.persona,enableParallelSubagents:e.enableParallelSubagents,selfVerification:e.selfVerification,...e.memoryStore?{memoryStore:e.memoryStore}:{},...e.automaticMemory?{automaticMemory:e.automaticMemory}:{},...e.recallMemory?{recallMemory:e.recallMemory}:{},...e.screenReader===void 0?{}:{screenReader:e.screenReader},promptHistory:e.promptHistory}}async function 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(ha,{name:t.productDisplayName,modelCommandToolPrefix:t.modelCommandToolPrefix,children:T(zn,{source:t.keybindingsSource,children:T(Me,{enabled:r,children:T(kr,{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(Er,{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 Zl(e,t,n){if(e.length<=t)return e;let r=Math.max(1,t-1),i=n===void 0?`check workspace trust in the terminal`:`see ${n}`;return[...e.slice(0,r),`… ${e.length-r} more — ${i}`]}function $(e){return e?.liveness===`alive`&&e.control===`available`&&e.generation!==void 0}function Ql(e){return e.liveness===`dead`?`dead`:$(e)?e.activity:`unverified`}function $l(e){return[...e].sort((e,t)=>Xl.indexOf(Ql(e))-Xl.indexOf(Ql(t))||e.id.localeCompare(t.id))}function eu(e){return[...e].sort((e,t)=>(e.cwd===void 0)-+(t.cwd===void 0)||(e.cwd??``).localeCompare(t.cwd??``)||Xl.indexOf(Ql(e))-Xl.indexOf(Ql(t))||e.id.localeCompare(t.id))}function tu(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(ru(c))<=n?c:e.slice(o)}function nu(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 ru(e){return nu(e).join(``)}function iu(e,t){let n=nu(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 au(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 ou(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 su({loadRows:e,onStop:t,onStart:n,startTrustQuestion:r,trustStatusCommand:a,onOpenPr:o,onAttach:s,filteredByCwd:l=!1,filteredByName:u=!1,filteredByPr:f=!1,stateFilter:m,refreshMs:h=2e3,initialSelectedId:g,initialGroupByDirectory:_=!1}){let{exit:v}=c(),{stdout:b}=p(),ee=Math.max(12,b.columns??80),O=W(),[te,ne]=C([]),[re,ie]=C(Date.now),[k,ae]=C(`loading`),[oe,se]=C(g),[ce,le]=C(!1),[ue,de]=C(_),[A,fe]=C(),j=A?.id,[pe,me]=C(`idle`),[M,N]=C(`idle`),[he,P]=C(),ge=S(!1),[_e,ve]=C(`idle`),[F,ye]=C(),[I,be]=C(),L=S(!1),[xe,Se]=C(`idle`),Ce=S(!1),R=S(!0),we=e=>{n!==void 0&&(L.current=!0,ve(`starting`),Promise.resolve().then(()=>n(e)).then(e=>{R.current&&(ye(e),ve(`started`))}).catch(()=>{R.current&&ve(`failed`)}).finally(()=>{L.current=!1}))},z=x(()=>{let e=te.filter(e=>m===void 0||Ql(e)===m);return ue?eu(e):$l(e)},[te,m,ue]),Te=x(()=>{let e=[],t=[...new Set(z.map(e=>e.cwd).filter(e=>e!==void 0))],n,r=0;return z.forEach((i,a)=>{let o=ue?i.cwd??`unverified`:Ql(i);if(o!==n){let n=ue?i.cwd===void 0?`Directory: unverified`:(()=>{let e=`Dir ${++r}: `,n=Math.max(4,ee-e.length),a=iu(tu(i.cwd,t,n),n),o=`${e}${a} — ${ru(i.cwd)}`;return O||D(o)<=ee?o:`${e}${a}`})():`${o}:`;e.push({kind:`group`,label:n})}e.push({kind:`row`,row:i,index:a}),n=o}),e},[z,ue,ee,O]);y(()=>{let t=new AbortController,n=!0,r,i=async()=>{try{let r=$l(await e(t.signal));if(!n||t.signal.aborted)return;let i=Date.now();ne(e=>au(e,r)?e:r),ie(e=>r.some(t=>t.nextLoopAt!==void 0&&ou(t.nextLoopAt,e)!==ou(t.nextLoopAt,i))?i:e),ae(`ready`)}catch{n&&!t.signal.aborted&&ae(`unavailable`)}finally{n&&!t.signal.aborted&&(r=setTimeout(()=>{i()},h))}};return i(),()=>{n=!1,r!==void 0&&clearTimeout(r),t.abort()}},[e,h]),y(()=>(R.current=!0,()=>{R.current=!1}),[]);let B=oe!==void 0&&z.some(e=>e.id===oe)?oe:z[0]?.id;y(()=>{se(e=>z.length===0||e!==void 0&&z.some(t=>t.id===e)?e:z[0]?.id)},[z]),d((e,i)=>{if(!ge.current&&!(Ce.current&&e!==`q`&&!(!O&&i.escape)&&!(i.ctrl&&e===`c`))&&!(L.current&&e!==`q`&&!(!O&&i.escape)&&!(i.ctrl&&e===`c`))){if(I!==void 0){e===`y`||e===`r`?(be(void 0),we(e===`y`?`trust`:`restricted`)):(e===`n`||i.escape)&&be(void 0);return}if(j!==void 0){if(e===`n`||i.escape){fe(void 0);return}if(e===`y`&&A?.action===`attach`){let e=A,t=z.find(t=>t.id===e.id);if(fe(void 0),k!==`ready`||!$(t)||t.generation!==e.generation||e.mode===void 0||s===void 0){me(`unavailable`);return}s({id:e.id,generation:e.generation,mode:e.mode,groupByDirectory:ue}),v();return}if(e===`y`){let e=A,n=z.find(t=>t.id===e?.id);if(fe(void 0),k!==`ready`||e===void 0||!$(n)||n.generation!==e.generation||t===void 0){N(`unavailable`);return}ge.current=!0,N(`stopping`),t(e.id,e.generation).then(()=>{R.current&&(P(e.id),N(`stopped`))}).catch(()=>{R.current&&N(`failed`)}).finally(()=>{ge.current=!1})}return}if(e===`q`||!O&&i.escape||i.ctrl&&e===`c`){v();return}if(e===`?`){le(e=>!e);return}if(e===`g`){Ee.clear(),de(e=>!e);return}if(e===`n`&&n!==void 0){if(r===void 0){we();return}L.current=!0,r().then(e=>{L.current=!1,R.current&&(e===void 0?we():be(e))}).catch(()=>{L.current=!1,R.current&&ve(`failed`)});return}if((e===`a`||e===`p`)&&s!==void 0){let t=z.find(e=>e.id===B);k!==`ready`||!$(t)?me(`unavailable`):(me(`idle`),N(`idle`),fe({id:t.id,generation:t.generation,action:`attach`,mode:e===`a`?`drive`:`observe`}));return}if(e===`o`&&o!==void 0){let e=z.find(e=>e.id===B);if(k!==`ready`||!$(e)||!e.pr){Se(`unavailable`);return}Ce.current=!0,Se(`opening`),o(e.id,e.pr.url,e.generation).then(()=>{R.current&&Se(`opened`)}).catch(()=>{R.current&&Se(`failed`)}).finally(()=>{Ce.current=!1});return}if(e===`s`&&t!==void 0){let e=z.find(e=>e.id===B);k!==`ready`||!$(e)?N(`unavailable`):(N(`idle`),me(`idle`),fe({id:e.id,generation:e.generation,action:`stop`}));return}if(!(O||z.length===0)&&(i.upArrow||i.downArrow)){let e=Math.max(0,z.findIndex(e=>e.id===B)),t=Math.max(0,Math.min(z.length-1,e+(i.downArrow?1:-1)));se(z[t]?.id)}}});let Ee=fn({enabled:O&&j===void 0&&I===void 0&&M!==`stopping`,itemCount:z.length,cancellable:!0,repeatable:!0,onSelect:e=>{se(z[e]?.id),N(`idle`)},onCancel:()=>{ge.current||v()}}),H=z.find(e=>e.id===B),De=k===`ready`&&$(H)?H.name:void 0,Oe=k===`ready`&&$(H)&&H.activity===`idle`&&H.nextLoopAt?ou(H.nextLoopAt,re):``,U=k===`ready`&&$(H)?H.pr:void 0,ke=Math.max(8,b.rows??24),Ae=[`Keys:`,O?`Number+Enter Select`:`↑/↓ Select`,`s Request stop`,`g Group state/dir`,...n===void 0?[]:[`n New session`],...s===void 0?[]:[`a Attach (drive)`,`p Peek (read only)`],...o===void 0?[]:[`o Open linked PR`],`y Confirm`,`n/Esc Cancel`,`q/Esc/Ctrl+C Close`,`? Toggle help`,`Activity ≠ liveness`,`Idle ≠ attach-ready`,`Close keeps sessions`],je=ce&&j===void 0&&M!==`stopping`,Me=2+(m===void 0?0:1)+ +(k===`loading`||k===`unavailable`||k===`ready`&&z.length===0)+(B===void 0?0:1)+(De===void 0?0:1)+(U===void 0?0:2)+ +!!Oe+(xe===`idle`?0:1)+(_e===`idle`?0:1)+(I===void 0?0:1)+(j===void 0?M===`idle`?0:1:O?1:2)+ +(j===void 0&&pe!==`idle`)+1+(je?Ae.length:0)+2,Ne=Math.max(1,ke-Me),Pe=Math.max(0,Te.findIndex(e=>e.kind===`row`&&e.row.id===B)),Fe=Math.min(Math.max(0,Pe-Math.floor(Ne/2)),Math.max(0,Te.length-Ne)),Ie=O?Te:Te.slice(Fe,Fe+Ne),Le=I===void 0?[]:Zl([`Not trusted: ${I.folder}`,`Trusting it loads the project's own settings, hooks, plugins, skills and MCP servers:`,...I.loads],O?1/0:Ne,a),G=O?{}:{wrap:`truncate-end`},Re=s!==void 0&&k===`ready`&&$(H),ze=M===`stopping`?`Stop in progress; wait for result.`:I===void 0?j===void 0?O?`Type a number and Enter to select; s Stop;${Re?` a Attach; p Peek;`:``}${n?` n New;`:``}${o?` o Open PR;`:``} g Group; Escape to close; ? Help.`:`↑↓ Navigate s Stop${Re?` a Attach p Peek`:``}${n?` n New`:``}${o?` o Open PR`:``} g Group ? Help q/Esc Close`:`Confirm ${A?.action===`attach`?`attach`:`stop`} or cancel before closing.`:`Answer the trust question or cancel before closing.`,Be=e=>A?.action===`attach`&&A.mode!==void 0?`${A.mode===`drive`?`Attach to`:`Peek at`} ${e} to ${Yl[A.mode]}?`:`Stop ${e}?`;return E(i,{flexDirection:`column`,...O?{}:{height:ke},children:[E(V,{...G,children:[l?`Background sessions in selected directory`:`Background sessions across projects`,u?` · name filter active`:``,f?` · PR filter active`:``]}),E(V,{...G,children:[z.length,` supervised session(s). Foreground peers and saved records are separate.`]}),m!==void 0&&E(V,{...G,children:[`State: `,m]}),k===`loading`&&T(V,{...G,children:`Loading supervised sessions...`}),k===`unavailable`&&T(V,{...G,children:`Supervised session discovery unavailable; last verified rows remain below.`}),k===`ready`&&z.length===0&&T(V,{...G,children:`No supervised sessions.`}),Le.map((e,t)=>T(V,{...G,children:e},`trust-${t}`)),I===void 0&&Fe>0&&!O&&E(V,{children:[Fe,` more above`]}),(I===void 0?Ie:[]).map(e=>e.kind===`group`?T(V,{...G,children:e.label},`group-${e.label}`):E(V,{...O?{}:{wrap:`truncate-end`},children:[O?Hn(e.index):e.row.id===B?`> `:` `,e.row.name&&$(e.row)?O?`${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,k===`ready`&&$(e.row)&&e.row.activity===`idle`&&e.row.nextLoopAt?` ${ou(e.row.nextLoopAt,re)}`:``,e.row.problem?` ${e.row.problem}`:``,k===`ready`&&$(e.row)&&e.row.pr?` ${e.row.pr.host} ${e.row.pr.kind===`pull`?`#`:`!`}${e.row.pr.number}`:``]},`row-${e.row.id}`)),I===void 0&&!O&&Fe+Ie.length<Te.length&&E(V,{children:[Te.length-Fe-Ie.length,` more below`]}),B!==void 0&&E(V,{...G,children:[`Selected `,B]}),De!==void 0&&E(V,{...G,children:[`Name: `,De]}),U!==void 0&&E(V,{...G,children:[`PR: `,U.host,` `,U.kind===`pull`?`#`:`!`,U.number]}),U!==void 0&&E(V,{...G,children:[`URL: `,U.url]}),Oe&&T(V,{...G,children:Oe}),xe===`opening`&&T(V,{...G,children:`Opening linked PR...`}),xe===`opened`&&T(V,{...G,children:`Opened linked PR.`}),xe===`failed`&&T(V,{...G,children:`PR link changed or could not be opened.`}),xe===`unavailable`&&T(V,{...G,children:`No verified PR link is available.`}),_e===`starting`&&T(V,{...G,children:`Starting a background session...`}),_e===`started`&&E(V,{...G,children:[`Started `,F,u||m!==void 0?` (may be hidden by filter)`:``]}),_e===`failed`&&T(V,{...G,children:`Start failed; check workspace trust or run session start --background for details.`}),I!==void 0&&T(V,{...G,children:`y Trust and start / r Start Restricted / n Cancel`}),j!==void 0&&(O?E(V,{children:[Be(j),` y Yes / n No`]}):E(w,{children:[T(V,{...G,children:Be(`…${j.slice(-8)}`)}),T(V,{...G,children:`y Yes / n No`})]})),j===void 0&&M===`unavailable`&&T(V,{...G,children:`This session cannot be stopped from the view.`}),j===void 0&&pe===`unavailable`&&T(V,{...G,children:`This session cannot be attached to from the view.`}),M===`stopping`&&T(V,{...G,children:`Stopping selected session; wait for confirmation.`}),M===`stopped`&&E(V,{...G,children:[`Stopped `,he]}),M===`failed`&&T(V,{...G,children:`Stop failed; session remains listed until verified otherwise.`}),O&&z.length>0&&j===void 0&&M!==`stopping`&&E(V,{children:[Vn(z.length,!0),Ee.buffer?` ${Ee.buffer}`:``]}),O&&Ee.invalid&&T(V,{children:`Selection out of range.`}),T(V,{...G,children:ze}),je&&Ae.map(e=>T(V,{...G,children:e},e))]})}async function cu(e){e.announce!==!1&&Pc({enabled:e.screenReader,channel:e.screenReaderChannel,hint:e.screenReaderHint});let t;process.stdin.resume();let n=s(T(Me,{enabled:e.screenReader,children:T(su,{loadRows:e.loadRows,onStop:e.onStop,onStart:e.onStart,startTrustQuestion:e.startTrustQuestion,onOpenPr:e.onOpenPr,onAttach:e=>{t=e},filteredByCwd:e.filteredByCwd,filteredByName:e.filteredByName,filteredByPr:e.filteredByPr,stateFilter:e.stateFilter,refreshMs:e.refreshMs,...e.initialSelectedId===void 0?{}:{initialSelectedId:e.initialSelectedId},...e.initialGroupByDirectory===void 0?{}:{initialGroupByDirectory:e.initialGroupByDirectory}})}),{isScreenReaderEnabled:e.screenReader,exitOnCtrlC:!1});try{await n.waitUntilExit()}finally{n.unmount()}return t===void 0?{kind:`closed`}:{kind:`attach`,...t}}function lu({providerDefinitions:e,reloadPluginCommandSource:t,userSettingsPath:n,settingsSources:r,formatResumeCommand:i}){return{getUserSettingsPath:()=>n,readSettings:e=>ue(e),reloadPluginCommandSource:e=>{t(e)},applyActiveModelChange:(e,t,i)=>(re(r,[ae(`user`,n)],t,i),{applied:!0}),getGitBranch:e=>A(e),getProviderDisplayName:t=>me(e,t)?.displayName??t,...i===void 0?{}:{formatResumeCommand:i}}}function uu(e){return{...e===void 0?{}:{$schema:e},version:1,bindings:{}}}function du(e,t){let n=jn(JSON.stringify(uu(t)),e);if(!n.ok)throw Error(n.diagnostic.message);return n.snapshot}var fu=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=du(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=R(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()===Ce(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(R(this.filePath),{recursive:!0});try{await Se(this.filePath,`${JSON.stringify(uu(this.#e),null,2)}\n`,{encoding:`utf8`,flag:`wx`,mode:384})}catch(e){if(!mu(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 xe(this.filePath,`utf8`)}catch(e){if(pu(e))return;this.#d({file:this.filePath,path:`$`,message:gu(e)});return}let t=jn(e,this.filePath);if(!t.ok){this.#d(t.diagnostic);return}this.#f(Object.freeze({...t.snapshot,generation:this.#r.generation+1}))}#d(e){this.#t?.(e),this.#f(Object.freeze({...this.#r,generation:this.#r.generation+1,diagnostic:e}))}#f(e){if(!this.#s){this.#r=e;for(let t of this.#n)t(e)}}};function pu(e){return hu(e)&&e.code===`ENOENT`}function mu(e){return hu(e)&&e.code===`EEXIST`}function hu(e){return e instanceof Error&&`code`in e}function gu(e){return e instanceof Error?e.message:String(e)}function _u(e){return new fu(e)}export{vl as TuiInteractionChannel,lu as createDefaultTuiCliAdapter,_u as createNodeKeybindingsSource,hc as createThemeCataloguePort,fc as createThemeRegistry,dt as escapeThemeText,ke as listBuiltInThemes,wt as parseThemeDocument,ut as quoteThemeText,Gl as renderApp,Kl as renderAttachedApp,cu as renderSupervisedSessionView,ft as sanitizeThemeProse};
|
|
32
|
+
`,T(V,{dimColor:!0,children:i})]}):null]})},onSelect:e=>t(e.id),onCancel:n})]})}function Oo(e){let t=ko(e),n=e.hasPendingPrompt&&t.kind!==`queued`?[`queued`]:[],r=[t.label,...n].join(` · `);return{...t,segments:n,text:r}}function ko(e){return e.activeToolCount>0?{kind:`tools`,label:`Tools (${e.activeToolCount})`,tone:`accent`}:e.isThinking?{kind:`thinking`,label:`Thinking`,tone:`warning`}:e.activeBackgroundTaskCount>0?{kind:`background`,label:`Background (${e.activeBackgroundTaskCount})`,tone:`accent`}:e.hasPendingPrompt?{kind:`queued`,label:`Queued`,tone:`warning`}:{kind:`idle`,label:`Idle`,tone:`muted`}}const Ao=` | `;function jo(e,t){return e>=90?t.text.error:e>=70?t.text.warning:t.text.success}function Mo({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r}){let i=K(),a=Oo({isThinking:e,activeToolCount:t,activeBackgroundTaskCount:n,hasPendingPrompt:r});return T(V,{color:i.text[a.tone],bold:a.kind!==`idle`,children:a.text})}function No({percentage:e,usedTokens:t,maxTokens:n}){return E(V,{color:jo(e,K()),children:[`Context: `,Math.round(e),`% (`,M(t),`/`,M(n),` tokens)`]})}function Po(){return T(V,{color:K().text.warning,bold:!0,children:`Observing — read only`})}function Fo({permissionMode:e}){return E(w,{children:[T(V,{color:K().text.accent,bold:!0,children:`Mode:`}),` `,T(V,{children:e})]})}function Io(e,t){return t||e!=="default"}function Lo({activePresetId:e}){return E(w,{children:[T(V,{color:K().text.accent,bold:!0,children:`Preset:`}),` `,T(V,{children:e})]})}function Ro(e){return e!==void 0&&e!=="default"}function zo({modelName:e,providerDisplayName:t,effort:n}){return E(V,{dimColor:!0,children:[t===void 0?e:`${t} ${e}`,n===void 0?``:` Effort: ${n}`]})}function Bo(e){let t=K(),n=e.showGitBranch&&e.gitBranch!==void 0&&e.gitBranch.length>0,r=W(),i=Io(e.permissionMode,r),a=e.activePresetId,o=Ro(a);return E(V,{children:[e.readOnly&&E(w,{children:[T(Po,{}),!r&&Ao]}),!r&&T(Mo,{isThinking:e.isThinking,activeToolCount:e.activeToolCount,activeBackgroundTaskCount:e.activeBackgroundTaskCount,hasPendingPrompt:e.hasPendingPrompt}),i&&E(w,{children:[Ao,T(Fo,{permissionMode:e.permissionMode})]}),o&&E(w,{children:[Ao,T(Lo,{activePresetId:a})]}),e.sessionName&&E(w,{children:[Ao,T(V,{color:t.text.session,children:e.sessionName})]}),n&&E(w,{children:[Ao,E(V,{dimColor:!0,children:[`git: `,e.gitBranch]})]}),Ao,T(zo,{modelName:e.modelName,providerDisplayName:e.providerDisplayName,effort:e.effort}),!r&&E(w,{children:[Ao,T(No,{percentage:e.contextPercentage,usedTokens:e.contextUsedTokens,maxTokens:e.contextMaxTokens})]})]})}function Vo({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=K();return E(i,{paddingLeft:1,paddingRight:1,justifyContent:`space-between`,children:[T(Bo,{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(V,{color:y.text.warning,bold:!0,children:[`[`,h,`]`]})]})}const Ho=g(null),Uo=Ho.Provider;function Wo(){let e=v(Ho);if(!e)throw Error(`TuiCliAdapterContext not provided`);return e}function Go({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 _=Wo(),v=x(()=>_.getGitBranch(e),[_,e,h]),y=x(()=>r===void 0?void 0:_.getProviderDisplayName(r),[_,r]);return d.enabled?T(Vo,{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(Po,{}):null}function Ko(e,t){let n=At(e);return{color:kt(t,n),icon:Ot[n],strikethrough:n===`error`||n===`denied`}}function qo({isThinking:e}){let t=K();return e?T(i,{marginBottom:1,children:T(V,{color:t.text.warning,children:`Thinking...`})}):T(w,{})}function Jo({activeTools:e}){let t=K(),n=_a();return E(i,{flexDirection:`column`,marginBottom:1,children:[T(V,{color:t.text.emphasis,bold:!0,children:`Tools:`}),T(V,{children:` `}),e.map((e,r)=>{let{color:a,icon:o,strikethrough:s}=Ko(e,t);return E(i,{flexDirection:`column`,children:[E(V,{color:a,strikethrough:s,children:[` `,o,` `,da(e.toolName,n),`(`,fa(e.firstArg),`)`]}),e.diffLines&&e.diffLines.length>0&&T(ka,{file:e.diffFile,lines:e.diffLines})]},`${e.toolName}-${r}`)})]})}function Yo(e,t,n,r){let i=t.map(e=>da(e.toolName,r)).join(`, `),a=[i.length>0?`${va.tool} ${i}`:void 0,e.length>0?e:n?va.thinking:void 0].filter(e=>e!==void 0);return a.length===0?T(w,{}):T(V,{children:a.join(` — `)})}function Xo({text:e,activeTools:t,isThinking:n=!1}){let r=K(),a=la(),o=t.length>0,s=e.length>0,c=W(),l=ga(),u=_a();return c?Yo(e,t,n,u):!o&&!s?T(qo,{isThinking:n}):E(i,{flexDirection:`column`,children:[o&&T(Jo,{activeTools:t}),s&&E(i,{flexDirection:`column`,marginBottom:1,children:[E(V,{color:r.text.accent,bold:!0,children:[l,`:`]}),T(V,{children:` `}),T(i,{marginLeft:2,children:T(H,{wrap:`wrap`,children:a(e)})})]})]})}function Zo(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?`> `:` `:Hn(r);return E(V,{...t&&r===void 0?{color:i.text.accent,bold:!0}:{},children:[a,Zo(e,n)]})}function $o({itemCount:e,buffer:t,invalid:n}){let r=Vn(e,!0);return E(i,{flexDirection:`column`,children:[E(V,{children:[r,t.length>0?` ${t}`:``]}),n&&T(V,{children:r})]})}function es(e,t){let n=e.findIndex(e=>e.id===t);return n<0?0:n}function ts(e){let[t,n]=h.useState(()=>({syntaxHighlighting:e.syntaxHighlighting,reducedMotion:e.reducedMotion}));return{toggles:t,setToggles:n}}function ns(e){let{themes:t,activeThemeId:n,preview:r}=e,[i,a]=h.useState(()=>es(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 rs(e,t){let{themes:n,select:r,cancel:i}=e,{focusedIndex:a,move:o}=ns(e),{toggles:s,setToggles:c}=ts(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=fn({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 is({themes:e,activeThemeId:t,focusedIndex:n,screenReader:r}){return e.length===0?T(V,{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 as(){return Ne()?T(w,{}):T(V,{dimColor:!0,children:`Colour is off for this terminal — themes apply, previews cannot show.`})}function os({skipped:e}){return e.length===0?T(w,{}):T(i,{flexDirection:`column`,marginTop:1,children:e.map((e,t)=>T(V,{dimColor:!0,children:` Skipped "${e.fileName}" — ${e.reason}`},t))})}function ss({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(V,{dimColor:!0,children:`syntax ${r(e.syntaxHighlighting)} · motion ${r(!e.reducedMotion)}${a}`}),n&&T(V,{dimColor:!0,children:`Change with /theme syntax on|off or /theme motion on|off`})]})}function cs({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($o,{itemCount:t,buffer:n.buffer,invalid:n.invalid}):T(Y,{hints:r})}function ls({picker:e}){let t=K(),n=W(),{themes:r,activeThemeId:a}=e,{focusedIndex:o,toggles:s,numbered:c}=rs(e,n);return E(i,{flexDirection:`column`,...n?{}:{borderStyle:`round`,borderColor:t.border.focused},paddingX:1,children:[T(V,{color:t.text.accent,bold:!0,children:`Theme`}),T(as,{}),T(ss,{toggles:s,reducedMotionPin:e.reducedMotionPin,screenReader:n}),T(i,{flexDirection:`column`,marginTop:1,children:T(is,{themes:r,activeThemeId:a,focusedIndex:o,screenReader:n})}),T(os,{skipped:e.skipped}),T(cs,{screenReader:n,itemCount:r.length,numbered:c})]})}function us({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(V,{color:t?n.text.accent:void 0,bold:t,children:`${a} ${e.transport.name.padEnd(18)} ${o} ${c}`})})}function ds(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 fs({registry:e,onClose:t}){let n=K(),r=ga(),[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 ds(a,s,l,e,c,u,f,t,p),E(i,{flexDirection:`column`,paddingX:2,paddingY:1,children:[T(V,{bold:!0,children:`Settings › Transports`}),T(i,{marginTop:1,flexDirection:`column`,children:a.map((e,t)=>T(us,{entry:e,selected:t===s},e.transport.name))}),E(i,{marginTop:1,flexDirection:`column`,children:[T(Y,{hints:m}),E(V,{dimColor:!0,children:[`A toggle is saved now and applies the next time `,r,` starts.`]})]}),l&&T(i,{marginTop:1,children:T(V,{color:n.text.warning,children:`Saving…`})}),d!==void 0&&T(i,{marginTop:1,children:T(V,{color:n.text.error,children:`Not saved — ${d}`})})]})}function ps({message:e}){return T(i,{paddingX:1,marginBottom:1,children:T(V,{color:K().text.warning,children:e})})}function ms({model:e}){return T(a,{items:e.staticItems,children:e=>e.kind===`banner`?T(Tt,{version:e.version},`logo`):T(Ra,{entry:e.entry},e.entry.id)},e.transcriptKey)}function hs({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(Qt,{entry:n.selectedEntry,page:n.detail.page,loading:n.detail.loading,error:n.detail.error}),e.isShuttingDown&&T(V,{color:t.text.warning,children:`Shutting down...`}),(r.isThinking||r.activeTools.length>0)&&E(i,{flexDirection:`column`,marginBottom:1,children:[T(Xo,{text:r.text,activeTools:r.activeTools,isThinking:r.isThinking}),r.isStalled&&T(V,{color:t.text.warning,children:`⚠ Still waiting on the provider — the network may be stalled. Esc to interrupt.`})]}),!r.isThinking&&r.lastErrorMessage&&T(V,{color:t.text.error,children:`✖ Last turn failed — the session is alive; type your next prompt when ready.`}),T(Xt,{entries:n.entries,focusedIndex:n.focusedIndex})]})}function gs({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(Kn,{snapshot:t.snapshot,selectedEntryId:t.selectedEntryId,onSelect:t.select,onClose:t.closeSwitcher,onAttach:t.attachToFork}),e.permissionRequest&&T(oo,{request:e.permissionRequest}),a&&T($a,{request:a,onAnswer:t=>e.resolveUserAction(a,t)}),n.visible&&T(Co,{callbacks:n.callbacks,onClose:n.close,addMessage:e=>n.addMessage(e.content)}),i.visible&&i.registry&&T(fs,{registry:i.registry,onClose:i.close}),r.visible&&T(Do,{sessions:r.sessions,onSelect:r.select,onCancel:r.cancel}),e.theme.picker.visible&&T(ls,{picker:e.theme.picker})]})}function _s({model:e}){let{input:t}=e;return E(w,{children:[T(Zt,{percentage:e.contextPercentage}),T(Ri,{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(Go,{...e.status})]})}function vs({viewModel:e}){let t=K(),n=Bn();return E(i,{flexDirection:`column`,children:[T(ms,{model:e}),!e.handoffSuspended&&E(w,{children:[e.updateNotice&&T(ps,{message:e.updateNotice}),e.coordinationError&&E(V,{color:t.text.error,children:[e.coordinationError,` Press Enter to retry.`]}),n.diagnostic&&T(V,{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(V,{color:t.text.warning,children:`Keybindings ${e.path}: ${e.message}`},`${e.path}:${e.code}`)),e.theme.unknownThemeNotice!==void 0&&T(V,{color:t.text.warning,children:e.theme.unknownThemeNotice}),T(wo,{notices:e.sessionEventNotices}),T(hs,{model:e}),T(gs,{model:e}),T(_s,{model:e})]})]})}function ys(e){return[...e.screenReader?[]:[{kind:`banner`,version:e.version??`0.0.0`}],...e.history.map(e=>({kind:`entry`,entry:e}))]}function bs(e){let t=e.forceExit??(e=>process.exit(e));if(e.isShuttingDown){t(130);return}e.graceful()}function xs(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 Ss={promptStart:`A`,promptEnd:`B`,turnStart:`C`,turnEnd:`D`};function Cs(e){return`\x1b]133;${Ss[e]}\x07`}function ws(e){let t=e.write??(e=>{process.stdout.write(e)});return{emit(n){!e.enabled||!e.supported()||t(Cs(n))}}}function Ts(e,t){return e.executionId??`${e.toolName}#${t}`}function Es(e){let t=new Set;return e.forEach((e,n)=>{e.isRunning&&t.add(Ts(e,n))}),t}function Ds(e){let{enabled:t,isThinking:n,activeTools:r,awaitingAnswer:i}=e,a=x(()=>xs({enabled:t}),[t]),o=Dr(),s=Ar(),c=x(()=>ws({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=Es(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 Os(e){return!!(e.permissionRequest||e.pendingUserAction||e.pluginVisible||e.transportVisible||e.sessionPickerVisible||e.workspaceSwitcherVisible||e.historySearchOpen||e.themePickerVisible||e.coordinationBlocked)}function ks(e){Q(e.isThinking?`thinking`:`background-detail`,t=>{if(Os(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 As(e){Q(`app`,t=>{t.includes(`open-workspace-switcher`)&&(e.permissionRequest||e.pendingUserAction||e.pluginVisible||e.sessionPickerVisible||e.historySearchOpen||e.themePickerVisible||e.coordinationBlocked||e.isShuttingDown||e.toggleWorkspaceSwitcher())})}function js(e){Q(`recovery`,t=>{e.recoveryError!==void 0&&!e.recoveryPending&&t.includes(`retry`)&&e.retryRecovery()})}function Ms(e,t){return e===``||t&&e===`]`}function Ns(e){let{exit:t}=c(),n=n=>{bs({isShuttingDown:e.isShuttingDown,graceful:()=>void e.shutdown(n).finally(()=>t())})};d((t,r)=>{(r.ctrl&&t===`c`||e.attached&&Ms(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 Ps(e){ks(e),js(e),As(e),Ns(e);let t=W();return Ds({enabled:t,isThinking:e.isThinking,activeTools:e.activeTools,awaitingAnswer:e.permissionRequest!==null||e.pendingUserAction!==null}),t}function Fs(){return Promise.reject(Error(`Plugin management is unavailable in this host.`))}function Is(){return{listInstalled:Fs,listAvailablePlugins:Fs,install:Fs,uninstall:Fs,enable:Fs,disable:Fs,marketplaceAdd:Fs,marketplaceRemove:Fs,marketplaceUpdate:Fs,marketplaceList:Fs,reloadPlugins:Fs}}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(P(j(t))),[e.addEntry]),r=_(t=>{e.setSessionPickerVisible(!1),e.onSessionSwitch(t)},[e.onSessionSwitch,e.setSessionPickerVisible]),i=_(()=>{e.setSessionPickerVisible(!1),e.addEntry(P(j(`Session resume cancelled.`)))},[e.addEntry,e.setSessionPickerVisible]),a=e.hostSessions??ce(e.sessionStore,e.cwd),o=e.sessionPickerVisible&&a.length===0;return y(()=>{o&&(e.setSessionPickerVisible(!1),e.addEntry(P(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=Ps({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=ga();y(()=>{let n=B(e??``),r=B(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 le(e.readSettings(e.getUserSettingsPath()))}function Js(){let e=Wo(),[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=Wo();return _(i=>{let a=e=>n(P(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){Q(`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(()=>Ft(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:It(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===F)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={...O},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=Wo(),[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=ke(),t=[]){let n=new Map(e.map(e=>[e.id,e]));return{list:()=>e,skipped:()=>t,get:e=>n.get(e),resolve:e=>{if(e===void 0||e===U)return{theme:Ae(n.get(U))};let t=n.get(e);return t?{theme:t}:{theme:Ae(n.get(U)),unknownId:e}}}}function pc(e){return`Theme "${e}" is not installed — using "${U}".`}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(()=>ys({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(ze,{theme:t.theme.resolved,reducedMotion:t.theme.reducedMotion,syntaxHighlighting:t.theme.syntaxHighlighting,children:T(vs,{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(Uo,{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 ye{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 B(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(P(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,a){return new Promise(o=>{this.entries.push({toolName:e,toolArgs:t,resolve:o,...n===void 0?{}:{id:n},...r===void 0?{}:{canPersistProjectPermission:r},...i===void 0?{}:{requestedByPeer:i},...a===void 0?{}:{requester:a}}),this.processNext()})}dismissById(e){let t=this.entries.filter(t=>t.id===e);if(t.length===0)return!1;let n=this.entries[0]?.id===e;this.entries=this.entries.filter(t=>t.id!==e);for(let e of t)e.resolve(!1);return n&&(this.processing=!1,this.currentRequest=null,this.processNext()),!0}cancelAll(){let e=this.entries;this.entries=[],this.processing=!1,this.currentRequest=null;for(let t of e)t.resolve(!1);this.onChange()}processNext(){if(this.processing)return;let e=this.entries[0];if(!e){this.currentRequest=null,this.onChange();return}this.processing=!0,this.currentRequest={toolName:e.toolName,toolArgs:e.toolArgs,...e.canPersistProjectPermission===void 0?{}:{canPersistProjectPermission:e.canPersistProjectPermission},...e.requestedByPeer===void 0?{}:{requestedByPeer:e.requestedByPeer},...e.requester===void 0?{}:{requester:e.requester},resolve:t=>{this.entries[0]===e&&(this.entries.shift(),this.processing=!1,this.currentRequest=null,e.resolve(t),setTimeout(()=>this.processNext(),0))}},this.onChange()}};function sl(e,t){let n=null;try{n=t.getActiveDriverId?.()??null}catch{n=null}return P(pe(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,requester:s})=>{n?.onNeedsInput();let c=o?.startsWith(`peer:`)?ge(o):void 0;this.options.requestPermission(r,i,t,a,c,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.environment===void 0?{}:{environment:e.environment},...e.resolveProviderCredential===void 0?{}:{resolveProviderCredential:e.resolveProviderCredential},...e.editCheckpointStore===void 0?{}:{editCheckpointStore:e.editCheckpointStore},...e.externalEventVerifierFactory===void 0?{}:{externalEventVerifierFactory:e.externalEventVerifierFactory},...e.externalEventGrantHistory===void 0?{}:{externalEventGrantHistory:e.externalEventGrantHistory},...e.model===void 0?{}:{model:e.model},...e.effort===void 0?{}:{effort:e.effort},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt},...e.responseFormat===void 0?{}:{responseFormat:e.responseFormat},...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},permissionMode:e.permissionMode,maxTurns:e.maxTurns,sessionStore:e.sessionStore,disableSessionLoops:e.disableSessionLoops,resolveDefaultLoopPrompt:e.resolveDefaultLoopPrompt,resumeSessionId:e.resumeSessionId,forkSession:e.forkSession,...e.workspaceMovedFrom===void 0?{}:{workspaceMovedFrom:e.workspaceMovedFrom},sessionName:e.sessionName,autoName:!0,backgroundTaskRunners:e.backgroundTaskRunners,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.agentDefinitions===void 0?{}:{agentDefinitions:e.agentDefinitions},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.pluginDirectories===void 0?{}:{pluginDirectories:e.pluginDirectories},...e.additionalTools===void 0?{}:{additionalTools:e.additionalTools},...e.defaultTools===void 0?{}:{defaultTools:e.defaultTools},...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},...e.sandboxClient===void 0?{}:{sandboxClient:e.sandboxClient},commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,...e.remoteCommandPolicy?{remoteCommandPolicy:e.remoteCommandPolicy}:{},language:e.language,agentName:e.agentName,activePresetId:e.activePresetId,persona:e.persona,systemPrompt:e.systemPrompt,appendSystemPrompt:e.appendSystemPrompt,allowedTools:e.allowedTools,deniedTools:e.deniedTools,enableParallelSubagents:e.enableParallelSubagents,selfVerification:e.selfVerification,terminalHandoff:e.terminalHandoff,...e.providerDefinitions?{providerDefinitions:e.providerDefinitions}:{},...e.memoryStore?{memoryStore:e.memoryStore}:{},...e.automaticMemory?{automaticMemory:e.automaticMemory}:{},...e.recallMemory?{recallMemory:e.recallMemory}:{},...e.promptHistory?{promptHistory:e.promptHistory}:{}}}function 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=e.executionId===void 0?this.activeTools.findLastIndex(t=>t.toolName===e.toolName&&t.isRunning):this.activeTools.findIndex(t=>t.executionId===e.executionId&&t.isRunning);if(t!==-1){let n=[...this.activeTools];n[t]=e,this.activeTools=n}this.isThinking&&!this.activeTools.some(e=>e.isRunning)&&this.armStallTimer(),this.notify()};onThinking=e=>{this.isThinking=e,e?(this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.lastErrorMessage=null,this.armStallTimer()):(this.isAborting=!1,this.activeTools=[],this.clearStallTimer()),this.notify()};onComplete=e=>{this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.contextState={percentage:e.contextState.usedPercentage,usedTokens:e.contextState.usedTokens,maxTokens:e.contextState.maxTokens},this.notify()};onInterrupted=()=>{this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onError=e=>{this.clearStallTimer(),this.lastErrorMessage=e?.message??`Unknown error`,this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onContextUpdate=e=>{this.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})};syncHistory(e){e.length!==0&&(this.history=this.withLocalNotices(e),this.notify())}syncHostHistory(e,t){this.history=[...this.withLocalNotices(e),...t],this.notify()}withLocalNotices(e){let t=[],n=0;for(let r of this.localNotices){let i=Math.min(r.afterSessionEntries,e.length);for(;n<i;)t.push(e[n++]);t.push(r.entry)}for(;n<e.length;)t.push(e[n++]);return t}addEntry(e){this.localNotices.push({entry:e,afterSessionEntries:this.history.length-this.localNotices.length}),this.history=[...this.history,e],this.notify()}addUserEcho(e){this.history=[...this.history,e],this.notify()}clearHistory(){this.history=[],this.localNotices=[],this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()}setPendingPrompt(e){this.pendingPrompt=e,this.notify()}setAborting(e){this.isAborting=e,this.notify()}setContextState(e){this.contextState=e,this.notify()}addSessionEventNotice(e){this.sessionNoticeStore.add(e),this.notify()}addAttentionRecap(e){this.sessionNoticeStore.addAttentionRecap(e),this.notify()}addSessionEventDeliveryError(e,t){this.sessionNoticeStore.addDeliveryError(e,t),this.notify()}syncExecutionWorkspaceSnapshot(e){let t=this.selectedExecutionEntryId,n=t!==void 0&&e.entries.some(e=>e.id===t)?t:e.selectedEntryId??e.entries[0]?.id;this.executionWorkspaceSnapshot={...e,...n?{selectedEntryId:n}:{}},this.selectedExecutionEntryId=n,this.notify()}selectExecutionWorkspaceEntry(e){this.executionWorkspaceSnapshot?.entries.some(t=>t.id===e)&&(this.selectedExecutionEntryId=e,this.executionWorkspaceSnapshot={...this.executionWorkspaceSnapshot,selectedEntryId:e},this.notify())}dispose(){this.clearStallTimer(),this.debouncedStreamNotify.flush(),this.onChange=null}};function 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,a)=>this.permissions.enqueue(e,t,n,r,i,a),askUser:(e,t)=>this.askUser(e,t),dismissPrompt:e=>this.dismissPromptById(e),...e.onSessionEventDeliveryError?{onDeliveryError:e.onSessionEventDeliveryError}:{}}),this.lifecycle=new 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(P(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(P(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(P(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/Et}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(!oe(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 ne(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?F: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:F}}),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:F});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:`)?ge(e.requesterDriverId):void 0,n=this.promptGeneration;this.permissions.enqueue(e.toolName,e.toolArgs,e.id,e.canPersistProjectPermission,t,e.requester).then(t=>this.answer(n,e.id,{type:`permission-response`,id:e.id,result:t}))}askUser(e){if(this.showsPrompt(e.id))return;this.attention?.onNeedsInput();let t=this.promptGeneration;this.userActions.enqueue(e.request,e.id).then(n=>this.answer(t,e.id,{type:`ask-response`,id:e.id,response:n}))}answer(e,t,n){e===this.promptGeneration&&(this.shownPromptIds.delete(t),!this.settledPromptIds.delete(t)&&this.send(n))}dismissPrompt(e){this.settledPromptIds.add(e);let t=this.userActions.dismissById(e),n=this.permissions.dismissById(e);!t&&!n&&this.settledPromptIds.delete(e)}showUiIntent(e){if(e.requesterDriverId===void 0){this.uiEvents.emitUiIntent(e);return}if(zl.has(e.intent.type)){this.notice(`That screen is not available while attached to a daemon.`);return}let t={...e,requesterDriverId:F};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:To(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(To(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&&!I(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(P(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.environment===void 0?{}:{environment:e.environment},...e.resolveProviderCredential===void 0?{}:{resolveProviderCredential:e.resolveProviderCredential},...e.orgPolicy===void 0?{}:{orgPolicy:e.orgPolicy},...e.externalEventVerifierFactory===void 0?{}:{externalEventVerifierFactory:e.externalEventVerifierFactory},...e.externalEventGrantHistory===void 0?{}:{externalEventGrantHistory:e.externalEventGrantHistory},...e.providerDefinitions?{providerDefinitions:e.providerDefinitions}:{},...e.modelId===void 0?{}:{model:e.modelId},...e.effort===void 0?{}:{effort:e.effort},...e.temperature===void 0?{}:{temperature:e.temperature},...e.maxOutputTokens===void 0?{}:{maxOutputTokens:e.maxOutputTokens},...e.presetSystemPrompt===void 0?{}:{presetSystemPrompt:e.presetSystemPrompt},...e.appendSystemPrompt===void 0?{}:{appendSystemPrompt:e.appendSystemPrompt},...e.responseFormat===void 0?{}:{responseFormat:e.responseFormat},...e.outputStyle===void 0?{}:{outputStyle:e.outputStyle},permissionMode:e.permissionMode,maxTurns:e.maxTurns,allowedTools:e.allowedTools,deniedTools:e.deniedTools,sessionStore:e.sessionStore,disableSessionLoops:e.disableSessionLoops,resolveDefaultLoopPrompt:e.resolveDefaultLoopPrompt,resumeSessionId:t,forkSession:e.forkSession,sessionName:e.sessionName,backgroundTaskRunners:e.backgroundTaskRunners,...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},subagentRunnerFactory:e.subagentRunnerFactory,...e.agentDefinitions===void 0?{}:{agentDefinitions:e.agentDefinitions},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.pluginDirectories===void 0?{}:{pluginDirectories:e.pluginDirectories},...e.additionalTools===void 0?{}:{additionalTools:e.additionalTools},...e.defaultTools===void 0?{}:{defaultTools:e.defaultTools},...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},...e.sandboxClient===void 0?{}:{sandboxClient:e.sandboxClient},commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,remoteCommandPolicy:e.remoteCommandPolicy,transportRegistry:e.transportRegistry,bindTransports:e.bindTransports,language:e.language,reloadPluginCommandSource:e.reloadPluginCommandSource,agentName:e.agentName,activePresetId:e.activePresetId,persona:e.persona,enableParallelSubagents:e.enableParallelSubagents,selfVerification:e.selfVerification,...e.memoryStore?{memoryStore:e.memoryStore}:{},...e.automaticMemory?{automaticMemory:e.automaticMemory}:{},...e.recallMemory?{recallMemory:e.recallMemory}:{},...e.screenReader===void 0?{}:{screenReader:e.screenReader},promptHistory:e.promptHistory}}async function 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(ha,{name:t.productDisplayName,modelCommandToolPrefix:t.modelCommandToolPrefix,children:T(zn,{source:t.keybindingsSource,children:T(Me,{enabled:r,children:T(kr,{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(Er,{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 Zl(e,t,n){if(e.length<=t)return e;let r=Math.max(1,t-1),i=n===void 0?`check workspace trust in the terminal`:`see ${n}`;return[...e.slice(0,r),`… ${e.length-r} more — ${i}`]}function $(e){return e?.liveness===`alive`&&e.control===`available`&&e.generation!==void 0}function Ql(e){return e.liveness===`dead`?`dead`:$(e)?e.activity:`unverified`}function $l(e){return[...e].sort((e,t)=>Xl.indexOf(Ql(e))-Xl.indexOf(Ql(t))||e.id.localeCompare(t.id))}function eu(e){return[...e].sort((e,t)=>(e.cwd===void 0)-+(t.cwd===void 0)||(e.cwd??``).localeCompare(t.cwd??``)||Xl.indexOf(Ql(e))-Xl.indexOf(Ql(t))||e.id.localeCompare(t.id))}function tu(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(ru(c))<=n?c:e.slice(o)}function nu(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 ru(e){return nu(e).join(``)}function iu(e,t){let n=nu(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 au(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 ou(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 su({loadRows:e,onStop:t,onStart:n,startTrustQuestion:r,trustStatusCommand:a,onOpenPr:o,onAttach:s,filteredByCwd:l=!1,filteredByName:u=!1,filteredByPr:f=!1,stateFilter:m,refreshMs:h=2e3,initialSelectedId:g,initialGroupByDirectory:_=!1}){let{exit:v}=c(),{stdout:b}=p(),ee=Math.max(12,b.columns??80),O=W(),[te,ne]=C([]),[re,ie]=C(Date.now),[k,ae]=C(`loading`),[oe,se]=C(g),[ce,le]=C(!1),[ue,de]=C(_),[A,fe]=C(),j=A?.id,[pe,me]=C(`idle`),[M,N]=C(`idle`),[he,P]=C(),ge=S(!1),[_e,ve]=C(`idle`),[F,ye]=C(),[I,be]=C(),L=S(!1),[xe,Se]=C(`idle`),Ce=S(!1),R=S(!0),we=e=>{n!==void 0&&(L.current=!0,ve(`starting`),Promise.resolve().then(()=>n(e)).then(e=>{R.current&&(ye(e),ve(`started`))}).catch(()=>{R.current&&ve(`failed`)}).finally(()=>{L.current=!1}))},z=x(()=>{let e=te.filter(e=>m===void 0||Ql(e)===m);return ue?eu(e):$l(e)},[te,m,ue]),Te=x(()=>{let e=[],t=[...new Set(z.map(e=>e.cwd).filter(e=>e!==void 0))],n,r=0;return z.forEach((i,a)=>{let o=ue?i.cwd??`unverified`:Ql(i);if(o!==n){let n=ue?i.cwd===void 0?`Directory: unverified`:(()=>{let e=`Dir ${++r}: `,n=Math.max(4,ee-e.length),a=iu(tu(i.cwd,t,n),n),o=`${e}${a} — ${ru(i.cwd)}`;return O||D(o)<=ee?o:`${e}${a}`})():`${o}:`;e.push({kind:`group`,label:n})}e.push({kind:`row`,row:i,index:a}),n=o}),e},[z,ue,ee,O]);y(()=>{let t=new AbortController,n=!0,r,i=async()=>{try{let r=$l(await e(t.signal));if(!n||t.signal.aborted)return;let i=Date.now();ne(e=>au(e,r)?e:r),ie(e=>r.some(t=>t.nextLoopAt!==void 0&&ou(t.nextLoopAt,e)!==ou(t.nextLoopAt,i))?i:e),ae(`ready`)}catch{n&&!t.signal.aborted&&ae(`unavailable`)}finally{n&&!t.signal.aborted&&(r=setTimeout(()=>{i()},h))}};return i(),()=>{n=!1,r!==void 0&&clearTimeout(r),t.abort()}},[e,h]),y(()=>(R.current=!0,()=>{R.current=!1}),[]);let B=oe!==void 0&&z.some(e=>e.id===oe)?oe:z[0]?.id;y(()=>{se(e=>z.length===0||e!==void 0&&z.some(t=>t.id===e)?e:z[0]?.id)},[z]),d((e,i)=>{if(!ge.current&&!(Ce.current&&e!==`q`&&!(!O&&i.escape)&&!(i.ctrl&&e===`c`))&&!(L.current&&e!==`q`&&!(!O&&i.escape)&&!(i.ctrl&&e===`c`))){if(I!==void 0){e===`y`||e===`r`?(be(void 0),we(e===`y`?`trust`:`restricted`)):(e===`n`||i.escape)&&be(void 0);return}if(j!==void 0){if(e===`n`||i.escape){fe(void 0);return}if(e===`y`&&A?.action===`attach`){let e=A,t=z.find(t=>t.id===e.id);if(fe(void 0),k!==`ready`||!$(t)||t.generation!==e.generation||e.mode===void 0||s===void 0){me(`unavailable`);return}s({id:e.id,generation:e.generation,mode:e.mode,groupByDirectory:ue}),v();return}if(e===`y`){let e=A,n=z.find(t=>t.id===e?.id);if(fe(void 0),k!==`ready`||e===void 0||!$(n)||n.generation!==e.generation||t===void 0){N(`unavailable`);return}ge.current=!0,N(`stopping`),t(e.id,e.generation).then(()=>{R.current&&(P(e.id),N(`stopped`))}).catch(()=>{R.current&&N(`failed`)}).finally(()=>{ge.current=!1})}return}if(e===`q`||!O&&i.escape||i.ctrl&&e===`c`){v();return}if(e===`?`){le(e=>!e);return}if(e===`g`){Ee.clear(),de(e=>!e);return}if(e===`n`&&n!==void 0){if(r===void 0){we();return}L.current=!0,r().then(e=>{L.current=!1,R.current&&(e===void 0?we():be(e))}).catch(()=>{L.current=!1,R.current&&ve(`failed`)});return}if((e===`a`||e===`p`)&&s!==void 0){let t=z.find(e=>e.id===B);k!==`ready`||!$(t)?me(`unavailable`):(me(`idle`),N(`idle`),fe({id:t.id,generation:t.generation,action:`attach`,mode:e===`a`?`drive`:`observe`}));return}if(e===`o`&&o!==void 0){let e=z.find(e=>e.id===B);if(k!==`ready`||!$(e)||!e.pr){Se(`unavailable`);return}Ce.current=!0,Se(`opening`),o(e.id,e.pr.url,e.generation).then(()=>{R.current&&Se(`opened`)}).catch(()=>{R.current&&Se(`failed`)}).finally(()=>{Ce.current=!1});return}if(e===`s`&&t!==void 0){let e=z.find(e=>e.id===B);k!==`ready`||!$(e)?N(`unavailable`):(N(`idle`),me(`idle`),fe({id:e.id,generation:e.generation,action:`stop`}));return}if(!(O||z.length===0)&&(i.upArrow||i.downArrow)){let e=Math.max(0,z.findIndex(e=>e.id===B)),t=Math.max(0,Math.min(z.length-1,e+(i.downArrow?1:-1)));se(z[t]?.id)}}});let Ee=fn({enabled:O&&j===void 0&&I===void 0&&M!==`stopping`,itemCount:z.length,cancellable:!0,repeatable:!0,onSelect:e=>{se(z[e]?.id),N(`idle`)},onCancel:()=>{ge.current||v()}}),H=z.find(e=>e.id===B),De=k===`ready`&&$(H)?H.name:void 0,Oe=k===`ready`&&$(H)&&H.activity===`idle`&&H.nextLoopAt?ou(H.nextLoopAt,re):``,U=k===`ready`&&$(H)?H.pr:void 0,ke=Math.max(8,b.rows??24),Ae=[`Keys:`,O?`Number+Enter Select`:`↑/↓ Select`,`s Request stop`,`g Group state/dir`,...n===void 0?[]:[`n New session`],...s===void 0?[]:[`a Attach (drive)`,`p Peek (read only)`],...o===void 0?[]:[`o Open linked PR`],`y Confirm`,`n/Esc Cancel`,`q/Esc/Ctrl+C Close`,`? Toggle help`,`Activity ≠ liveness`,`Idle ≠ attach-ready`,`Close keeps sessions`],je=ce&&j===void 0&&M!==`stopping`,Me=2+(m===void 0?0:1)+ +(k===`loading`||k===`unavailable`||k===`ready`&&z.length===0)+(B===void 0?0:1)+(De===void 0?0:1)+(U===void 0?0:2)+ +!!Oe+(xe===`idle`?0:1)+(_e===`idle`?0:1)+(I===void 0?0:1)+(j===void 0?M===`idle`?0:1:O?1:2)+ +(j===void 0&&pe!==`idle`)+1+(je?Ae.length:0)+2,Ne=Math.max(1,ke-Me),Pe=Math.max(0,Te.findIndex(e=>e.kind===`row`&&e.row.id===B)),Fe=Math.min(Math.max(0,Pe-Math.floor(Ne/2)),Math.max(0,Te.length-Ne)),Ie=O?Te:Te.slice(Fe,Fe+Ne),Le=I===void 0?[]:Zl([`Not trusted: ${I.folder}`,`Trusting it loads the project's own settings, hooks, plugins, skills and MCP servers:`,...I.loads],O?1/0:Ne,a),G=O?{}:{wrap:`truncate-end`},Re=s!==void 0&&k===`ready`&&$(H),ze=M===`stopping`?`Stop in progress; wait for result.`:I===void 0?j===void 0?O?`Type a number and Enter to select; s Stop;${Re?` a Attach; p Peek;`:``}${n?` n New;`:``}${o?` o Open PR;`:``} g Group; Escape to close; ? Help.`:`↑↓ Navigate s Stop${Re?` a Attach p Peek`:``}${n?` n New`:``}${o?` o Open PR`:``} g Group ? Help q/Esc Close`:`Confirm ${A?.action===`attach`?`attach`:`stop`} or cancel before closing.`:`Answer the trust question or cancel before closing.`,Be=e=>A?.action===`attach`&&A.mode!==void 0?`${A.mode===`drive`?`Attach to`:`Peek at`} ${e} to ${Yl[A.mode]}?`:`Stop ${e}?`;return E(i,{flexDirection:`column`,...O?{}:{height:ke},children:[E(V,{...G,children:[l?`Background sessions in selected directory`:`Background sessions across projects`,u?` · name filter active`:``,f?` · PR filter active`:``]}),E(V,{...G,children:[z.length,` supervised session(s). Foreground peers and saved records are separate.`]}),m!==void 0&&E(V,{...G,children:[`State: `,m]}),k===`loading`&&T(V,{...G,children:`Loading supervised sessions...`}),k===`unavailable`&&T(V,{...G,children:`Supervised session discovery unavailable; last verified rows remain below.`}),k===`ready`&&z.length===0&&T(V,{...G,children:`No supervised sessions.`}),Le.map((e,t)=>T(V,{...G,children:e},`trust-${t}`)),I===void 0&&Fe>0&&!O&&E(V,{children:[Fe,` more above`]}),(I===void 0?Ie:[]).map(e=>e.kind===`group`?T(V,{...G,children:e.label},`group-${e.label}`):E(V,{...O?{}:{wrap:`truncate-end`},children:[O?Hn(e.index):e.row.id===B?`> `:` `,e.row.name&&$(e.row)?O?`${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,k===`ready`&&$(e.row)&&e.row.activity===`idle`&&e.row.nextLoopAt?` ${ou(e.row.nextLoopAt,re)}`:``,e.row.problem?` ${e.row.problem}`:``,k===`ready`&&$(e.row)&&e.row.pr?` ${e.row.pr.host} ${e.row.pr.kind===`pull`?`#`:`!`}${e.row.pr.number}`:``]},`row-${e.row.id}`)),I===void 0&&!O&&Fe+Ie.length<Te.length&&E(V,{children:[Te.length-Fe-Ie.length,` more below`]}),B!==void 0&&E(V,{...G,children:[`Selected `,B]}),De!==void 0&&E(V,{...G,children:[`Name: `,De]}),U!==void 0&&E(V,{...G,children:[`PR: `,U.host,` `,U.kind===`pull`?`#`:`!`,U.number]}),U!==void 0&&E(V,{...G,children:[`URL: `,U.url]}),Oe&&T(V,{...G,children:Oe}),xe===`opening`&&T(V,{...G,children:`Opening linked PR...`}),xe===`opened`&&T(V,{...G,children:`Opened linked PR.`}),xe===`failed`&&T(V,{...G,children:`PR link changed or could not be opened.`}),xe===`unavailable`&&T(V,{...G,children:`No verified PR link is available.`}),_e===`starting`&&T(V,{...G,children:`Starting a background session...`}),_e===`started`&&E(V,{...G,children:[`Started `,F,u||m!==void 0?` (may be hidden by filter)`:``]}),_e===`failed`&&T(V,{...G,children:`Start failed; check workspace trust or run session start --background for details.`}),I!==void 0&&T(V,{...G,children:`y Trust and start / r Start Restricted / n Cancel`}),j!==void 0&&(O?E(V,{children:[Be(j),` y Yes / n No`]}):E(w,{children:[T(V,{...G,children:Be(`…${j.slice(-8)}`)}),T(V,{...G,children:`y Yes / n No`})]})),j===void 0&&M===`unavailable`&&T(V,{...G,children:`This session cannot be stopped from the view.`}),j===void 0&&pe===`unavailable`&&T(V,{...G,children:`This session cannot be attached to from the view.`}),M===`stopping`&&T(V,{...G,children:`Stopping selected session; wait for confirmation.`}),M===`stopped`&&E(V,{...G,children:[`Stopped `,he]}),M===`failed`&&T(V,{...G,children:`Stop failed; session remains listed until verified otherwise.`}),O&&z.length>0&&j===void 0&&M!==`stopping`&&E(V,{children:[Vn(z.length,!0),Ee.buffer?` ${Ee.buffer}`:``]}),O&&Ee.invalid&&T(V,{children:`Selection out of range.`}),T(V,{...G,children:ze}),je&&Ae.map(e=>T(V,{...G,children:e},e))]})}async function cu(e){e.announce!==!1&&Pc({enabled:e.screenReader,channel:e.screenReaderChannel,hint:e.screenReaderHint});let t;process.stdin.resume();let n=s(T(Me,{enabled:e.screenReader,children:T(su,{loadRows:e.loadRows,onStop:e.onStop,onStart:e.onStart,startTrustQuestion:e.startTrustQuestion,onOpenPr:e.onOpenPr,onAttach:e=>{t=e},filteredByCwd:e.filteredByCwd,filteredByName:e.filteredByName,filteredByPr:e.filteredByPr,stateFilter:e.stateFilter,refreshMs:e.refreshMs,...e.initialSelectedId===void 0?{}:{initialSelectedId:e.initialSelectedId},...e.initialGroupByDirectory===void 0?{}:{initialGroupByDirectory:e.initialGroupByDirectory}})}),{isScreenReaderEnabled:e.screenReader,exitOnCtrlC:!1});try{await n.waitUntilExit()}finally{n.unmount()}return t===void 0?{kind:`closed`}:{kind:`attach`,...t}}function lu({providerDefinitions:e,reloadPluginCommandSource:t,userSettingsPath:n,settingsSources:r,formatResumeCommand:i}){return{getUserSettingsPath:()=>n,readSettings:e=>ue(e),reloadPluginCommandSource:e=>{t(e)},applyActiveModelChange:(e,t,i)=>(re(r,[ae(`user`,n)],t,i),{applied:!0}),getGitBranch:e=>A(e),getProviderDisplayName:t=>me(e,t)?.displayName??t,...i===void 0?{}:{formatResumeCommand:i}}}function uu(e){return{...e===void 0?{}:{$schema:e},version:1,bindings:{}}}function du(e,t){let n=jn(JSON.stringify(uu(t)),e);if(!n.ok)throw Error(n.diagnostic.message);return n.snapshot}var fu=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=du(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=R(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()===Ce(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(R(this.filePath),{recursive:!0});try{await Se(this.filePath,`${JSON.stringify(uu(this.#e),null,2)}\n`,{encoding:`utf8`,flag:`wx`,mode:384})}catch(e){if(!mu(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 xe(this.filePath,`utf8`)}catch(e){if(pu(e))return;this.#d({file:this.filePath,path:`$`,message:gu(e)});return}let t=jn(e,this.filePath);if(!t.ok){this.#d(t.diagnostic);return}this.#f(Object.freeze({...t.snapshot,generation:this.#r.generation+1}))}#d(e){this.#t?.(e),this.#f(Object.freeze({...this.#r,generation:this.#r.generation+1,diagnostic:e}))}#f(e){if(!this.#s){this.#r=e;for(let t of this.#n)t(e)}}};function pu(e){return hu(e)&&e.code===`ENOENT`}function mu(e){return hu(e)&&e.code===`EEXIST`}function hu(e){return e instanceof Error&&`code`in e}function gu(e){return e instanceof Error?e.message:String(e)}function _u(e){return new fu(e)}export{vl as TuiInteractionChannel,lu as createDefaultTuiCliAdapter,_u as createNodeKeybindingsSource,hc as createThemeCataloguePort,fc as createThemeRegistry,dt as escapeThemeText,ke as listBuiltInThemes,wt as parseThemeDocument,ut as quoteThemeText,Gl as renderApp,Kl as renderAttachedApp,cu as renderSupervisedSessionView,ft as sanitizeThemeProse};
|
|
33
33
|
//# sourceMappingURL=index.js.map
|