@robota-sdk/agent-transport 3.0.0-beta.69 → 3.0.0-beta.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/node/headless/index.cjs +1 -1
  2. package/dist/node/headless/index.d.ts +2 -2
  3. package/dist/node/headless/index.js +1 -1
  4. package/dist/node/headless-C6tj35h3.js +15 -0
  5. package/dist/node/headless-C6tj35h3.js.map +1 -0
  6. package/dist/node/headless-DCtHvyVf.cjs +14 -0
  7. package/dist/node/http/index.d.ts +1 -1
  8. package/dist/node/index-27HV5PJB.d.ts +68 -0
  9. package/dist/node/index-27HV5PJB.d.ts.map +1 -0
  10. package/dist/node/index-BRchlFBE.d.ts +68 -0
  11. package/dist/node/index-BRchlFBE.d.ts.map +1 -0
  12. package/dist/node/{index-C7DvsmEg.d.ts → index-BRgV_MPB.d.ts} +2 -2
  13. package/dist/node/{index-C7DvsmEg.d.ts.map → index-BRgV_MPB.d.ts.map} +1 -1
  14. package/dist/node/{index-D-aT_t_N.d.ts → index-BVNhOeeU.d.ts} +3 -2
  15. package/dist/node/{index-D-aT_t_N.d.ts.map → index-BVNhOeeU.d.ts.map} +1 -1
  16. package/dist/node/{index-yvGShbDx.d.ts → index-COWvtBa2.d.ts} +2 -2
  17. package/dist/node/{index-yvGShbDx.d.ts.map → index-COWvtBa2.d.ts.map} +1 -1
  18. package/dist/node/{index-ioN9mYAD.d.ts → index-TMAlNHuM.d.ts} +5 -4
  19. package/dist/node/{index-ioN9mYAD.d.ts.map → index-TMAlNHuM.d.ts.map} +1 -1
  20. package/dist/node/{index-DOA2KIYt.d.ts → index-nBlMTFkZ.d.ts} +2 -2
  21. package/dist/node/{index-DOA2KIYt.d.ts.map → index-nBlMTFkZ.d.ts.map} +1 -1
  22. package/dist/node/index.cjs +1 -1
  23. package/dist/node/index.d.ts +7 -7
  24. package/dist/node/index.js +1 -1
  25. package/dist/node/index.js.map +1 -1
  26. package/dist/node/mcp/index.d.ts +1 -1
  27. package/dist/node/tui/index.cjs +1 -1
  28. package/dist/node/tui/index.d.ts +2 -2
  29. package/dist/node/tui/index.js +1 -1
  30. package/dist/node/tui-Cf1-zocr.js +25 -0
  31. package/dist/node/tui-Cf1-zocr.js.map +1 -0
  32. package/dist/node/tui-re-S-CGS.cjs +24 -0
  33. package/dist/node/ws/index.d.ts +1 -1
  34. package/package.json +6 -6
  35. package/src/headless/HeadlessInteractionChannel.ts +84 -0
  36. package/src/headless/index.ts +2 -0
  37. package/src/tui/App.tsx +26 -56
  38. package/src/tui/InputArea.tsx +3 -59
  39. package/src/tui/StatusBar.tsx +1 -1
  40. package/src/tui/TuiInteractionChannel.ts +461 -0
  41. package/src/tui/__tests__/TuiInteractionChannel.display-contract.test.ts +239 -0
  42. package/src/tui/__tests__/TuiInteractionChannel.lifecycle.test.ts +294 -0
  43. package/src/tui/__tests__/TuiInteractionChannel.requestAction.test.ts +124 -0
  44. package/src/tui/__tests__/compact-event-bridge.test.ts +1 -1
  45. package/src/tui/__tests__/input-area-flow.test.ts +5 -12
  46. package/src/tui/flows/input-area-flow.ts +10 -15
  47. package/src/tui/hooks/use-interactive-session-init.ts +37 -2
  48. package/src/tui/hooks/useSlashRouting.ts +1 -1
  49. package/src/tui/hooks/useTuiChannel.ts +95 -0
  50. package/src/tui/index.ts +2 -1
  51. package/src/tui/interactions/__tests__/CommandConfirm.test.tsx +124 -0
  52. package/src/tui/interactions/__tests__/CommandPicker.test.tsx +138 -0
  53. package/src/tui/render.tsx +39 -1
  54. package/src/tui/tui-state-manager.ts +2 -1
  55. package/src/tui/tui-transport.ts +1 -1
  56. package/dist/node/headless-C-Ezlo9U.js +0 -15
  57. package/dist/node/headless-C-Ezlo9U.js.map +0 -1
  58. package/dist/node/headless-Cv-igy49.cjs +0 -14
  59. package/dist/node/index-CP7kaYMg.d.ts +0 -41
  60. package/dist/node/index-CP7kaYMg.d.ts.map +0 -1
  61. package/dist/node/index-Gby9H4q2.d.ts +0 -41
  62. package/dist/node/index-Gby9H4q2.d.ts.map +0 -1
  63. package/dist/node/tui-87G6pg3z.js +0 -25
  64. package/dist/node/tui-87G6pg3z.js.map +0 -1
  65. package/dist/node/tui-BAtwGilM.cjs +0 -24
  66. package/src/tui/command-interaction-registry.ts +0 -66
  67. package/src/tui/hooks/useInteractiveSession.ts +0 -299
@@ -1,24 +0,0 @@
1
- const e=require(`./chunk-Bmb41Sf3.cjs`);let t=require(`ink`),n=require(`react`),r=e.t(n,1);n=e.t(n);let i=require(`@robota-sdk/agent-core`),a=require(`@robota-sdk/agent-framework`),o=require(`react/jsx-runtime`),s=require(`chalk`);s=e.t(s);let c=require(`string-width`);c=e.t(c,1);let l=require(`@robota-sdk/agent-interface-tui`),u=require(`marked`),d=require(`marked-terminal`);d=e.t(d,1);const f=[`active`,`queued`,`running`,`waiting_permission`,`sleeping`],p=/\s+/g;function m(e){return(e?.entries??[]).filter(e=>e.kind===`background_task`&&e.visibility===`default`)}function h(e){return m(e).filter(e=>f.includes(e.status)).length}function g(e,t={}){let n=e.id===t.selectedEntryId,r={id:e.id,radio:n?`●`:`○`,title:v(e),subtitle:y(e),statusLabel:b(e.status),preview:S(e.preview??e.currentAction),color:x(e),isSelected:n};return{...r,accessibleText:C(r)}}function _(e){let t=e.text.trim().replace(p,` `);return t?t.length>160?`${t.slice(0,160)}...`:t:e.kind}function v(e){return e.kind===`main_thread`?e.title:e.kind===`background_group`?`${e.title} group`:e.taskKind===`agent`?`${e.title} agent`:e.taskKind===`process`?e.title||`Process`:e.taskKind===`scheduled`?e.title||`Scheduled`:e.title}function y(e){return e.kind===`main_thread`?e.subtitle:[e.taskKind,e.subtitle,e.attention===`none`?void 0:e.attention].filter(e=>typeof e==`string`&&e.length>0).join(` · `)||void 0}function b(e){return e.replace(/_/g,` `)}function x(e){return e.attention===`failed`||e.status===`failed`?`red`:e.attention===`permission`||e.status===`waiting_permission`?`yellow`:e.status===`completed`?`green`:e.status===`cancelled`?`yellow`:f.includes(e.status)?`cyan`:`white`}function S(e){return e?.trim().replace(p,` `)||void 0}function C(e){return[e.radio,e.title,e.statusLabel,e.subtitle,e.preview].filter(e=>typeof e==`string`&&e.length>0).join(` · `)}function w(e,t={}){let n=g(e),r=T(e)?`□`:`■`,i=[n.statusLabel,n.subtitle].filter(e=>typeof e==`string`&&e.length>0);return{connector:t.isLast===!1?`├`:`└`,marker:r,color:n.color,label:n.title,segments:i,preview:n.preview,accessibleText:[`${t.isLast===!1?`├`:`└`} ${r} ${n.title}`,...i,n.preview].filter(e=>typeof e==`string`&&e.length>0).join(` · `)}}function T(e){return e.status===`active`||e.status===`queued`||e.status===`running`||e.status===`waiting_permission`||e.status===`sleeping`}function E({entries:e}){return e.length===0?null:(0,o.jsxs)(t.Box,{flexDirection:`column`,marginBottom:1,children:[(0,o.jsx)(t.Text,{color:`cyan`,bold:!0,children:`Background work`}),e.map((n,r)=>{let i=w(n,{isLast:r===e.length-1});return(0,o.jsxs)(t.Text,{children:[`${i.connector} `,(0,o.jsx)(t.Text,{color:i.color,children:i.marker}),` ${i.label}`,i.segments.map((e,n)=>(0,o.jsx)(t.Text,{dimColor:!0,children:` · ${e}`},`${e}-${n}`)),i.preview?(0,o.jsx)(t.Text,{dimColor:!0,children:` · ${i.preview}`}):null]},n.id)})]})}function ee({percentage:e}){return e>=90?(0,o.jsx)(t.Box,{borderStyle:`single`,borderColor:`red`,paddingX:1,children:(0,o.jsxs)(t.Text,{color:`red`,bold:!0,children:[`⚠ Context at `,Math.round(e),`% — window nearly full. Run /compact to summarize the conversation.`]})}):e>=70?(0,o.jsx)(t.Box,{paddingX:1,children:(0,o.jsxs)(t.Text,{color:`yellow`,children:[`Context at `,Math.round(e),`% — consider running /compact to free up space.`]})}):null}function D({entry:e,page:n,loading:r,error:i}){let a=g(e,{selectedEntryId:e.id}),s=n?.records.slice(-12)??[];return(0,o.jsxs)(t.Box,{flexDirection:`column`,marginBottom:1,children:[(0,o.jsx)(t.Text,{color:`cyan`,bold:!0,children:`Viewing ${a.title}`}),(0,o.jsxs)(t.Text,{dimColor:!0,children:[a.statusLabel,a.subtitle?` · ${a.subtitle}`:``,a.preview?` · ${a.preview}`:``]}),r?(0,o.jsx)(t.Text,{dimColor:!0,children:`Loading workspace detail...`}):null,i?(0,o.jsx)(t.Text,{color:`red`,children:i}):null,!r&&!i&&s.length===0?(0,o.jsx)(t.Text,{dimColor:!0,children:`No detail yet`}):null,!r&&!i&&s.map(e=>(0,o.jsx)(t.Text,{color:O(e.kind),children:_(e)},e.id)),n?.nextCursor?(0,o.jsx)(t.Text,{dimColor:!0,children:`... more detail available`}):null]})}function O(e){if(e===`error`)return`red`;if(e===`result`)return`green`;if(e===`process_output`)return`white`;if(e===`group_summary`)return`cyan`}function k(){return{selectedIndex:0,scrollOffset:0,resolved:!1}}function A(e){if(e.escape===!0)return`cancel`;if(e.upArrow===!0)return`previous`;if(e.downArrow===!0)return`next`;if(e.return===!0)return`select`}function j(e){if(e.escape===!0)return`cancel`;if(e.leftArrow===!0||e.upArrow===!0)return`previous`;if(e.rightArrow===!0||e.downArrow===!0)return`next`;if(e.return===!0)return`select`}function M(e,t,n){if(e.resolved)return{state:e,effect:{type:`none`}};if(t===`cancel`)return{state:{...e,resolved:!0},effect:{type:`cancel`}};if(n.enabled===!1||n.itemCount===0)return{state:e,effect:{type:`none`}};if(t===`select`){let t=F(e.selectedIndex,n.itemCount);return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`select`,index:t}}}let r=te(e.selectedIndex,t,n),i=P(r,e.scrollOffset,n);return{state:{...e,selectedIndex:r,scrollOffset:i},effect:{type:`none`}}}function N(e,t){if(t.itemCount===0)return{...e,selectedIndex:0,scrollOffset:0};let n=F(e.selectedIndex,t.itemCount),r=P(n,e.scrollOffset,t);return n===e.selectedIndex&&r===e.scrollOffset?e:{...e,selectedIndex:n,scrollOffset:r}}function te(e,t,n){return t===`previous`?n.wrap===!0&&e===0?n.itemCount-1:Math.max(0,e-1):n.wrap===!0&&e===n.itemCount-1?0:Math.min(n.itemCount-1,e+1)}function P(e,t,n){let r=n.maxVisible??n.itemCount;return r<=0?0:e<t?e:e>=t+r?e-r+1:Math.max(0,t)}function F(e,t){return Math.min(Math.max(e,0),t-1)}function I({snapshot:e,selectedEntryId:n,onSelect:r,onClose:i}){let{normalized:a,visibleEntries:s,applyAction:c}=L({entries:[...e?.entries??[]],selectedEntryId:n,onSelect:r,onClose:i});return(0,t.useInput)((e,t)=>{let n=A(t);n!==void 0&&c(n)}),(0,o.jsxs)(t.Box,{flexDirection:`column`,borderStyle:`round`,borderColor:`cyan`,paddingX:1,children:[(0,o.jsx)(t.Text,{color:`cyan`,bold:!0,children:`Execution workspace`}),(0,o.jsx)(t.Box,{flexDirection:`column`,marginTop:1,children:s.length===0?(0,o.jsx)(t.Text,{dimColor:!0,children:`No workspace entries`}):s.map((e,t)=>(0,o.jsx)(B,{entry:e,isFocused:a.scrollOffset+t===a.selectedIndex,selectedEntryId:n},e.id))}),(0,o.jsx)(t.Text,{dimColor:!0,children:`Ctrl+B Close ↑↓ Navigate Enter Switch Esc Close`})]})}function L({entries:e,selectedEntryId:t,onSelect:r,onClose:i}){let[a,o]=(0,n.useState)(()=>k()),s=(0,n.useRef)(a);(0,n.useEffect)(()=>{let n=z({selectedIndex:Math.max(0,e.findIndex(e=>e.id===t)),itemCount:e.length});s.current=n,o(n)},[e.length,t]);let c=z({selectedIndex:a.selectedIndex,scrollOffset:a.scrollOffset,itemCount:e.length});return c!==a&&(s.current=c),{normalized:c,visibleEntries:e.slice(c.scrollOffset,c.scrollOffset+8),applyAction:R({entries:e,stateRef:s,setState:o,onSelect:r,onClose:i})}}function R({entries:e,stateRef:t,setState:n,onSelect:r,onClose:i}){return a=>{let o=M(t.current,a,{itemCount:e.length,maxVisible:8}),s=o.effect.type===`select`||o.effect.type===`cancel`?{...o.state,resolved:!1}:o.state;if(t.current=s,n(s),o.effect.type===`cancel`)i();else if(o.effect.type===`select`){let t=e[o.effect.index];t&&r(t.id)}}}function z(e){return N({selectedIndex:e.selectedIndex,scrollOffset:e.scrollOffset??0,resolved:!1},{itemCount:e.itemCount,maxVisible:8})}function B({entry:e,isFocused:n,selectedEntryId:r}){let i=g(e,{selectedEntryId:r});return(0,o.jsxs)(t.Text,{children:[(0,o.jsx)(t.Text,{color:n?`cyan`:void 0,bold:n,children:n?`> `:` `}),(0,o.jsx)(t.Text,{color:i.color,children:i.radio}),(0,o.jsx)(t.Text,{color:n?`cyan`:void 0,bold:n,children:` ${i.title}`}),(0,o.jsx)(t.Text,{dimColor:!0,children:` · ${i.statusLabel}`}),i.subtitle?(0,o.jsx)(t.Text,{dimColor:!0,children:` · ${i.subtitle}`}):null,i.preview?(0,o.jsx)(t.Text,{dimColor:!0,children:` · ${i.preview}`}):null]})}function V(e,t){let n=null;return{schedule(){n||=setTimeout(()=>{n=null,e()},t)},flush(){n&&=(clearTimeout(n),null)}}}var H=class{history=[];streamingText=``;activeTools=[];isThinking=!1;isAborting=!1;pendingPrompt=null;contextState={percentage:0,usedTokens:0,maxTokens:0};executionWorkspaceSnapshot=null;selectedExecutionEntryId;onChange=null;streamBuf=``;debouncedStreamNotify=V(()=>this.notify(),300);notify(){this.onChange?.()}onTextDelta=e=>{this.streamBuf+=e,this.streamingText=this.streamBuf,this.debouncedStreamNotify.schedule()};onToolStart=e=>{this.activeTools=[...this.activeTools,e],this.notify()};onToolEnd=e=>{let t=this.activeTools.findLastIndex(t=>t.toolName===e.toolName&&t.isRunning);if(t!==-1){let n=[...this.activeTools];n[t]=e,this.activeTools=n}this.notify()};onThinking=e=>{this.isThinking=e,e?(this.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[]):this.isAborting=!1,this.notify()};onComplete=e=>{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.debouncedStreamNotify.flush(),this.streamBuf=``,this.streamingText=``,this.activeTools=[],this.notify()};onError=()=>{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=e.length>100?e.slice(-100):[...e],this.notify())}addEntry(e){let t=[...this.history,e];this.history=t.length>100?t.slice(-100):t,this.notify()}clearHistory(){this.history=[],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()}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())}},ne=class{queue=[];enqueueInteraction(e){this.queue.push({type:`interaction`,interaction:e})}enqueueEffects(e){e.length!==0&&this.queue.push({type:`effects`,effects:[...e]})}drain(){return this.queue.shift()}clear(){this.queue.length=0}};function U(e,t){let n=new a.InteractiveSession({cwd:e.cwd,provider:e.provider,permissionMode:e.permissionMode,maxTurns:e.maxTurns,permissionHandler:t,sessionStore:e.sessionStore,resumeSessionId:e.resumeSessionId,forkSession:e.forkSession,sessionName:e.sessionName,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,language:e.language,agentName:e.agentName,systemPrompt:e.systemPrompt,appendSystemPrompt:e.appendSystemPrompt,allowedTools:e.allowedTools,deniedTools:e.deniedTools}),r=new a.CommandRegistry;for(let t of e.commandModules??[])r.addModule(t);return e.reloadPluginCommandSource?.(r),{interactiveSession:n,registry:r,manager:new H,commandEffectQueue:new ne}}function W(){let[e,t]=(0,r.useState)(null),n=(0,r.useRef)([]),i=(0,r.useRef)(!1),a=(0,r.useCallback)(()=>{if(i.current)return;let e=n.current[0];if(!e){t(null);return}i.current=!0,t({toolName:e.toolName,toolArgs:e.toolArgs,resolve:r=>{n.current.shift(),i.current=!1,t(null),e.resolve(r),setTimeout(()=>a(),0)}})},[]);return{permissionHandler:(0,r.useCallback)((e,t)=>new Promise(r=>{n.current.push({toolName:e,toolArgs:t,resolve:r}),a()}),[a]),permissionRequest:e}}function G(e,t,n,a,o){return(0,r.useCallback)(async r=>{if(!r.startsWith(`/`)){await e.submit(r),n.setPendingPrompt(e.getPendingPrompt());return}let s=r.slice(1).split(/\s+/),c=s[0]?.toLowerCase()??``,l=s.slice(1).join(` `),u=await e.executeCommand(c,l);if(u){if(u.effects?.some(e=>e.type===`session-execution-started`)){n.setPendingPrompt(e.getPendingPrompt());return}re(u,e,t,n,a,o);return}n.addEntry((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(`Unknown command "/${c}". Type /help for help.`)))},[e,t,n,a,o])}function re(e,t,n,r,a,o){let s=ie(e.effects,n,r,o);if(r.addEntry((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(e.message))),e.interaction!==void 0&&a.enqueueInteraction(e.interaction),s.length>0&&a.enqueueEffects(s),t.isInitialized){let e=t.getContextState();r.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens})}}function ie(e,t,n,r){if(e===void 0||e.length===0)return[];let i=[];for(let a of e){if(a.type===`conversation-history-cleared`){n.clearHistory();continue}if(a.type===`plugin-registry-reload-requested`){r?.(t);continue}i.push(a)}return i}function ae(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,``).trim().replace(/\s+/g,`-`).replace(/-+/g,`-`).slice(0,60)}async function oe(e,t){let n=t.slice(0,200),r=await e.chat([(0,i.createSystemMessage)(`You generate short session titles. Respond with ONLY a 3-5 word lowercase-hyphenated title (e.g. refactor-auth-middleware). No explanation, no punctuation, no quotes.`),(0,i.createUserMessage)(n)],{maxTokens:20}),a=ae(typeof r.content==`string`?r.content:``);return!a||a.length<3?ae(t):a}function se(e,t){t.syncHistory(e.getFullHistory())}function ce(e,t){t.syncHistory(e.getFullHistory())}function K(e,t){try{t.syncExecutionWorkspaceSnapshot(e.getExecutionWorkspaceSnapshot({selectedEntryId:t.selectedExecutionEntryId}))}catch{}}function le(e){let[,t]=(0,r.useState)(0),[n,a]=(0,r.useState)(!1),{permissionHandler:o,permissionRequest:s}=W(),c=(0,r.useRef)(!1),[l]=(0,r.useState)(()=>U(e,o)),{interactiveSession:u,registry:d,manager:f,commandEffectQueue:p}=l;if(f.onChange=()=>t(e=>e+1),f.history.length===0){let e=u.getFullHistory();e.length>0&&f.syncHistory(e)}(0,r.useEffect)(()=>{if(!e.transportRegistry)return;let t=e.transportRegistry;return t.startAll(u).catch(()=>void 0),()=>{t.stopAll().catch(()=>void 0)}},[u,e.transportRegistry]),(0,r.useEffect)(()=>{let t=()=>se(u,f),n=()=>ce(u,f),r=t=>{c.current||e.sessionName||u.getName()||(c.current=!0,oe(e.provider,t).then(t=>{u.setName(t),e.onAutoNamed?.(t)}).catch(()=>{c.current=!1}))},i=e=>f.syncExecutionWorkspaceSnapshot(e.snapshot);u.on(`user_message`,r),u.on(`text_delta`,f.onTextDelta),u.on(`tool_start`,f.onToolStart),u.on(`tool_end`,f.onToolEnd),u.on(`thinking`,f.onThinking),u.on(`complete`,f.onComplete),u.on(`interrupted`,f.onInterrupted),u.on(`error`,f.onError),u.on(`context_update`,f.onContextUpdate),u.on(`compact`,t),u.on(`skill_activation`,n),u.on(`execution_workspace_event`,i);let a=setInterval(()=>{try{let e=u.getContextState();f.setContextState({percentage:e.usedPercentage,usedTokens:e.usedTokens,maxTokens:e.maxTokens});let t=u.getFullHistory();t.length>0&&f.syncHistory(t),K(u,f),clearInterval(a)}catch{}},200);return()=>{clearInterval(a),u.off(`user_message`,r),u.off(`text_delta`,f.onTextDelta),u.off(`tool_start`,f.onToolStart),u.off(`tool_end`,f.onToolEnd),u.off(`thinking`,f.onThinking),u.off(`complete`,f.onComplete),u.off(`interrupted`,f.onInterrupted),u.off(`error`,f.onError),u.off(`context_update`,f.onContextUpdate),u.off(`compact`,t),u.off(`skill_activation`,n),u.off(`execution_workspace_event`,i)}},[u,f]),(0,r.useEffect)(()=>{f.syncHistory(u.getFullHistory()),K(u,f),f.isThinking||f.setPendingPrompt(u.getPendingPrompt())},[f.isThinking,u,f]);let m=G(u,d,f,p,e.reloadPluginCommandSource),h=(0,r.useCallback)(()=>{f.setAborting(!0),u.abort()},[u,f]),g=(0,r.useCallback)(()=>{u.cancelQueue(),f.setPendingPrompt(null)},[u,f]),_=(0,r.useCallback)(async(e=`prompt_input_exit`)=>{n||(a(!0),f.addEntry((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(`Shutting down...`))),await u.shutdown({reason:e,message:`CLI shutdown`}))},[u,f,n]),v=(0,r.useCallback)(e=>f.selectExecutionWorkspaceEntry(e),[f]),y=(0,r.useCallback)(e=>u.readExecutionWorkspaceDetail(e),[u]);return{interactiveSession:u,registry:d,commandEffectQueue:p,history:f.history,addEntry:e=>f.addEntry(e),streamingText:f.streamingText,activeTools:f.activeTools,isThinking:f.isThinking,isAborting:f.isAborting,isShuttingDown:n,pendingPrompt:f.pendingPrompt,executionWorkspaceSnapshot:f.executionWorkspaceSnapshot,selectedExecutionEntryId:f.selectedExecutionEntryId,permissionRequest:s,contextState:f.contextState,handleSubmit:m,handleAbort:h,handleCancelQueue:g,handleShutdown:_,selectExecutionWorkspaceEntry:v,readExecutionWorkspaceDetail:y}}function ue(){return{listInstalled:async()=>[],listAvailablePlugins:async()=>[],install:async()=>void 0,uninstall:async()=>void 0,enable:async()=>void 0,disable:async()=>void 0,marketplaceAdd:async()=>``,marketplaceRemove:async()=>void 0,marketplaceUpdate:async()=>void 0,marketplaceList:async()=>[],reloadPlugins:async()=>({loadedPluginCount:0})}}function de(e){return(0,r.useMemo)(()=>ue(),[])}function q(e,t){for(let n of e){if(n.type===`language-change-requested`)return J(n.language,t),!0;if(n.type===`settings-reset-requested`)return Y(t),!0;if(n.type===`session-exit-requested`)return t.requestShutdown(n.reason??`prompt_input_exit`,n.message??`User requested exit`),!0;if(n.type===`session-restart-requested`)return t.requestShutdown(n.reason,n.message),!0;if(n.type===`plugin-tui-requested`)return t.openPluginTUI(),!0;if(n.type===`settings-tui-requested`)return t.openTransportTUI(),!0;if(n.type===`agent-switcher-requested`)return t.openAgentSwitcher(),!0;if(n.type===`session-picker-requested`)return t.openSessionPicker(),!0;if(n.type===`session-renamed`)return t.renameSession(n.name),!0;if(n.type===`statusline-settings-patch`&&(0,a.isStatusLineCommandSettingsPatch)(n.patch))return t.applyStatusLinePatch(n.patch)}return!1}function J(e,t){let n=t.cliAdapter.getUserSettingsPath(),r=t.cliAdapter.readSettings(n);r.language=e,t.cliAdapter.writeSettings(n,r),t.addEntry((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(`Language set to "${e}". Restarting...`))),t.requestShutdown(`other`,`Language change restart`)}function Y(e){let t=e.cliAdapter.getUserSettingsPath();e.cliAdapter.deleteSettings(t)?e.addEntry((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(`Deleted ${t}. Exiting...`))):e.addEntry((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(`No user settings found.`))),e.requestShutdown(`other`,`Reset settings restart`)}const X=(0,n.createContext)(null),fe=X.Provider;function Z(){let e=(0,n.useContext)(X);if(!e)throw Error(`TuiCliAdapterContext not provided`);return e}function pe({cwd:e,providerOverride:n,interactiveSession:a,commandEffectQueue:o,addEntry:s,baseHandleSubmit:c,setSessionName:l,setStatusLineSettings:u,showSessionPickerOnStart:d,openAgentSwitcher:f}){let{exit:p}=(0,t.useApp)(),m=Z(),[h,g]=(0,r.useState)(null),_=(0,r.useRef)(null),[v,y]=(0,r.useState)(!1),[b,x]=(0,r.useState)(d??!1),[S,C]=(0,r.useState)(!1),w=(0,r.useCallback)((e,t)=>{s((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(`Shutting down...`))),setTimeout(()=>{a.shutdown({reason:e,message:t}).finally(()=>p())},500)},[a,s,p]),T=(0,r.useCallback)(e=>q(e,{addEntry:s,requestShutdown:w,openPluginTUI:()=>y(!0),openSessionPicker:()=>x(!0),openTransportTUI:()=>C(!0),openAgentSwitcher:()=>f?.(),renameSession:e=>{a.setName(e),l(e)},applyStatusLinePatch:e=>(u(m.applyStatusLineSettings(m.getUserSettingsPath(),e)),!0),cliAdapter:m}),[s,m,a,w,l,u]),E=(0,r.useCallback)(e=>{if(e.message.length>0&&s((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(e.message))),e.interaction!==void 0){_.current=e.interaction,g(e.interaction.prompt);return}_.current=null,g(null),e.effects!==void 0&&e.effects.length>0&&T(e.effects)},[s,T]),ee=(0,r.useCallback)(()=>{let e=o.drain();if(e===void 0)return!1;if(e.type===`interaction`){let{interaction:t}=e;return _.current=t,g(t.prompt),!0}return T(e.effects)},[T,o]);return{handleSubmit:(0,r.useCallback)(async e=>{await c(e),ee()},[c,ee]),pendingInteractionPrompt:h,showPluginTUI:v,showSessionPicker:b,showTransportTUI:S,setShowPluginTUI:y,setShowSessionPicker:x,setShowTransportTUI:C,handleInteractionSubmit:(0,r.useCallback)(async e=>{let t=_.current;if(t===null){g(null);return}try{E(await t.submit(e))}catch(e){_.current=null,g(null),s((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(`Failed: ${e instanceof Error?e.message:String(e)}`)))}},[s,E]),handleInteractionCancel:(0,r.useCallback)(()=>{let e=_.current;if(_.current=null,g(null),e?.cancel===void 0){s((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(`Command interaction cancelled.`)));return}Promise.resolve(e.cancel()).then(e=>E(e)).catch(e=>{s((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(`Failed: ${e instanceof Error?e.message:String(e)}`)))})},[s,E])}}function me(e){let t={...a.DEFAULT_STATUS_LINE_COMMAND_SETTINGS},n=e.statusline;return he(n)?{enabled:typeof n.enabled==`boolean`?n.enabled:t.enabled,gitBranch:typeof n.gitBranch==`boolean`?n.gitBranch:t.gitBranch}:t}function he(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function ge(){let e=Z();return(0,r.useState)(()=>me(e.readSettings(e.getUserSettingsPath())))}const _e=`[200~`,Q=`[201~`;function ve(e){return{value:e,cursor:e.length,isPasting:!1,pasteBuffer:``}}function ye(e,t,n){return t===e.value?e:{...e,value:t,cursor:n==null?t.length:Math.min(n,t.length)}}function be(e,t,n,r){let i=Se(e,t,r);if(i!==void 0)return i;let a=Ce(e,t,n,r);if(a!==void 0)return a;let o=we(e,n,r);return o===void 0?Pe(e,t):o}function xe(e,t,n){let r=t.replace(/\r\n?/g,`
2
- `);return r.length===0?{state:e,effect:{type:`none`}}:r.includes(`
3
- `)&&n.canPaste?{state:e,effect:{type:`paste`,text:r,cursor:e.cursor}}:Pe(e,r)}function Se(e,t,n){if(t===_e||t.startsWith(_e))return ke(e,t);if(e.isPasting)return Ae(e,t,n)}function Ce(e,t,n,r){if(n.ctrl===!0&&t===`c`||n.tab===!0)return{state:e,effect:{type:`none`}};if(n.return===!0)return{state:e,effect:{type:`submit`,value:e.value}};if(t.length>1&&(t.includes(`
4
- `)||t.includes(`\r`))&&r.canPaste)return{state:e,effect:{type:`paste`,text:t.replace(/\r\n?/g,`
5
- `),cursor:e.cursor}}}function we(e,t,n){if(t.upArrow===!0||t.downArrow===!0)return n.enableVerticalNavigation===!1?{state:e,effect:{type:`none`}}:je(e,t.upArrow===!0?`up`:`down`,n.availableWidth);if(t.leftArrow===!0)return Me(e,`left`);if(t.rightArrow===!0)return Me(e,`right`);if(t.backspace===!0||t.delete===!0)return Ne(e)}function Te(e){if(!e||e.length===0)return``;let t=``;for(let n of e){let e=n.charCodeAt(0);e>31&&e!==127&&(t+=n)}return t}function Ee(e,t,n){return{value:e.slice(0,t)+n+e.slice(t),cursor:t+n.length}}function De(e,t,n){let r=0;for(let i=0;i<t&&i<e.length;i++){let t=(0,c.default)(e[i]),a=r%n;a+t>n&&(r+=n-a),r+=t}return r}function Oe(e,t,n){let r=0;for(let i=0;i<e.length;i++){if(r>=t)return i;let a=(0,c.default)(e[i]),o=r%n;o+a>n&&(r+=n-o),r+=a}return e.length}function ke(e,t){return{state:{...e,isPasting:!0,pasteBuffer:t.slice(5)},effect:{type:`none`}}}function Ae(e,t,n){if(t!==Q&&!t.includes(Q))return{state:{...e,pasteBuffer:e.pasteBuffer+t},effect:{type:`none`}};let r=t.split(Q)[0]??``;return xe({...e,isPasting:!1,pasteBuffer:``},e.pasteBuffer+r,n)}function je(e,t,n){if(!n||n<=0)return{state:e,effect:{type:`none`}};let r=[...e.value],i=De(r,e.cursor,n),a=t===`up`?i-n:i+n;if(a<0)return{state:e,effect:{type:`none`}};let o=Oe(r,a,n);return o===e.cursor?{state:e,effect:{type:`none`}}:{state:{...e,cursor:o},effect:{type:`render`}}}function Me(e,t){return t===`left`&&e.cursor>0?{state:{...e,cursor:e.cursor-1},effect:{type:`render`}}:t===`right`&&e.cursor<e.value.length?{state:{...e,cursor:e.cursor+1},effect:{type:`render`}}:{state:e,effect:{type:`none`}}}function Ne(e){if(e.cursor===0)return{state:e,effect:{type:`none`}};let t=e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor);return{state:{...e,value:t,cursor:e.cursor-1},effect:{type:`change`,value:t}}}function Pe(e,t){let n=Te(t);if(n.length===0)return{state:e,effect:{type:`none`}};let r=Ee(e.value,e.cursor,n);return{state:{...e,value:r.value,cursor:r.cursor},effect:{type:`change`,value:r.value}}}function Fe({value:e,onChange:r,onSubmit:i,onPaste:a,placeholder:s=``,focus:c=!0,showCursor:l=!0,availableWidth:u,cursorHint:d=null,enableVerticalNavigation:f=!0}){let p=(0,n.useRef)(ve(e)),[,m]=(0,n.useState)(0);return p.current=ye(p.current,e,d),Ie({stateRef:p,onChange:r,onSubmit:i,onPaste:a,availableWidth:u,focus:c,enableVerticalNavigation:f,forceRender:m}),(0,o.jsx)(t.Text,{children:Be(p.current.value,p.current.cursor,s,l&&c)})}function Ie(e){(0,t.usePaste)(t=>{Re(e,()=>xe(e.stateRef.current,t,Le(e)))},{isActive:e.focus}),(0,t.useInput)((t,n)=>{Re(e,()=>be(e.stateRef.current,t,n,Le(e)))},{isActive:e.focus})}function Le(e){return{availableWidth:e.availableWidth,canPaste:e.onPaste!==void 0,enableVerticalNavigation:e.enableVerticalNavigation}}function Re(e,t){try{let n=t();e.stateRef.current=n.state,ze(n.effect,e.onChange,e.onSubmit,e.onPaste,e.forceRender)}catch{}}function ze(e,t,n,r,i){e.type===`change`?t(e.value):e.type===`submit`?n?.(e.value):e.type===`paste`?r?.(e.text,e.cursor):e.type===`render`&&i(e=>e+1)}function Be(e,t,n,r){if(!r)return e.length>0?e:n?s.default.gray(n):``;if(e.length===0)return n.length>0?s.default.inverse(n[0])+s.default.gray(n.slice(1)):s.default.inverse(` `);let i=[...e],a=``;for(let e=0;e<i.length;e++){let n=i[e]??``;a+=e===t?s.default.inverse(n):n}return t>=i.length&&(a+=s.default.inverse(` `)),a}function Ve(){return[{label:`plan`,value:`plan`,description:`Plan only, no execution`},{label:`default`,value:`default`,description:`Ask before risky actions`},{label:`acceptEdits`,value:`acceptEdits`,description:`Auto-approve file edits`},{label:`bypassPermissions`,value:`bypassPermissions`,description:`Skip all permission checks`}]}function He(){return[{label:`ko Korean`,value:`ko`,description:`한국어`},{label:`en English`,value:`en`,description:`English`},{label:`ja Japanese`,value:`ja`,description:`日本語`},{label:`zh Chinese`,value:`zh`,description:`中文`}]}function Ue(){return[{label:`current`,value:`current`,description:`Show current provider`},{label:`list`,value:`list`,description:`List available providers`},{label:`use`,value:`use`,description:`Switch to a provider`},{label:`add`,value:`add`,description:`Add a new provider`},{label:`test`,value:`test`,description:`Test provider connection`}]}const We={agent:void 0,background:void 0,clear:{onMissingArgs:`confirm`,message:`Clear conversation history?`},compact:void 0,context:void 0,cost:void 0,exit:{onMissingArgs:`confirm`,message:`Exit the session?`},help:void 0,language:{onMissingArgs:`picker`,getItems:He},memory:void 0,mode:{onMissingArgs:`picker`,getItems:Ve},model:void 0,permissions:void 0,plugin:void 0,provider:{onMissingArgs:`picker`,getItems:Ue},rename:void 0,reset:void 0,resume:void 0,rewind:void 0,settings:void 0,skills:void 0,statusline:void 0,"user-local":void 0,"validate-session":void 0};function Ge(e){return We[e]}function Ke(e){if(!e.startsWith(`/`))return{isSlash:!1,parentCommand:``,filter:``};let t=e.slice(1),n=t.indexOf(` `);return n===-1?{isSlash:!0,parentCommand:``,filter:t}:{isSlash:!0,parentCommand:t.slice(0,n),filter:t.slice(n+1)}}function qe(e,t){let[n,i]=(0,r.useState)(0),[a,o]=(0,r.useState)(!1),s=r.default.useRef(e);s.current!==e&&(s.current=e,a&&o(!1));let c=Ke(e),l=c.isSlash&&c.parentCommand.length>0,u=(0,r.useMemo)(()=>{if(!t||!c.isSlash||a)return[];if(l){let e=t.getSubcommands(c.parentCommand);if(e.length===0)return[];if(!c.filter)return e;let n=c.filter.toLowerCase();return e.filter(e=>e.name.toLowerCase().startsWith(n))}return t.getCommands(c.filter)},[t,c.isSlash,c.parentCommand,c.filter,a,l]),d=c.isSlash&&u.length>0&&!a;return n>=u.length&&u.length>0&&i(u.length-1),{showPopup:d,filteredCommands:u,selectedIndex:n,setSelectedIndex:i,isSubcommandMode:l,setShowPopup:e=>{o(typeof e==`function`?t=>!e(!t):!e)}}}function Je(e){if(e.upArrow===!0)return`previous`;if(e.downArrow===!0)return`next`;if(e.escape===!0)return`close`;if(e.tab===!0)return`complete`}function Ye(e){if(e.backspace===!0||e.delete===!0)return`cancelQueue`}function Xe(e){if(e.upArrow===!0)return`previous`;if(e.downArrow===!0)return`next`}function Ze(){return{selectedIndex:null,draft:``}}function Qe(e,t,n,r){if(t.length===0)return{value:e,cursorHint:e.length,state:n};if(r===`previous`){let r=n.selectedIndex===null?t.length-1:Math.max(0,n.selectedIndex-1),i=t[r]??e;return{value:i,cursorHint:i.length,state:{selectedIndex:r,draft:n.selectedIndex===null?e:n.draft}}}if(n.selectedIndex===null)return{value:e,cursorHint:e.length,state:n};if(n.selectedIndex<t.length-1){let r=n.selectedIndex+1,i=t[r]??e;return{value:i,cursorHint:i.length,state:{...n,selectedIndex:r}}}return{value:n.draft,cursorHint:n.draft.length,state:Ze()}}function $e(e,t){let n=t.trim();return n.length===0||e[e.length-1]===n?[...e]:[...e,n]}function et(e){let t=[];for(let n of e){if(n.category!==`chat`||n.type!==`user`)continue;let e=n.data;typeof e?.content==`string`&&(t=$e(t,e.content))}return t}function tt(e,t,n){return t===0?0:n===`previous`?e>0?e-1:t-1:e<t-1?e+1:0}function nt(e,t){let n=Ke(e);return n.parentCommand?{type:`insert`,value:`/${n.parentCommand} ${t.name} `}:t.subcommands&&t.subcommands.length>0?{type:`insert`,value:`/${t.name} `,selectedIndex:0}:{type:`insert`,value:`/${t.name} `}}function rt(e,t,n){let r=Ke(e);return r.parentCommand?{type:`submit`,value:`/${r.parentCommand} ${t.name}`}:n?.onMissingArgs?{type:`open-interaction`,commandName:t.name}:t.subcommands&&t.subcommands.length>0?{type:`insert`,value:`/${t.name} `,selectedIndex:0}:{type:`submit`,value:`/${t.name}`}}function it(e,t,n,r){let i=r.split(`
6
- `).length,a=`[Pasted text #${n} +${i} lines]`;return{value:e.slice(0,t)+a+e.slice(t),cursorHint:t+a.length,label:a,lineCount:i}}function at(e){return e.trim().length>0}function ot({commandName:e,interaction:n,onConfirm:r,onCancel:i}){return(0,t.useInput)((e,t)=>{t.return||e===`y`||e===`Y`?r():(t.escape||e===`n`||e===`N`)&&i()}),(0,o.jsxs)(t.Box,{paddingX:1,children:[(0,o.jsxs)(t.Text,{bold:!0,color:`yellow`,children:[`/`,e,`:`,` `]}),(0,o.jsxs)(t.Text,{children:[n.message,` `]}),(0,o.jsx)(t.Text,{dimColor:!0,children:`[y/n]`})]})}function st(){let{stdout:e}=(0,t.useStdout)();return Math.max(40,(e.columns??80)-4)}function ct({commandName:e,interaction:r,onSelect:i,onCancel:a}){let s=r.getItems(),[c,l]=(0,n.useState)(0),u=st();(0,t.useInput)((e,t)=>{if(t.upArrow)l(e=>e>0?e-1:s.length-1);else if(t.downArrow)l(e=>e<s.length-1?e+1:0);else if(t.return){let e=s[c];e&&i(e)}else (t.escape||e===`q`)&&a()});let d=s.length<=8||c<8?0:Math.min(c-8+1,s.length-8),f=s.slice(d,d+8);return(0,o.jsxs)(t.Box,{flexDirection:`column`,borderStyle:`round`,borderColor:`cyan`,paddingX:1,children:[(0,o.jsxs)(t.Text,{bold:!0,color:`cyan`,children:[`/`,e]}),f.map((e,n)=>{let r=d+n===c;return(0,o.jsx)(t.Box,{width:u,children:(0,o.jsxs)(t.Text,{color:r?`cyan`:void 0,dimColor:!r,wrap:`truncate-end`,children:[r?`▸ `:` `,e.label,e.description==null?``:` ${e.description}`]})},e.value)}),(0,o.jsx)(t.Text,{dimColor:!0,children:`↑↓ navigate · Enter select · Esc cancel`})]})}function lt(){let{stdout:e}=(0,t.useStdout)(),r=()=>Math.max(40,(e.columns??80)-4),[i,a]=(0,n.useState)(r);return(0,n.useEffect)(()=>{let t=()=>a(r());return e.on(`resize`,t),()=>{e.off(`resize`,t)}},[e]),i}function ut(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e.padEnd(t)}function dt(e){let{cmd:n,isSelected:r,showSlash:i,rowWidth:a,nameColWidth:s}=e,c=r?`▸ `:` `,l=r?`cyan`:void 0,u=!r,d=ut(n.name,s);return(0,o.jsx)(t.Box,{width:a,children:(0,o.jsx)(t.Text,{color:l,dimColor:u,wrap:`truncate-end`,children:i?`${c}/${d} ${n.description??``}`:`${c}${d} ${n.description??``}`})})}function ft({commands:e,selectedIndex:n,visible:r,isSubcommandMode:i}){let a=lt();if(!r||e.length===0)return null;let s=pt(n,e.length),c=e.slice(s,s+8),l=Math.min(20,Math.max(...c.map(e=>e.name.length)));return(0,o.jsx)(t.Box,{flexDirection:`column`,borderStyle:`round`,borderColor:`gray`,paddingX:1,children:c.map((e,t)=>(0,o.jsx)(dt,{cmd:e,isSelected:s+t===n,showSlash:!i,rowWidth:a,nameColWidth:l},e.name))})}function pt(e,t){if(t<=8||e<8)return 0;let n=t-8;return Math.min(e-8+1,n)}const mt=/\[Pasted text #(\d+)(?: \+\d+ lines)?\]/g;function ht(e,t){return e.replace(mt,(e,n)=>t.get(Number(n))??``)}const gt=[`#666666`,`#888888`,`#aaaaaa`,`#888888`];function _t({text:e}){let[r,i]=(0,n.useState)(0);return(0,n.useEffect)(()=>{let e=setInterval(()=>{i(e=>e+1)},400);return()=>clearInterval(e)},[]),(0,o.jsx)(t.Text,{children:[...e].map((e,n)=>(0,o.jsx)(t.Text,{color:gt[(r+Math.floor(n/4))%gt.length],children:e},n))})}function vt({onSubmit:e,onCancelQueue:r,isDisabled:i,isAborting:a,pendingPrompt:s,registry:c,sessionName:u,history:d}){let[f,p]=(0,n.useState)(``),[m,h]=(0,n.useState)(null),[g,_]=(0,n.useState)(null),[v,y]=(0,n.useState)(Ze),[b,x]=(0,n.useState)([]),S=(0,n.useMemo)(()=>et(d??[]),[d]),C=(0,n.useMemo)(()=>b.reduce((e,t)=>$e(e,t),S),[S,b]),w=(0,n.useRef)(new Map),{columns:T}=(0,t.useWindowSize)(),E=T>0?T:80,ee=Math.max(1,E-5),D=(0,n.useRef)(0),{showPopup:O,filteredCommands:k,selectedIndex:A,setSelectedIndex:j,isSubcommandMode:M,setShowPopup:N}=qe(f,c),te=(0,n.useCallback)((e,t)=>{D.current+=1;let n=D.current;w.current.set(n,e),p(r=>{let i=it(r,t,n,e);return h(i.cursorHint),i.value})},[]),P=(0,n.useCallback)(()=>{y(Ze())},[]),F=(0,n.useCallback)(e=>{x(t=>$e(t,e))},[]),I=(0,n.useCallback)(t=>{F(t),P(),e(t)},[e,F,P]),L=(0,n.useCallback)(e=>{let t=nt(f,e);t.type===`insert`&&(p(t.value),t.selectedIndex!==void 0&&j(t.selectedIndex))},[f,j]),R=(0,n.useCallback)(e=>{let t=Ge(e.name),n=rt(f,e,t);if(n.type===`insert`){p(n.value),n.selectedIndex!==void 0&&j(n.selectedIndex);return}if(n.type===`open-interaction`&&t?.onMissingArgs){N(!1),_({commandName:n.commandName,interaction:t});return}n.type===`submit`&&(p(``),I(n.value))},[f,I,j,N]),z=(0,n.useCallback)(e=>{if(!at(e))return;if(O&&k[A]){R(k[A]);return}let t=ht(e.trim(),w.current);p(``),w.current.clear(),D.current=0,I(t)},[O,k,A,R,I]);(0,t.useInput)((e,t)=>{if(!O)return;let n=Je(t);if(n===`previous`||n===`next`)j(e=>tt(e,k.length,n));else if(n===`close`)N(!1);else if(n===`complete`){let e=k[A];e&&L(e)}},{isActive:O&&!i}),(0,t.useInput)((e,t)=>{let n=Xe(t);if(!n)return;let r=Qe(f,C,v,n);p(r.value),h(r.cursorHint),y(r.state)},{isActive:!O&&!i&&!s}),(0,t.useInput)((e,t)=>{Ye(t)===`cancelQueue`&&s&&r?.()},{isActive:!!s});let B=a?`yellow`:s?`cyan`:i?`gray`:`green`,V=Math.max(1,E-2),H=(()=>{if(u){let e=` "${u}" `,t=Math.max(0,V-e.length-2);return{left:`┌`+`─`.repeat(t),label:e,right:`─`.repeat(2)+`┐`}}return{left:`┌`+`─`.repeat(V),label:``,right:`┐`}})(),ne=(0,n.useCallback)(e=>{g&&(_(null),I(`/${g.commandName} ${e.value}`))},[g,I]),U=(0,n.useCallback)(()=>{g&&(_(null),I(`/${g.commandName}`))},[g,I]),W=(0,n.useCallback)(()=>{_(null)},[]);return(0,o.jsxs)(t.Box,{flexDirection:`column`,children:[g&&(0,l.isPickerInteraction)(g.interaction)&&(0,o.jsx)(ct,{commandName:g.commandName,interaction:g.interaction,onSelect:ne,onCancel:W}),g&&(0,l.isConfirmInteraction)(g.interaction)&&(0,o.jsx)(ot,{commandName:g.commandName,interaction:g.interaction,onConfirm:U,onCancel:W}),!g&&O&&(0,o.jsx)(ft,{commands:k,selectedIndex:A,visible:O,isSubcommandMode:M}),(0,o.jsxs)(t.Text,{color:B,children:[H.left,H.label?(0,o.jsx)(t.Text,{backgroundColor:B,color:`black`,bold:!0,children:H.label}):null,H.right]}),(0,o.jsx)(t.Box,{borderStyle:`single`,borderTop:!1,borderColor:B,paddingLeft:1,children:a?(0,o.jsx)(t.Text,{color:`yellow`,children:` Interrupting...`}):s?(0,o.jsxs)(t.Text,{color:`cyan`,children:[` `,`Queued:`,` `,s.length>50?s.slice(0,47)+`...`:s,` `,(0,o.jsx)(t.Text,{dimColor:!0,children:`(Backspace to cancel)`})]}):i?(0,o.jsx)(_t,{text:` Waiting for response... (ESC to interrupt)`}):(0,o.jsxs)(t.Box,{children:[(0,o.jsx)(t.Text,{color:`green`,bold:!0,children:`> `}),(0,o.jsx)(Fe,{value:f,onChange:e=>{p(e),P(),h(null)},onSubmit:z,onPaste:te,placeholder:`Type a message or /help`,availableWidth:ee,cursorHint:m,enableVerticalNavigation:!1})]})})]})}function yt({items:e,renderItem:r,onSelect:i,onCancel:a,maxVisible:s=3}){let[c,l]=(0,n.useState)(()=>k()),u=(0,n.useRef)(c),d=(0,n.useCallback)(t=>{let n=M(u.current,t,{itemCount:e.length,maxVisible:s});if(u.current=n.state,l(n.state),n.effect.type===`cancel`)a();else if(n.effect.type===`select`){let t=e[n.effect.index];t!==void 0&&i(t)}},[e,s,a,i]);if((0,t.useInput)((e,t)=>{let n=A(t);n!==void 0&&d(n)}),e.length===0)return(0,o.jsx)(t.Box,{});let f=N(c,{itemCount:e.length,maxVisible:s});f!==c&&(u.current=f);let{selectedIndex:p,scrollOffset:m}=f,h=e.slice(m,m+s),g=m+s<e.length;return(0,o.jsxs)(t.Box,{flexDirection:`column`,children:[m>0&&(0,o.jsxs)(t.Text,{dimColor:!0,children:[` ↑ `,m,` more above`]}),h.map((e,n)=>(0,o.jsx)(t.Box,{marginBottom:1,children:r(e,m+n===p)},m+n)),g&&(0,o.jsxs)(t.Text,{dimColor:!0,children:[` ↓ `,e.length-m-s,` more below`]})]})}function bt(){return{value:``,resolved:!1}}function xt(e,t){if(t.escape===!0)return{type:`cancel`};if(t.return===!0)return{type:`submit`};if(t.backspace===!0||t.delete===!0)return{type:`delete`};if(e&&t.ctrl!==!0&&t.meta!==!0)return{type:`insert`,value:e}}function St(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`}}:Ct(e,n)}function Ct(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 wt({title:e,description:r,placeholder:i,onSubmit:a,onCancel:s,validate:c,allowEmpty:l=!1,masked:u=!1}){let[d,f]=(0,n.useState)(()=>bt()),p=(0,n.useRef)(d),m=(0,n.useCallback)(e=>{let t=St(p.current,e,{allowEmpty:l,validate:c});p.current=t.state,f(t.state),t.effect.type===`cancel`?s():t.effect.type===`submit`&&a(t.effect.value)},[l,c,s,a]);return(0,t.useInput)((e,t)=>{let n=xt(e,t);n!==void 0&&m(n)}),(0,o.jsxs)(t.Box,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[(0,o.jsx)(t.Text,{color:`yellow`,bold:!0,children:e}),(0,o.jsx)(Tt,{description:r}),(0,o.jsxs)(t.Box,{marginTop:1,children:[(0,o.jsx)(t.Text,{color:`cyan`,children:`> `}),d.value?(0,o.jsx)(t.Text,{children:u?`*`.repeat(d.value.length):d.value}):i?(0,o.jsx)(t.Text,{dimColor:!0,children:i}):null,(0,o.jsx)(t.Text,{color:`cyan`,children:`█`})]}),d.error&&(0,o.jsx)(t.Text,{color:`red`,children:d.error}),(0,o.jsx)(t.Text,{dimColor:!0,children:` Enter Submit Esc Cancel`})]})}function Tt({description:e}){return e===void 0||e.length===0?null:(0,o.jsx)(t.Text,{dimColor:!0,children:e})}function Et({prompt:e,onSubmit:n,onCancel:r}){return e.kind===`text`?(0,o.jsx)(wt,{title:e.title,description:e.description,placeholder:e.placeholder,allowEmpty:e.allowEmpty,masked:e.masked,validate:e.validate,onSubmit:n,onCancel:r},`text:${e.title}`):(0,o.jsxs)(t.Box,{flexDirection:`column`,children:[(0,o.jsx)(t.Text,{bold:!0,children:e.title}),e.description!==void 0&&e.description.length>0&&(0,o.jsx)(t.Text,{dimColor:!0,children:e.description}),(0,o.jsx)(yt,{items:[...e.options],maxVisible:e.maxVisible,renderItem:(e,n)=>(0,o.jsxs)(t.Text,{color:n?`cyan`:void 0,children:[n?`> `:` `,e.label]}),onSelect:e=>n(e.value),onCancel:r})]})}const Dt=new Set([`Bash`,`BackgroundProcess`]);function Ot(e){if(!Dt.has(e.toolName)||!e.toolResultData)return;let t=kt(e.toolResultData),n=It(t,`exitCode`),r=Lt(t,`success`),i=Nt(Mt(At(e.toolResultData,t))),a=i.slice(0,4),o=Math.max(0,i.length-a.length),s=e.result===`error`||r===!1||n!==void 0&&n!==0;return{status:s?`error`:`success`,statusLabel:jt(s,n),previewLines:a,omittedLineCount:o,transcriptHint:o>0?`... +${o} lines (full output in session transcript)`:void 0}}function kt(e){try{return JSON.parse(e)}catch{return e}}function At(e,t){if(!$(t))return e;let n=Ft(t,`output`);if(n!==void 0)return n;let r=Ft(t,`stdout`),i=Ft(t,`stderr`),a=Ft(t,`error`),o=[];return r&&o.push(r),i&&o.push(Pt(i,`[stderr] `)),!r&&!i&&a&&o.push(a),o.join(`
7
- `)}function jt(e,t){return t!==void 0&&t!==0?`exit ${t}`:e?`error`:`ok`}function Mt(e){return e?e.replace(/\r\n/g,`
8
- `).split(`
9
- `):[]}function Nt(e){let t=e.length;for(;t>0&&e[t-1].trim().length===0;)--t;return e.slice(0,t)}function Pt(e,t){return Mt(e).map(e=>`${t}${e}`).join(`
10
- `)}function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function Ft(e,t){if(!$(e))return;let n=e[t];return typeof n==`string`?n:void 0}function It(e,t){if(!$(e))return;let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Lt(e,t){if(!$(e))return;let n=e[t];return typeof n==`boolean`?n:void 0}const Rt=`\x1B[0m`,zt=` `,Bt=d.default;function Vt(e){return e===void 0?process.env.NO_COLOR||process.env.FORCE_COLOR===`0`?!1:process.env.FORCE_COLOR?!0:!!process.stdout.isTTY:e}function Ht(e){return e?.trim().toLowerCase()===`diff`}function Ut(e,t,n){let r=`${zt}${e}`.padEnd(t);return n?e.startsWith(`+`)?`${r}${Rt}`:e.startsWith(`-`)?`${r}${Rt}`:r.trimEnd():r.trimEnd()}function Wt(e,t,n){if(e.startsWith(`+`)||e.startsWith(`-`))return Ut(e,n,t);let r=`${zt}${e}`;return t?e.startsWith(`@@`)?`${r}${Rt}`:e.startsWith(`diff `)||e.startsWith(`index `)?`${r}${Rt}`:r:r}function Gt(e,t){let n=e.reduce((e,t)=>Math.max(e,4+t.length),0);return t===void 0?n:Math.max(n,t)}function Kt(e,t,n){let r=e.split(`
11
- `),i=Gt(r,n);return`${r.map(e=>Wt(e,t,i)).join(`
12
- `)}\n\n`}function qt(e,t){let n=new Bt(void 0,{ignoreIllegals:!0}),r=n.code.bind(n);return n.code=(n,i,a)=>Ht(i)?Kt(n,e,t):r(n,i,a),n}function Jt(e,t={}){let n=u.marked.parse(e,{renderer:qt(Vt(t.color),t.codeBlockWidth)});return typeof n==`string`?n.trimEnd():e}function Yt({tool:e}){let n=Ot(e);if(!n||n.statusLabel===`ok`&&n.previewLines.length===0&&!n.transcriptHint)return null;let r=n.status===`error`?`red`:`white`;return(0,o.jsxs)(t.Box,{flexDirection:`column`,marginLeft:4,children:[n.statusLabel!==`ok`&&(0,o.jsx)(t.Text,{color:r,dimColor:!0,children:n.statusLabel}),n.previewLines.map((e,n)=>(0,o.jsx)(t.Text,{color:r,dimColor:!0,children:e},`${e}-${n}`)),n.transcriptHint&&(0,o.jsx)(t.Text,{dimColor:!0,children:n.transcriptHint})]})}function Xt(e){let t=e.lines.length>12?Qt(e.lines):e.lines,n=Math.max(...t.map(e=>e.lineNumber),0).toString().length,r=t.map(e=>Zt(e,n)),i=e.lines.length>12;return{file:e.file,markdown:["```diff",...r,"```"].join(`
13
- `),truncated:i,remainingLineCount:i?e.lines.length-t.length:0}}function Zt(e,t){if(e.type===`hunk`)return e.text;let n=e.lineNumber.toString().padStart(t,` `);return e.type===`remove`?`- ${n} | ${e.text}`:e.type===`add`?`+ ${n} | ${e.text}`:` ${n} | ${e.text}`}function Qt(e){let t=$t(e),n=[];for(let e of t){if(n.length===0&&e.length>10)return e.slice(0,10);if(n.length+e.length>10)break;n.push(...e)}return n.length>0?n:e.slice(0,10)}function $t(e){let t=[],n=[];for(let r of e){if(r.type===`hunk`&&n.length>0){t.push(n),n=[r];continue}n.push(r)}return n.length>0&&t.push(n),t}function en({file:e,lines:n}){let r=Xt({file:e,lines:n});return(0,o.jsxs)(t.Box,{flexDirection:`column`,marginLeft:4,children:[r.file&&(0,o.jsxs)(t.Text,{color:`white`,dimColor:!0,children:[`│ `,r.file]}),(0,o.jsx)(t.Text,{children:Jt(r.markdown)}),r.truncated&&(0,o.jsxs)(t.Text,{color:`white`,dimColor:!0,children:[`│ ... and `,r.remainingLineCount,` more lines`]})]})}function tn({entry:e}){let n=e.data;if(!n)return(0,o.jsx)(o.Fragment,{});let r=n.promptTokens===void 0?`?`:nn(n.promptTokens),a=n.completionTokens===void 0?`?`:nn(n.completionTokens),s=nn(n.totalTokens),c=`${Math.round(n.contextUsedPercentage)}% (${(0,i.formatTokenCount)(n.contextUsedTokens)}/${(0,i.formatTokenCount)(n.contextMaxTokens)})`,l=n.costStatus===`unknown`?`cost unknown`:`cost ${n.costStatus}`;return(0,o.jsx)(t.Box,{flexDirection:`column`,marginBottom:1,children:(0,o.jsxs)(t.Box,{children:[(0,o.jsxs)(t.Text,{color:`white`,bold:!0,children:[`Usage:`,` `]}),(0,o.jsxs)(t.Text,{dimColor:!0,children:[n.kind,` `,s,` tokens (in `,r,` / out `,a,`) · Context `,c,` ·`,` `,l]})]})})}function nn(e){return e<1e3?e.toLocaleString():(0,i.formatTokenCount)(e)}function rn(e){return Ot(e)?.status===`error`?`✗`:e.isRunning?`⟳`:e.result===`error`?`✗`:e.result===`denied`?`⊘`:`✓`}function an(e){return Ot(e)?.status===`error`||e.result===`error`?`red`:e.isRunning||e.result===`denied`?`yellow`:`green`}function on(e){return`${rn(e)} ${e.toolName}${e.firstArg?`(${e.firstArg})`:``}`}function sn({role:e}){switch(e){case`user`:return(0,o.jsxs)(t.Text,{color:`green`,bold:!0,children:[`You:`,` `]});case`assistant`:return(0,o.jsxs)(t.Text,{color:`cyan`,bold:!0,children:[`Robota:`,` `]});case`system`:return(0,o.jsxs)(t.Text,{color:`yellow`,bold:!0,children:[`System:`,` `]});case`tool`:return(0,o.jsxs)(t.Text,{color:`white`,bold:!0,children:[`Tool:`,` `]})}}function cn({message:e}){if(!(0,i.isToolMessage)(e))return(0,o.jsx)(o.Fragment,{});let n=e.name,r=e.content,a=null;try{let e=JSON.parse(r);Array.isArray(e)&&e.length>0&&typeof e[0].line==`string`&&(a=e)}catch{}if(a)return(0,o.jsxs)(t.Box,{flexDirection:`column`,marginBottom:1,children:[(0,o.jsxs)(t.Box,{children:[(0,o.jsxs)(t.Text,{color:`white`,bold:!0,children:[`Tool:`,` `]}),n&&(0,o.jsxs)(t.Text,{color:`white`,dimColor:!0,children:[`[`,n,`]`]})]}),(0,o.jsx)(t.Text,{children:` `}),a.map((e,n)=>(0,o.jsxs)(t.Box,{flexDirection:`column`,children:[(0,o.jsxs)(t.Text,{color:`green`,children:[` `,`✓`,` `,e.line]}),e.diffLines&&e.diffLines.length>0&&(0,o.jsx)(en,{file:e.diffFile,lines:e.diffLines})]},n))]});let s=r.split(`
14
- `).filter(e=>e.trim());return(0,o.jsxs)(t.Box,{flexDirection:`column`,marginBottom:1,children:[(0,o.jsxs)(t.Box,{children:[(0,o.jsxs)(t.Text,{color:`white`,bold:!0,children:[`Tool:`,` `]}),n&&(0,o.jsxs)(t.Text,{color:`white`,dimColor:!0,children:[`[`,n,`]`]})]}),(0,o.jsx)(t.Text,{children:` `}),s.map((e,n)=>(0,o.jsxs)(t.Text,{color:`green`,children:[` `,`✓`,` `,e]},n))]})}const ln=n.default.memo(function({message:e}){if((0,i.isToolMessage)(e))return(0,o.jsx)(cn,{message:e});let n=e.content??``,r=e.state===`interrupted`;return(0,o.jsxs)(t.Box,{flexDirection:`column`,marginBottom:1,children:[(0,o.jsx)(t.Box,{children:(0,o.jsx)(sn,{role:e.role})}),(0,o.jsx)(t.Text,{children:` `}),(0,o.jsx)(t.Box,{marginLeft:2,children:(0,o.jsx)(t.Text,{wrap:`wrap`,children:(0,i.isAssistantMessage)(e)?Jt(n+(r?`
15
-
16
- _(interrupted)_`:``)):n})})]})});function un({entry:e}){let n=e.data,r=n?.tools,i=n?.summary?.split(`
17
- `)??[];return r&&r.length>0?(0,o.jsxs)(t.Box,{flexDirection:`column`,marginBottom:1,children:[(0,o.jsx)(t.Box,{children:(0,o.jsxs)(t.Text,{color:`white`,bold:!0,children:[`Tool:`,` `]})}),(0,o.jsx)(t.Text,{children:` `}),r.map((e,n)=>(0,o.jsxs)(t.Box,{flexDirection:`column`,children:[(0,o.jsxs)(t.Text,{color:an(e),children:[` `,on(e)]}),(0,o.jsx)(Yt,{tool:e}),e.diffLines&&e.diffLines.length>0&&(0,o.jsx)(en,{file:e.diffFile,lines:e.diffLines})]},n))]}):(0,o.jsxs)(t.Box,{flexDirection:`column`,marginBottom:1,children:[(0,o.jsx)(t.Box,{children:(0,o.jsxs)(t.Text,{color:`white`,bold:!0,children:[`Tool:`,` `]})}),(0,o.jsx)(t.Text,{children:` `}),i.map((e,n)=>(0,o.jsxs)(t.Text,{color:`green`,children:[` `,e]},n))]})}function dn({entry:e}){let n=e.data,r=typeof n?.message==`string`?n.message:typeof n?.content==`string`?n.content:e.type;return(0,o.jsxs)(t.Box,{flexDirection:`column`,marginBottom:1,children:[(0,o.jsx)(t.Box,{children:(0,o.jsxs)(t.Text,{color:`yellow`,bold:!0,children:[`System:`,` `]})}),(0,o.jsx)(t.Text,{children:` `}),(0,o.jsx)(t.Box,{marginLeft:2,children:(0,o.jsx)(t.Text,{wrap:`wrap`,children:r})})]})}function fn({entry:e}){if(e.category===`chat`){let t=e.data;return(0,o.jsx)(ln,{message:t})}return e.type===`tool-summary`?(0,o.jsx)(un,{entry:e}):e.type===`usage-summary`?(0,o.jsx)(tn,{entry:e}):e.type===`tool-start`||e.type===`tool-end`?(0,o.jsx)(o.Fragment,{}):(0,o.jsx)(dn,{entry:e})}function pn({history:e}){return(0,o.jsx)(t.Box,{flexDirection:`column`,children:e.map(e=>(0,o.jsx)(fn,{entry:e},e.id))})}const mn=[`Allow [y]`,`Allow always (this session) [s]`,`Allow always (this project) [p]`,`Deny [n]`];function hn(e,t){let n=j({...t,escape:!1});if(n!==void 0)return n;if(e===`y`||e===`1`)return{type:`shortcut`,index:0};if(e===`s`||e===`a`||e===`2`)return{type:`shortcut`,index:1};if(e===`p`||e===`3`)return{type:`shortcut`,index:2};if(e===`n`||e===`d`||e===`4`)return{type:`shortcut`,index:3}}function gn(e,t){if(e.resolved)return{state:e,effect:{type:`none`}};if(typeof t!=`string`)return vn(e,t.index);let n=M(e,t,{itemCount:mn.length});return n.effect.type===`select`?{state:n.state,effect:{type:`resolve`,decision:_n(n.effect.index)}}:{state:n.state,effect:{type:`none`}}}function _n(e){return e===0?!0:e===1?`allow-session`:e===2?`allow-project`:!1}function vn(e,t){return{state:{...e,selectedIndex:t,resolved:!0},effect:{type:`resolve`,decision:_n(t)}}}function yn(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 bn({request:e}){let[r,i]=n.default.useState(()=>k()),a=n.default.useRef(r),s=n.default.useRef(e);if(s.current!==e){s.current=e;let t=k();a.current=t,i(t)}let c=n.default.useCallback(t=>{let n=gn(a.current,t);a.current=n.state,i(n.state),n.effect.type===`resolve`&&e.resolve(n.effect.decision)},[e]);return(0,t.useInput)((e,t)=>{let n=hn(e,t);n!==void 0&&c(n)}),(0,o.jsxs)(t.Box,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[(0,o.jsx)(t.Text,{color:`yellow`,bold:!0,children:`[Permission Required]`}),(0,o.jsxs)(t.Text,{children:[`Tool:`,` `,(0,o.jsx)(t.Text,{color:`cyan`,bold:!0,children:e.toolName})]}),(0,o.jsxs)(t.Text,{dimColor:!0,children:[` `,yn(e.toolArgs)]}),(0,o.jsx)(t.Box,{marginTop:1,children:mn.map((e,n)=>(0,o.jsx)(t.Box,{marginRight:2,children:(0,o.jsxs)(t.Text,{color:n===r.selectedIndex?`cyan`:void 0,bold:n===r.selectedIndex,children:[n===r.selectedIndex?`> `:` `,e]})},e))}),(0,o.jsx)(t.Text,{dimColor:!0,children:` left/right to select, Enter to confirm`})]})}function xn(e,t,n){let r=j({...t,escape:!1});if(r!==void 0)return r;if(n===2&&e===`y`)return{type:`shortcut`,index:0};if(n===2&&e===`n`)return{type:`shortcut`,index:1}}function Sn(e,t,n){return e.resolved?{state:e,effect:{type:`none`}}:typeof t==`string`?M(e,t,{itemCount:n}):{state:{...e,selectedIndex:t.index,resolved:!0},effect:{type:`select`,index:t.index}}}function Cn({message:e,options:r=[`Yes`,`No`],onSelect:i}){let[a,s]=(0,n.useState)(()=>k()),c=(0,n.useRef)(a),l=(0,n.useCallback)(e=>{let t=Sn(c.current,e,r.length);c.current=t.state,s(t.state),t.effect.type===`select`&&i(t.effect.index)},[i,r.length]);return(0,t.useInput)((e,t)=>{let n=xn(e,t,r.length);n!==void 0&&l(n)}),(0,o.jsxs)(t.Box,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[(0,o.jsx)(t.Text,{color:`yellow`,children:e}),(0,o.jsx)(t.Box,{marginTop:1,children:r.map((e,n)=>(0,o.jsx)(t.Box,{marginRight:2,children:(0,o.jsxs)(t.Text,{color:n===a.selectedIndex?`cyan`:void 0,bold:n===a.selectedIndex,children:[n===a.selectedIndex?`> `:` `,e]})},e))}),(0,o.jsx)(t.Text,{dimColor:!0,children:` arrow keys to select, Enter to confirm`})]})}function wn(e,t,n,i,a){let[o,s]=(0,r.useState)([]),[c,l]=(0,r.useState)(!1),[u,d]=(0,r.useState)();return(0,r.useEffect)(()=>{if(s([]),d(void 0),e===`marketplace-list`)l(!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}));s([...t,...n]),l(!1)}).catch(e=>{d(e instanceof Error?e.message:String(e)),l(!1)});else if(e===`marketplace-browse`){let e=t??``;l(!0),n.listAvailablePlugins(e).then(e=>{s(e.map(e=>({label:e.name,value:e.name,hint:e.installed?`installed`:e.description}))),l(!1)}).catch(e=>{d(e instanceof Error?e.message:String(e)),l(!1)})}else e===`installed-list`&&(l(!0),n.listInstalled().then(e=>{s(e.map(e=>({label:e.name,value:e.name,hint:e.description}))),l(!1)}).catch(e=>{d(e instanceof Error?e.message:String(e)),l(!1)}))},[a,e,t,n,i]),{items:o,loading:c,error:u}}function Tn({title:e,items:r,onSelect:i,onBack:a,loading:s,error:c}){let[l,u]=(0,n.useState)(()=>k()),d=(0,n.useRef)(l),f=!s&&!c,p=(0,n.useCallback)(e=>{let t=M(d.current,e,{itemCount:r.length,enabled:f});if(d.current=t.state,u(t.state),t.effect.type===`cancel`)a();else if(t.effect.type===`select`){let e=r[t.effect.index];e!==void 0&&i(e.value)}},[f,r,a,i]);(0,t.useInput)((e,t)=>{let n=A(t);n!==void 0&&p(n)});let m=N(l,{itemCount:r.length});m!==l&&(d.current=m);let h=m.selectedIndex;return(0,o.jsxs)(t.Box,{flexDirection:`column`,borderStyle:`round`,borderColor:`yellow`,paddingX:1,children:[(0,o.jsx)(t.Text,{color:`yellow`,bold:!0,children:e}),s&&(0,o.jsx)(t.Box,{marginTop:1,children:(0,o.jsx)(t.Text,{dimColor:!0,children:`Loading...`})}),c&&(0,o.jsxs)(t.Box,{marginTop:1,flexDirection:`column`,children:[(0,o.jsx)(t.Text,{color:`red`,children:c}),(0,o.jsx)(t.Text,{dimColor:!0,children:`Press Esc to go back`})]}),!s&&!c&&(0,o.jsx)(t.Box,{flexDirection:`column`,marginTop:1,children:r.map((e,n)=>(0,o.jsxs)(t.Box,{children:[(0,o.jsxs)(t.Text,{color:n===h?`cyan`:void 0,bold:n===h,children:[n===h?`> `:` `,e.label]}),e.hint&&(0,o.jsxs)(t.Text,{dimColor:!0,children:[` `,e.hint]})]},e.value))}),(0,o.jsx)(t.Text,{dimColor:!0,children:s||c?``:` ↑↓ Navigate Enter Select Esc Back`})]})}function En(e,t){e===`marketplace`?t.push({screen:`marketplace-list`}):e===`installed`&&t.push({screen:`installed-list`})}function Dn(e,t){e===`__add__`?t.push({screen:`marketplace-add`}):t.push({screen:`marketplace-action`,context:{marketplace:e}})}function On(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 kn(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 An(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 jn(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 Mn(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 Nn({callbacks:e,onClose:t,addMessage:r}){let[i,a]=(0,n.useState)([{screen:`main`}]),[s,c]=(0,n.useState)(),[l,u]=(0,n.useState)(0),d=i[i.length-1]??{screen:`main`},f=(0,n.useCallback)(e=>{a(t=>[...t,e])},[]),p=(0,n.useCallback)(()=>{a(e=>e.length<=1?(t(),e):e.slice(0,-1))},[t]),m=(0,n.useCallback)(e=>{a(n=>{let r=n.slice(0,Math.max(1,n.length-e));return r.length===0?(t(),n):r})},[t]),h=(0,n.useCallback)(e=>{r?.({role:`system`,content:e})},[r]),g=(0,n.useCallback)(()=>{u(e=>e+1)},[]),_=(0,n.useCallback)(e=>c(e),[c]),v={push:(0,n.useCallback)(e=>f({screen:e.screen,context:e.context}),[f]),pop:p,popN:m,notify:h,setConfirm:_,refresh:g},{items:y,loading:b,error:x}=wn(d.screen,d.context?.marketplace,e,l,i.length),S=(0,n.useCallback)(t=>{let n=d.screen,r=d.context;n===`main`?En(t,v):n===`marketplace-list`?Dn(t,v):n===`marketplace-action`?On(t,r?.marketplace??``,e,v):n===`marketplace-browse`?kn(t,r?.marketplace??``,y,v):n===`marketplace-install-scope`?An(t,r?.pluginId??``,e,v):n===`installed-list`?jn(t,e,v):n===`installed-action`&&Mn(t,r?.pluginId??``,e,v)},[d,y,e,f,p,m,h,c,g]),C=(0,n.useCallback)(t=>{d.screen===`marketplace-add`&&e.marketplaceAdd(t).then(e=>{h(`Added marketplace "${e}" from ${t}.`),p()}).catch(e=>{h(`Error: ${e instanceof Error?e.message:String(e)}`),p()})},[d.screen,e,h,p]);if(s)return(0,o.jsx)(Cn,{message:s.message,onSelect:e=>{e===0?s.onConfirm():s.onCancel()}});let w=d.screen;return w===`marketplace-add`?(0,o.jsx)(wt,{title:`Add Marketplace Source`,placeholder:`owner/repo or git URL`,onSubmit:C,onCancel:p,validate:e=>e.includes(`/`)?void 0:`Must be owner/repo or a git URL`}):w===`marketplace-action`?(0,o.jsx)(Tn,{title:`Marketplace: ${d.context?.marketplace??``}`,items:[{label:`Browse plugins`,value:`browse`},{label:`Update`,value:`update`},{label:`Remove`,value:`remove`}],onSelect:S,onBack:p},i.length):w===`marketplace-install-scope`?(0,o.jsx)(Tn,{title:`Install scope for "${d.context?.pluginId??``}"`,items:[{label:`User scope`,value:`user`},{label:`Project scope`,value:`project`}],onSelect:S,onBack:p},i.length):w===`installed-action`?(0,o.jsx)(Tn,{title:`Plugin: ${d.context?.pluginId??``}`,items:[{label:`Uninstall`,value:`uninstall`}],onSelect:S,onBack:p},i.length):(0,o.jsx)(Tn,{title:{main:`Plugin Management`,"marketplace-list":`Marketplace`,"marketplace-browse":`Browse: ${d.context?.marketplace??``}`,"installed-list":`Installed Plugins`}[w]??`Plugin Management`,items:{main:[{label:`Marketplace`,value:`marketplace`},{label:`Installed Plugins`,value:`installed`}]}[w]??y,onSelect:S,onBack:p,loading:b,error:x},`${w}-${i.length}-${l}`)}function Pn({sessions:e,onSelect:n,onCancel:r}){return(0,o.jsxs)(t.Box,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[(0,o.jsx)(t.Text,{bold:!0,color:`cyan`,children:`Select a session to resume (ESC to cancel):`}),(0,o.jsx)(yt,{items:[...e],renderItem:(e,n)=>{let r=e.preview?e.preview.slice(0,60)+(e.preview.length>60?`...`:``):``;return(0,o.jsxs)(t.Text,{children:[n?`> `:` `,(0,o.jsx)(t.Text,{bold:!0,children:e.name??e.id.slice(0,8)}),` `,(0,o.jsx)(t.Text,{dimColor:!0,children:new Date(e.updatedAt).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}),` `,(0,o.jsxs)(t.Text,{dimColor:!0,children:[`msgs: `,e.messageCount]}),r?(0,o.jsxs)(o.Fragment,{children:[`
18
- `,(0,o.jsx)(t.Text,{color:`gray`,children:r})]}):null]})},onSelect:e=>n(e.id),onCancel:r})]})}function Fn(e){let t=In(e),n=e.hasPendingPrompt&&t.kind!==`queued`?[`queued`]:[],r=[t.label,...n].join(` · `);return{...t,segments:n,text:r}}function In(e){return e.activeToolCount>0?{kind:`tools`,label:`Tools x${e.activeToolCount}`,color:`cyan`}:e.isThinking?{kind:`thinking`,label:`Thinking`,color:`yellow`}:e.activeBackgroundTaskCount>0?{kind:`background`,label:`Background x${e.activeBackgroundTaskCount}`,color:`cyan`}:e.hasPendingPrompt?{kind:`queued`,label:`Queued`,color:`yellow`}:{kind:`idle`,label:`Idle`,color:`gray`}}function Ln(e){return e>=90?`red`:e>=70?`yellow`:`green`}function Rn({isThinking:e,activeToolCount:n,activeBackgroundTaskCount:r,hasPendingPrompt:i}){let a=Fn({isThinking:e,activeToolCount:n,activeBackgroundTaskCount:r,hasPendingPrompt:i});return(0,o.jsx)(t.Text,{color:a.color,bold:a.kind!==`idle`,children:a.text})}function zn({percentage:e,usedTokens:n,maxTokens:r}){return(0,o.jsxs)(t.Text,{color:Ln(e),children:[`Context: `,Math.round(e),`% (`,(0,i.formatTokenCount)(n),`/`,(0,i.formatTokenCount)(r),`)`]})}function Bn({permissionMode:e}){return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(t.Text,{color:`cyan`,bold:!0,children:`Mode:`}),` `,(0,o.jsx)(t.Text,{children:e})]})}function Vn(e){return e!==`default`}function Hn({modelName:e,providerDisplayName:n}){return n===void 0?(0,o.jsx)(t.Text,{dimColor:!0,children:e}):(0,o.jsxs)(t.Text,{dimColor:!0,children:[n,` `,e]})}function Un(e){let n=e.showGitBranch&&e.gitBranch!==void 0&&e.gitBranch.length>0,r=Vn(e.permissionMode);return(0,o.jsxs)(t.Text,{children:[(0,o.jsx)(Rn,{isThinking:e.isThinking,activeToolCount:e.activeToolCount,activeBackgroundTaskCount:e.activeBackgroundTaskCount,hasPendingPrompt:e.hasPendingPrompt}),r&&(0,o.jsxs)(o.Fragment,{children:[` | `,(0,o.jsx)(Bn,{permissionMode:e.permissionMode})]}),e.sessionName&&(0,o.jsxs)(o.Fragment,{children:[` | `,(0,o.jsx)(t.Text,{color:`magenta`,children:e.sessionName})]}),n&&(0,o.jsxs)(o.Fragment,{children:[` | `,(0,o.jsxs)(t.Text,{dimColor:!0,children:[`git: `,e.gitBranch]})]}),` | `,(0,o.jsx)(Hn,{modelName:e.modelName,providerDisplayName:e.providerDisplayName}),` | `,(0,o.jsx)(zn,{percentage:e.contextPercentage,usedTokens:e.contextUsedTokens,maxTokens:e.contextMaxTokens})]})}function Wn({permissionMode:e,modelName:n,providerDisplayName:r,sessionId:i,isThinking:a,activeToolCount:s=0,activeBackgroundTaskCount:c=0,hasPendingPrompt:l=!1,contextPercentage:u,contextUsedTokens:d,contextMaxTokens:f,sessionName:p,gitBranch:m,showGitBranch:h=!0,activeAgentLabel:g}){return(0,o.jsxs)(t.Box,{borderStyle:`single`,borderColor:`gray`,paddingLeft:1,paddingRight:1,justifyContent:`space-between`,children:[(0,o.jsx)(Un,{permissionMode:e,modelName:n,providerDisplayName:r,isThinking:a,activeToolCount:s,activeBackgroundTaskCount:c,hasPendingPrompt:l,contextPercentage:u,contextUsedTokens:d,contextMaxTokens:f,sessionName:p,gitBranch:m,showGitBranch:h}),g!==void 0&&(0,o.jsxs)(t.Text,{color:`yellow`,bold:!0,children:[`[`,g,`]`]})]})}function Gn({cwd:e,permissionMode:t,modelId:r,providerType:i,sessionId:a,isThinking:s,activeToolCount:c,activeBackgroundTaskCount:l,hasPendingPrompt:u,contextState:d,sessionName:f,settings:p,activeAgentLabel:m,gitRefreshToken:h}){let g=Z(),_=(0,n.useMemo)(()=>g.getGitBranch(e),[g,e,h]),v=(0,n.useMemo)(()=>i===void 0?void 0:g.getProviderDisplayName(i),[g,i]);return p.enabled?(0,o.jsx)(Wn,{permissionMode:t,modelName:r??``,providerDisplayName:v,sessionId:a,isThinking:s,activeToolCount:c,activeBackgroundTaskCount:l,hasPendingPrompt:u,contextPercentage:d.percentage,contextUsedTokens:d.usedTokens,contextMaxTokens:d.maxTokens,sessionName:f,gitBranch:_,showGitBranch:p.gitBranch,activeAgentLabel:m}):null}function Kn(e){return e.isRunning?{color:`yellow`,icon:`⟳`,strikethrough:!1}:e.result===`error`?{color:`red`,icon:`✗`,strikethrough:!0}:e.result===`denied`?{color:`yellowBright`,icon:`⊘`,strikethrough:!0}:{color:`green`,icon:`✓`,strikethrough:!1}}function qn(e){return e?(0,o.jsx)(t.Box,{marginBottom:1,children:(0,o.jsx)(t.Text,{color:`yellow`,children:`Thinking...`})}):(0,o.jsx)(o.Fragment,{})}function Jn(e){return(0,o.jsxs)(t.Box,{flexDirection:`column`,marginBottom:1,children:[(0,o.jsx)(t.Text,{color:`white`,bold:!0,children:`Tools:`}),(0,o.jsx)(t.Text,{children:` `}),e.map((e,n)=>{let{color:r,icon:i,strikethrough:a}=Kn(e);return(0,o.jsxs)(t.Box,{flexDirection:`column`,children:[(0,o.jsxs)(t.Text,{color:r,strikethrough:a,children:[` `,i,` `,e.toolName,`(`,e.firstArg,`)`]}),e.diffLines&&e.diffLines.length>0&&(0,o.jsx)(en,{file:e.diffFile,lines:e.diffLines})]},`${e.toolName}-${n}`)})]})}function Yn({text:e,activeTools:n,isThinking:r=!1}){let i=n.length>0,a=e.length>0;return!i&&!a?qn(r):(0,o.jsxs)(t.Box,{flexDirection:`column`,children:[i&&Jn(n),a&&(0,o.jsxs)(t.Box,{flexDirection:`column`,marginBottom:1,children:[(0,o.jsx)(t.Text,{color:`cyan`,bold:!0,children:`Robota:`}),(0,o.jsx)(t.Text,{children:` `}),(0,o.jsx)(t.Box,{marginLeft:2,children:(0,o.jsx)(t.Text,{wrap:`wrap`,children:Jt(e)})})]})]})}function Xn({entry:e,selected:n}){let r=e.config.enabled,i=r?`●`:`○`,a=r?`[enabled] `:`[disabled]`,s=e.config.options?.port,c=typeof s==`number`?`port: ${s}`:``;return(0,o.jsx)(t.Box,{children:(0,o.jsx)(t.Text,{color:n?`cyan`:void 0,bold:n,children:`${i} ${e.transport.name.padEnd(18)} ${a} ${c}`})})}function Zn(e,r,i,a,o,s,c,l){(0,t.useInput)((0,n.useCallback)((t,n)=>{if(!i){if(n.upArrow){o(e=>Math.max(0,e-1));return}if(n.downArrow){o(t=>Math.min(e.length-1,t+1));return}if(n.escape||n.return){c();return}if(t===` `){let t=e[r];if(!t)return;s(!0),a.setEnabled(t.transport.name,!t.config.enabled).then(()=>{l(),s(!1)}).catch(()=>s(!1))}}},[i,e,r,a,c,l,o,s]))}function Qn({registry:e,onClose:r}){let[i,a]=(0,n.useState)(()=>e.getAll()),[s,c]=(0,n.useState)(0),[l,u]=(0,n.useState)(!1);return Zn(i,s,l,e,c,u,r,(0,n.useCallback)(()=>{a(e.getAll())},[e])),(0,o.jsxs)(t.Box,{flexDirection:`column`,paddingX:2,paddingY:1,children:[(0,o.jsx)(t.Text,{bold:!0,children:`Settings › Transports`}),(0,o.jsx)(t.Box,{marginTop:1,flexDirection:`column`,children:i.map((e,t)=>(0,o.jsx)(Xn,{entry:e,selected:t===s},e.transport.name))}),(0,o.jsx)(t.Box,{marginTop:1,children:(0,o.jsx)(t.Text,{dimColor:!0,children:`↑↓ select space toggle enter/esc close`})}),l&&(0,o.jsx)(t.Box,{marginTop:1,children:(0,o.jsx)(t.Text,{color:`yellow`,children:`Saving…`})})]})}function $n({message:e}){return(0,o.jsx)(t.Box,{paddingX:1,marginBottom:1,children:(0,o.jsx)(t.Text,{color:`yellow`,children:e})})}function er(e){let[t,r]=(0,n.useState)(e.resumeSessionId),[i,a]=(0,n.useState)(e.showSessionPickerOnStart??!1);return(0,o.jsx)(fe,{value:e.cliAdapter,children:(0,o.jsx)(tr,{...e,showSessionPickerOnStart:i,resumeSessionId:t,onSessionSwitch:e=>{a(!1),r(e)}},t??`__new__`)})}function tr(e){let r=e.cwd,[s,c]=(0,n.useState)(e.sessionName),{interactiveSession:l,registry:u,commandEffectQueue:d,history:f,addEntry:p,streamingText:g,activeTools:_,isThinking:v,isAborting:y,isShuttingDown:b,pendingPrompt:x,executionWorkspaceSnapshot:S,selectedExecutionEntryId:C,selectExecutionWorkspaceEntry:w,readExecutionWorkspaceDetail:T,permissionRequest:O,contextState:k,handleSubmit:A,handleAbort:j,handleCancelQueue:M,handleShutdown:N}=le({cwd:r,provider:e.provider,permissionMode:e.permissionMode,maxTurns:e.maxTurns,sessionStore:e.sessionStore,resumeSessionId:e.resumeSessionId,forkSession:e.forkSession,sessionName:e.sessionName,onAutoNamed:c,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,shellExec:e.shellExec,transportRegistry:e.transportRegistry,language:e.language,reloadPluginCommandSource:e.reloadPluginCommandSource,agentName:e.agentName,systemPrompt:e.systemPrompt,appendSystemPrompt:e.appendSystemPrompt,allowedTools:e.allowedTools,deniedTools:e.deniedTools}),te=de(r),P=e.commandHostAdapters?.plugin??te,{exit:F}=(0,t.useApp)(),[L,R]=(0,n.useState)(),[z,B]=(0,n.useState)(!1),[V,H]=(0,n.useState)(null),[ne,U]=(0,n.useState)(),[W,G]=(0,n.useState)(!1),[re,ie]=ge(),[ae,oe]=(0,n.useState)(0),se=(0,n.useMemo)(()=>m(S),[S]),ce=h(S),K=(0,n.useMemo)(()=>S?.entries.find(e=>e.id===C),[S,C]),{handleSubmit:ue,pendingInteractionPrompt:q,showPluginTUI:J,showSessionPicker:Y,showTransportTUI:X,setShowPluginTUI:fe,setShowSessionPicker:Z,setShowTransportTUI:me,handleInteractionSubmit:he,handleInteractionCancel:_e}=pe({cwd:r,providerOverride:e.providerOverride,interactiveSession:l,commandEffectQueue:d,addEntry:p,baseHandleSubmit:A,setSessionName:c,setStatusLineSettings:ie,showSessionPickerOnStart:e.showSessionPickerOnStart,openAgentSwitcher:()=>B(!0)}),Q=!K||K.kind===`main_thread`||K.controls.includes(`send`),ve=K&&K.kind!==`main_thread`?K.title:void 0,ye=(0,n.useMemo)(()=>S?.entries.find(e=>e.kind===`main_thread`)?.id,[S]),be=(0,n.useCallback)(async e=>{K&&K.kind!==`main_thread`&&K.controls.includes(`send`)?await l.sendAgentJob(K.sourceId,e):await ue(e)},[K,ue,l]),xe=(0,n.useCallback)(async e=>{oe(e=>e+1),await be(e)},[be]),Se=(0,n.useRef)(!1);(0,n.useEffect)(()=>{Se.current&&!v&&oe(e=>e+1),Se.current=v},[v]),(0,n.useEffect)(()=>{let e=l?.getName?.();e&&!s&&c(e)},[l,s]),(0,n.useEffect)(()=>{let t=!0;return e.startupUpdateNotice?.then(e=>{t&&e!==void 0&&R(e)}).catch(()=>{}),()=>{t=!1}},[e.startupUpdateNotice]),(0,n.useEffect)(()=>{let e=s?`Robota — ${s}`:`Robota`;process.stdout.write(`\x1b]0;${e}\x07`)},[s]),(0,t.useInput)((e,t)=>{!t.escape||!v||O||J||X||Y||z||j()}),(0,t.useInput)((e,t)=>{!t.ctrl||e!==`b`||O||J||Y||b||B(e=>!e)}),(0,t.useInput)((e,t)=>{!t.escape||v||O||J||X||Y||z||K&&K.kind!==`main_thread`&&ye!==void 0&&w(ye)}),(0,t.useInput)((e,t)=>{!t.ctrl||e!==`c`||b||N(`prompt_input_exit`).finally(()=>F())}),(0,n.useEffect)(()=>{let e=()=>{b||N(`other`).finally(()=>F())};return process.once(`SIGINT`,e),process.once(`SIGTERM`,e),()=>{process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}},[N,F,b]),(0,n.useEffect)(()=>{if(!K||K.kind===`main_thread`){H(null),U(void 0),G(!1);return}let e=!0;return G(!0),U(void 0),T(K.id).then(t=>{e&&(H(t),G(!1))}).catch(t=>{e&&(U(t.message),G(!1))}),()=>{e=!1}},[S,T,K]);let Ce=e.permissionMode??`default`,we=``;try{let e=l.getSession();Ce=e.getPermissionMode(),we=e.getSessionId()}catch{}return(0,o.jsxs)(t.Box,{flexDirection:`column`,children:[(0,o.jsxs)(t.Box,{flexDirection:`column`,paddingX:1,marginBottom:1,children:[(0,o.jsx)(t.Text,{color:`cyan`,bold:!0,children:`
19
- ____ ___ ____ ___ _____ _
20
- | _ \\ / _ \\| __ ) / _ \\_ _|/ \\
21
- | |_) | | | | _ \\| | | || | / _ \\
22
- | _ <| |_| | |_) | |_| || |/ ___ \\
23
- |_| \\_\\\\___/|____/ \\___/ |_/_/ \\_\\
24
- `}),(0,o.jsxs)(t.Text,{dimColor:!0,children:[` v`,e.version??`0.0.0`]})]}),L&&(0,o.jsx)($n,{message:L}),(0,o.jsxs)(t.Box,{flexDirection:`column`,paddingX:1,flexGrow:1,children:[K&&K.kind!==`main_thread`?(0,o.jsx)(D,{entry:K,page:V,loading:W,error:ne}):(0,o.jsx)(pn,{history:f}),b&&(0,o.jsx)(t.Box,{marginBottom:1,children:(0,o.jsx)(t.Text,{color:`yellow`,children:`Shutting down...`})}),(v||_.length>0)&&(0,o.jsx)(t.Box,{flexDirection:`column`,marginBottom:1,children:(0,o.jsx)(Yn,{text:g,activeTools:_,isThinking:v})}),(0,o.jsx)(E,{entries:se})]}),z&&(0,o.jsx)(I,{snapshot:S,selectedEntryId:C,onSelect:w,onClose:()=>B(!1)}),O&&(0,o.jsx)(bn,{request:O}),q&&(0,o.jsx)(Et,{prompt:q,onSubmit:he,onCancel:_e}),J&&(0,o.jsx)(Nn,{callbacks:P,onClose:()=>fe(!1),addMessage:e=>p((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(e.content)))}),X&&e.transportRegistry&&(0,o.jsx)(Qn,{registry:e.transportRegistry,onClose:()=>me(!1)}),Y&&(0,o.jsx)(Pn,{sessions:(0,a.listResumableSessionSummaries)(e.sessionStore,e.cwd),onSelect:t=>{Z(!1),e.onSessionSwitch(t)},onCancel:()=>{Z(!1),p((0,i.messageToHistoryEntry)((0,i.createSystemMessage)(`Session resume cancelled.`)))}}),(0,o.jsx)(ee,{percentage:k.percentage}),(0,o.jsx)(Gn,{cwd:r,permissionMode:Ce,modelId:e.modelId,providerType:e.providerType,sessionId:we,isThinking:v,activeToolCount:_.length,activeBackgroundTaskCount:ce,hasPendingPrompt:x!==null,contextState:k,sessionName:s,settings:re,activeAgentLabel:ve,gitRefreshToken:ae}),(0,o.jsx)(vt,{onSubmit:xe,onCancelQueue:M,isDisabled:!!O||J||X||Y||z||b||q!==null||v&&!!x||!Q,isAborting:y,pendingPrompt:x,registry:u,sessionName:s,history:f}),(0,o.jsx)(t.Box,{position:`absolute`,children:(0,o.jsx)(t.Text,{children:` `})})]})}async function nr(e){process.on(`unhandledRejection`,e=>{process.stderr.write(`\n[UNHANDLED REJECTION] ${e}\n`),e instanceof Error&&process.stderr.write(`${e.stack}\n`)}),await(0,t.render)((0,o.jsx)(er,{...e}),{exitOnCtrlC:!1}).waitUntilExit()}var rr=class{name=`tui`;defaultEnabled=!0;optionsSchema={};options;constructor(e){this.options=e}attach(e){}async start(){await nr(this.options)}async stop(){}validateOptions(e){return!0}};function ir({providerDefinitions:e,reloadPluginCommandSource:t}){return{getUserSettingsPath:()=>(0,a.getUserSettingsPath)(),readSettings:e=>(0,a.readSettings)(e),writeSettings:(e,t)=>(0,a.writeSettings)(e,t),deleteSettings:e=>(0,a.deleteSettings)(e),applyStatusLineSettings:(e,t)=>(0,a.applyStatusLineSettings)(e,t),reloadPluginCommandSource:e=>{t(e)},applyActiveModelChange:(e,t,n)=>((0,a.applyActiveModelChange)(e,t,n),{applied:!0}),getGitBranch:e=>(0,a.resolveGitBranch)(e),getProviderDisplayName:t=>(0,i.findProviderDefinition)(e,t)?.displayName??t}}Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return rr}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return ir}});
@@ -1,66 +0,0 @@
1
- import type { ITuiPickerItem, TAnyTuiCommandInteraction } from './command-interaction.js';
2
-
3
- function getModeItems(): ITuiPickerItem[] {
4
- return [
5
- { label: 'plan', value: 'plan', description: 'Plan only, no execution' },
6
- { label: 'default', value: 'default', description: 'Ask before risky actions' },
7
- { label: 'acceptEdits', value: 'acceptEdits', description: 'Auto-approve file edits' },
8
- {
9
- label: 'bypassPermissions',
10
- value: 'bypassPermissions',
11
- description: 'Skip all permission checks',
12
- },
13
- ];
14
- }
15
-
16
- function getLanguageItems(): ITuiPickerItem[] {
17
- return [
18
- { label: 'ko Korean', value: 'ko', description: '한국어' },
19
- { label: 'en English', value: 'en', description: 'English' },
20
- { label: 'ja Japanese', value: 'ja', description: '日本語' },
21
- { label: 'zh Chinese', value: 'zh', description: '中文' },
22
- ];
23
- }
24
-
25
- function getProviderSubcommandItems(): ITuiPickerItem[] {
26
- return [
27
- { label: 'current', value: 'current', description: 'Show current provider' },
28
- { label: 'list', value: 'list', description: 'List available providers' },
29
- { label: 'use', value: 'use', description: 'Switch to a provider' },
30
- { label: 'add', value: 'add', description: 'Add a new provider' },
31
- { label: 'test', value: 'test', description: 'Test provider connection' },
32
- ];
33
- }
34
-
35
- const BUILT_IN_INTERACTIONS: Record<string, TAnyTuiCommandInteraction | undefined> = {
36
- agent: undefined,
37
- background: undefined,
38
- clear: { onMissingArgs: 'confirm', message: 'Clear conversation history?' },
39
- compact: undefined,
40
- context: undefined,
41
- cost: undefined,
42
- exit: { onMissingArgs: 'confirm', message: 'Exit the session?' },
43
- help: undefined,
44
- language: { onMissingArgs: 'picker', getItems: getLanguageItems },
45
- memory: undefined,
46
- mode: { onMissingArgs: 'picker', getItems: getModeItems },
47
- model: undefined,
48
- permissions: undefined,
49
- plugin: undefined,
50
- provider: { onMissingArgs: 'picker', getItems: getProviderSubcommandItems },
51
- rename: undefined,
52
- reset: undefined,
53
- resume: undefined,
54
- rewind: undefined,
55
- settings: undefined,
56
- skills: undefined,
57
- statusline: undefined,
58
- 'user-local': undefined,
59
- 'validate-session': undefined,
60
- };
61
-
62
- export function resolveCommandInteraction(
63
- commandName: string,
64
- ): TAnyTuiCommandInteraction | undefined {
65
- return BUILT_IN_INTERACTIONS[commandName];
66
- }
@@ -1,299 +0,0 @@
1
- import { createSystemMessage, messageToHistoryEntry } from '@robota-sdk/agent-core';
2
- import { useState, useCallback, useEffect, useRef } from 'react';
3
-
4
- import { CommandEffectQueue, type ICommandEffectQueue } from './command-effect-queue.js';
5
- import { initializeSession, type IInitState } from './use-interactive-session-init.js';
6
- import { usePermissionQueue } from './usePermissionQueue.js';
7
- import { useSlashRouting } from './useSlashRouting.js';
8
- import { generateSessionName } from '../session-naming.js';
9
-
10
- import type { TuiStateManager } from '../tui-state-manager.js';
11
- import type { IPermissionRequest } from '../types.js';
12
- import type {
13
- IAIProvider,
14
- TPermissionMode,
15
- IHistoryEntry,
16
- TSessionEndReason,
17
- } from '@robota-sdk/agent-core';
18
- import type { InteractiveSession, CommandRegistry } from '@robota-sdk/agent-framework';
19
- import type {
20
- IBackgroundTaskRunner,
21
- ICommandHostAdapters,
22
- ICommandModule,
23
- IInteractiveSession,
24
- IInteractiveSessionStore,
25
- IExecutionWorkspaceEvent,
26
- TSubagentRunnerFactory,
27
- IExecutionDetailPage,
28
- IExecutionWorkspaceSnapshot,
29
- IToolState,
30
- TShellExecFn,
31
- } from '@robota-sdk/agent-framework';
32
- import type { ITransportRegistryView } from '@robota-sdk/agent-interface-transport';
33
-
34
- const SESSION_INIT_POLL_MS = 200;
35
-
36
- export interface IInteractiveSessionProps {
37
- cwd: string;
38
- provider: IAIProvider;
39
- permissionMode?: TPermissionMode;
40
- maxTurns?: number;
41
- sessionStore?: IInteractiveSessionStore;
42
- resumeSessionId?: string;
43
- forkSession?: boolean;
44
- sessionName?: string;
45
- onAutoNamed?: (name: string) => void;
46
- backgroundTaskRunners?: IBackgroundTaskRunner[];
47
- subagentRunnerFactory?: TSubagentRunnerFactory;
48
- commandModules?: readonly ICommandModule[];
49
- commandHostAdapters?: ICommandHostAdapters;
50
- shellExec?: TShellExecFn;
51
- transportRegistry?: ITransportRegistryView<IInteractiveSession>;
52
- language?: string;
53
- reloadPluginCommandSource?: (registry: CommandRegistry) => void;
54
- agentName?: string;
55
- systemPrompt?: string;
56
- appendSystemPrompt?: string;
57
- allowedTools?: string[];
58
- deniedTools?: string[];
59
- }
60
-
61
- export interface IInteractiveSessionState {
62
- interactiveSession: InteractiveSession;
63
- registry: CommandRegistry;
64
- commandEffectQueue: ICommandEffectQueue;
65
- history: IHistoryEntry[];
66
- addEntry: (entry: IHistoryEntry) => void;
67
- streamingText: string;
68
- activeTools: IToolState[];
69
- isThinking: boolean;
70
- isAborting: boolean;
71
- isShuttingDown: boolean;
72
- pendingPrompt: string | null;
73
- executionWorkspaceSnapshot: IExecutionWorkspaceSnapshot | null;
74
- selectedExecutionEntryId?: string;
75
- permissionRequest: IPermissionRequest | null;
76
- contextState: { percentage: number; usedTokens: number; maxTokens: number };
77
- handleSubmit: (input: string) => Promise<void>;
78
- handleAbort: () => void;
79
- handleCancelQueue: () => void;
80
- handleShutdown: (reason?: TSessionEndReason) => Promise<void>;
81
- selectExecutionWorkspaceEntry: (entryId: string) => void;
82
- readExecutionWorkspaceDetail: (entryId: string) => Promise<IExecutionDetailPage>;
83
- }
84
-
85
- interface IHistoryReadableSession {
86
- getFullHistory(): IHistoryEntry[];
87
- }
88
-
89
- interface IHistorySyncManager {
90
- syncHistory(entries: IHistoryEntry[]): void;
91
- }
92
-
93
- export function applyCompactEventToManager(
94
- interactiveSession: IHistoryReadableSession,
95
- manager: IHistorySyncManager,
96
- ): void {
97
- manager.syncHistory(interactiveSession.getFullHistory());
98
- }
99
-
100
- export function applySkillActivationEventToManager(
101
- interactiveSession: IHistoryReadableSession,
102
- manager: IHistorySyncManager,
103
- ): void {
104
- manager.syncHistory(interactiveSession.getFullHistory());
105
- }
106
-
107
- function syncExecutionWorkspaceFromSession(
108
- interactiveSession: InteractiveSession,
109
- manager: TuiStateManager,
110
- ): void {
111
- try {
112
- manager.syncExecutionWorkspaceSnapshot(
113
- interactiveSession.getExecutionWorkspaceSnapshot({
114
- selectedEntryId: manager.selectedExecutionEntryId,
115
- }),
116
- );
117
- } catch {
118
- // allow-fallback: session may not be initialized yet; swallow until ready
119
- /* Session not initialized yet */
120
- }
121
- }
122
-
123
- export function useInteractiveSession(props: IInteractiveSessionProps): IInteractiveSessionState {
124
- const [, forceRender] = useState(0);
125
- const [isShuttingDown, setIsShuttingDown] = useState(false);
126
- const { permissionHandler, permissionRequest } = usePermissionQueue();
127
- const autoNameTriggeredRef = useRef(false);
128
-
129
- // Initialize once — useState lazy initializer runs exactly once per mount, safe for Concurrent Mode
130
- const [initState] = useState<IInitState>(() => initializeSession(props, permissionHandler));
131
- const { interactiveSession, registry, manager, commandEffectQueue } = initState;
132
-
133
- manager.onChange = () => forceRender((n) => n + 1);
134
-
135
- // Sync restored history immediately (session resume restores history in constructor)
136
- if (manager.history.length === 0) {
137
- const restored = interactiveSession.getFullHistory();
138
- if (restored.length > 0) {
139
- manager.syncHistory(restored);
140
- }
141
- }
142
-
143
- // Start transports (settings-driven: WS + web-monitor based on registry config).
144
- useEffect(() => {
145
- if (!props.transportRegistry) return;
146
- const reg = props.transportRegistry;
147
- reg.startAll(interactiveSession).catch(() => undefined);
148
- return () => {
149
- reg.stopAll().catch(() => undefined);
150
- };
151
- }, [interactiveSession, props.transportRegistry]);
152
-
153
- // Connect InteractiveSession events to TuiStateManager
154
- useEffect(() => {
155
- const onCompact = (): void => applyCompactEventToManager(interactiveSession, manager);
156
- const onSkillActivation = (): void =>
157
- applySkillActivationEventToManager(interactiveSession, manager);
158
-
159
- const onUserMessage = (content: string): void => {
160
- if (autoNameTriggeredRef.current) return;
161
- if (props.sessionName || interactiveSession.getName()) return;
162
- autoNameTriggeredRef.current = true;
163
- generateSessionName(props.provider, content)
164
- .then((name) => {
165
- interactiveSession.setName(name);
166
- props.onAutoNamed?.(name);
167
- })
168
- .catch(() => {
169
- autoNameTriggeredRef.current = false;
170
- });
171
- };
172
- const onExecutionWorkspaceEvent = (event: IExecutionWorkspaceEvent): void =>
173
- manager.syncExecutionWorkspaceSnapshot(event.snapshot);
174
-
175
- interactiveSession.on('user_message', onUserMessage);
176
- interactiveSession.on('text_delta', manager.onTextDelta);
177
- interactiveSession.on('tool_start', manager.onToolStart);
178
- interactiveSession.on('tool_end', manager.onToolEnd);
179
- interactiveSession.on('thinking', manager.onThinking);
180
- interactiveSession.on('complete', manager.onComplete);
181
- interactiveSession.on('interrupted', manager.onInterrupted);
182
- interactiveSession.on('error', manager.onError);
183
- interactiveSession.on('context_update', manager.onContextUpdate);
184
- interactiveSession.on('compact', onCompact);
185
- interactiveSession.on('skill_activation', onSkillActivation);
186
- interactiveSession.on('execution_workspace_event', onExecutionWorkspaceEvent);
187
-
188
- // Sync context state and restored history after async initialization
189
- const initCheck = setInterval(() => {
190
- try {
191
- const ctx = interactiveSession.getContextState();
192
- manager.setContextState({
193
- percentage: ctx.usedPercentage,
194
- usedTokens: ctx.usedTokens,
195
- maxTokens: ctx.maxTokens,
196
- });
197
- const restored = interactiveSession.getFullHistory();
198
- if (restored.length > 0) {
199
- manager.syncHistory(restored);
200
- }
201
- syncExecutionWorkspaceFromSession(interactiveSession, manager);
202
- clearInterval(initCheck);
203
- } catch {
204
- // allow-fallback: session initializes asynchronously; poll until ready
205
- /* Not yet initialized */
206
- }
207
- }, SESSION_INIT_POLL_MS);
208
-
209
- return () => {
210
- clearInterval(initCheck);
211
- interactiveSession.off('user_message', onUserMessage);
212
- interactiveSession.off('text_delta', manager.onTextDelta);
213
- interactiveSession.off('tool_start', manager.onToolStart);
214
- interactiveSession.off('tool_end', manager.onToolEnd);
215
- interactiveSession.off('thinking', manager.onThinking);
216
- interactiveSession.off('complete', manager.onComplete);
217
- interactiveSession.off('interrupted', manager.onInterrupted);
218
- interactiveSession.off('error', manager.onError);
219
- interactiveSession.off('context_update', manager.onContextUpdate);
220
- interactiveSession.off('compact', onCompact);
221
- interactiveSession.off('skill_activation', onSkillActivation);
222
- interactiveSession.off('execution_workspace_event', onExecutionWorkspaceEvent);
223
- };
224
- }, [interactiveSession, manager]);
225
-
226
- // Sync messages on every thinking state change:
227
- // - thinking=true: "You:" and "System: Invoking..." are already in messages
228
- // - thinking=false: complete/interrupted messages are in messages
229
- useEffect(() => {
230
- manager.syncHistory(interactiveSession.getFullHistory());
231
- syncExecutionWorkspaceFromSession(interactiveSession, manager);
232
- if (!manager.isThinking) {
233
- manager.setPendingPrompt(interactiveSession.getPendingPrompt());
234
- }
235
- }, [manager.isThinking, interactiveSession, manager]);
236
-
237
- const handleSubmit = useSlashRouting(
238
- interactiveSession,
239
- registry,
240
- manager,
241
- commandEffectQueue,
242
- props.reloadPluginCommandSource,
243
- );
244
-
245
- const handleAbort = useCallback(() => {
246
- manager.setAborting(true);
247
- interactiveSession.abort();
248
- }, [interactiveSession, manager]);
249
-
250
- const handleCancelQueue = useCallback(() => {
251
- interactiveSession.cancelQueue();
252
- manager.setPendingPrompt(null);
253
- }, [interactiveSession, manager]);
254
-
255
- const handleShutdown = useCallback(
256
- async (reason: TSessionEndReason = 'prompt_input_exit'): Promise<void> => {
257
- if (isShuttingDown) return;
258
- setIsShuttingDown(true);
259
- manager.addEntry(messageToHistoryEntry(createSystemMessage('Shutting down...')));
260
- await interactiveSession.shutdown({ reason, message: 'CLI shutdown' });
261
- },
262
- [interactiveSession, manager, isShuttingDown],
263
- );
264
-
265
- const selectExecutionWorkspaceEntry = useCallback(
266
- (entryId: string): void => manager.selectExecutionWorkspaceEntry(entryId),
267
- [manager],
268
- );
269
-
270
- const readExecutionWorkspaceDetail = useCallback(
271
- (entryId: string): Promise<IExecutionDetailPage> =>
272
- interactiveSession.readExecutionWorkspaceDetail(entryId),
273
- [interactiveSession],
274
- );
275
-
276
- return {
277
- interactiveSession,
278
- registry,
279
- commandEffectQueue,
280
- history: manager.history,
281
- addEntry: (entry: IHistoryEntry) => manager.addEntry(entry),
282
- streamingText: manager.streamingText,
283
- activeTools: manager.activeTools,
284
- isThinking: manager.isThinking,
285
- isAborting: manager.isAborting,
286
- isShuttingDown,
287
- pendingPrompt: manager.pendingPrompt,
288
- executionWorkspaceSnapshot: manager.executionWorkspaceSnapshot,
289
- selectedExecutionEntryId: manager.selectedExecutionEntryId,
290
- permissionRequest,
291
- contextState: manager.contextState,
292
- handleSubmit,
293
- handleAbort,
294
- handleCancelQueue,
295
- handleShutdown,
296
- selectExecutionWorkspaceEntry,
297
- readExecutionWorkspaceDetail,
298
- };
299
- }