@sma1lboy/rove 0.9.160 → 0.9.162

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 (116) hide show
  1. package/dist/cli/{chunk-39x1ztey.js → chunk-044s3zc5.js} +1 -1
  2. package/dist/cli/{chunk-zmvsqfad.js → chunk-07m61r5j.js} +5 -5
  3. package/dist/cli/{chunk-qy855bd5.js → chunk-0e04wrvh.js} +1 -1
  4. package/dist/cli/{chunk-wdhcrcre.js → chunk-0f6hf3bv.js} +1 -1
  5. package/dist/cli/chunk-13mw2v47.js +2 -0
  6. package/dist/cli/{chunk-kt1ppyje.js → chunk-1kz2syvp.js} +1 -1
  7. package/dist/cli/{chunk-e85ttr8r.js → chunk-1x5wrm14.js} +1 -1
  8. package/dist/cli/chunk-2840nxj7.js +3 -0
  9. package/dist/cli/{chunk-y7szq7xb.js → chunk-29xgqs7n.js} +2 -2
  10. package/dist/cli/{chunk-144wtkqt.js → chunk-2pezpj5y.js} +1 -1
  11. package/dist/cli/{chunk-qpd817w4.js → chunk-2ra4990w.js} +1 -1
  12. package/dist/cli/chunk-3bcx9dyb.js +2 -0
  13. package/dist/cli/{chunk-ttnpek4s.js → chunk-3pwsrf4f.js} +3 -3
  14. package/dist/cli/chunk-3ye9er38.js +2 -0
  15. package/dist/cli/chunk-4wswdvzj.js +2 -0
  16. package/dist/cli/chunk-5h3bhg45.js +3 -0
  17. package/dist/cli/{chunk-39fjx5fq.js → chunk-5ks91n60.js} +5 -4
  18. package/dist/cli/{chunk-vj2vdx3w.js → chunk-632q2pg7.js} +1 -1
  19. package/dist/cli/chunk-6b8zqcpq.js +2 -0
  20. package/dist/cli/{chunk-t0y9ty67.js → chunk-6ndddtg5.js} +1 -1
  21. package/dist/cli/{chunk-a2xndedd.js → chunk-6tvrvekq.js} +1 -1
  22. package/dist/cli/{chunk-1aqmmea7.js → chunk-6zvw1wp6.js} +1 -1
  23. package/dist/cli/{chunk-ztx1pfqv.js → chunk-7027e3rb.js} +1 -1
  24. package/dist/cli/chunk-7fedb3me.js +2 -0
  25. package/dist/cli/chunk-8djkntnp.js +3 -0
  26. package/dist/cli/{chunk-zvfgzpw6.js → chunk-8g4xwg93.js} +1 -1
  27. package/dist/cli/{chunk-z49thwax.js → chunk-8z7gz4pp.js} +1 -1
  28. package/dist/cli/{chunk-caqpt09m.js → chunk-932ymm0m.js} +1 -1
  29. package/dist/cli/{chunk-sfv15era.js → chunk-9esrwvqc.js} +1 -1
  30. package/dist/cli/chunk-abpzjm1b.js +2 -0
  31. package/dist/cli/chunk-ayhhgfsz.js +3 -0
  32. package/dist/cli/{chunk-6pt23vas.js → chunk-b3pxf5xd.js} +1 -1
  33. package/dist/cli/{chunk-gkmpfpmn.js → chunk-bpkg51p5.js} +2 -2
  34. package/dist/cli/chunk-br3yby3b.js +9 -0
  35. package/dist/cli/{chunk-qr3e1m00.js → chunk-cjfc4hj1.js} +4 -4
  36. package/dist/cli/{chunk-ds9qf1w1.js → chunk-dx4xyegr.js} +1 -1
  37. package/dist/cli/{chunk-84s62bex.js → chunk-eezk0g2q.js} +1 -1
  38. package/dist/cli/{chunk-pas1rh6m.js → chunk-epjh74m5.js} +1 -1
  39. package/dist/cli/{chunk-wdq5p44p.js → chunk-ewj2egvk.js} +2 -2
  40. package/dist/cli/{chunk-56wver0a.js → chunk-ewp7xthp.js} +1 -1
  41. package/dist/cli/{chunk-hj08heah.js → chunk-ffj7jp3k.js} +1 -1
  42. package/dist/cli/{chunk-ny31s73y.js → chunk-ftpbjbg9.js} +1 -1
  43. package/dist/cli/{chunk-cz7qj1p8.js → chunk-g8725q49.js} +1 -1
  44. package/dist/cli/{chunk-ynknvkrw.js → chunk-gvm4ss24.js} +1 -1
  45. package/dist/cli/chunk-gyc4fj15.js +3 -0
  46. package/dist/cli/{chunk-5w26jqne.js → chunk-h7zbtt85.js} +1 -1
  47. package/dist/cli/{chunk-aak5ttgt.js → chunk-hfh1wgtr.js} +1 -1
  48. package/dist/cli/{chunk-5v893waj.js → chunk-j75axe29.js} +1 -1
  49. package/dist/cli/{chunk-w68k2kdb.js → chunk-k1qe5qqa.js} +1 -1
  50. package/dist/cli/{chunk-y8yyk9hq.js → chunk-k43kf7qa.js} +1 -1
  51. package/dist/cli/{chunk-ksqdd9zh.js → chunk-kadvep6x.js} +1 -1
  52. package/dist/cli/chunk-mqs1qvc6.js +2 -0
  53. package/dist/cli/chunk-mv7ptt5w.js +3 -0
  54. package/dist/cli/{chunk-yrawhw9y.js → chunk-n1r2qzvw.js} +2 -2
  55. package/dist/cli/chunk-n55jst34.js +7 -0
  56. package/dist/cli/{chunk-cfg0s90c.js → chunk-n5c3k1dg.js} +1 -1
  57. package/dist/cli/{chunk-g48s150x.js → chunk-n7rhhjta.js} +1 -1
  58. package/dist/cli/{chunk-9wn8m2rt.js → chunk-nwe9c7x6.js} +1 -1
  59. package/dist/cli/{chunk-0hn7ctj6.js → chunk-p2s4hv7y.js} +1 -1
  60. package/dist/cli/{chunk-myewzjst.js → chunk-pktxzp2v.js} +1 -1
  61. package/dist/cli/chunk-ptj9ng0t.js +2 -0
  62. package/dist/cli/{chunk-zz788rt4.js → chunk-q0s362r7.js} +2 -2
  63. package/dist/cli/{chunk-9h4kbsk5.js → chunk-q6c30g0b.js} +1 -1
  64. package/dist/cli/{chunk-47nevjck.js → chunk-qrry2qvw.js} +2 -2
  65. package/dist/cli/{chunk-cs50jnwn.js → chunk-qs80x1cd.js} +1 -1
  66. package/dist/cli/{chunk-ccjmtajy.js → chunk-qwsn05zz.js} +1 -1
  67. package/dist/cli/chunk-r79ht9kg.js +2 -0
  68. package/dist/cli/{chunk-1cjd7h8p.js → chunk-rcyasw34.js} +1 -1
  69. package/dist/cli/chunk-rqwx8wqx.js +2 -0
  70. package/dist/cli/chunk-s6mcrm5g.js +2 -0
  71. package/dist/cli/{chunk-wbt845s6.js → chunk-sx8fw2qd.js} +1 -1
  72. package/dist/cli/chunk-t2v3ad8y.js +3 -0
  73. package/dist/cli/{chunk-1ckc04zj.js → chunk-tj1tjdvd.js} +1 -1
  74. package/dist/cli/{chunk-t7xhb2jx.js → chunk-tqat428f.js} +1 -1
  75. package/dist/cli/{chunk-ntt7gy5a.js → chunk-ttd78mrr.js} +1 -1
  76. package/dist/cli/chunk-wc0g8kzq.js +2 -0
  77. package/dist/cli/{chunk-8vec42df.js → chunk-ww0rwg80.js} +1 -1
  78. package/dist/cli/chunk-wzdrq5es.js +2 -0
  79. package/dist/cli/{chunk-0bayctej.js → chunk-x5g5rjtn.js} +3 -3
  80. package/dist/cli/{chunk-t27t2x9b.js → chunk-xcgb5q15.js} +1 -1
  81. package/dist/cli/{chunk-j91yq51m.js → chunk-xwtqz55p.js} +3 -3
  82. package/dist/cli/{chunk-x6hevxs5.js → chunk-y9xr3c66.js} +1 -1
  83. package/dist/cli/chunk-ycdeav89.js +2 -0
  84. package/dist/cli/chunk-ykrvv6bc.js +4 -0
  85. package/dist/cli/chunk-ytkx5h87.js +2 -0
  86. package/dist/cli/{chunk-s59cymtd.js → chunk-zf45ap00.js} +1 -1
  87. package/dist/cli/index.js +7 -7
  88. package/dist/cli/kobe.js +1 -1
  89. package/dist/cli/pty-host-node.mjs +17 -18
  90. package/dist/cli/rove.js +1 -1
  91. package/package.json +1 -1
  92. package/dist/cli/chunk-0am6gj8j.js +0 -9
  93. package/dist/cli/chunk-0fhab4tq.js +0 -2
  94. package/dist/cli/chunk-1y37w7zq.js +0 -4
  95. package/dist/cli/chunk-22yhtgcy.js +0 -7
  96. package/dist/cli/chunk-4502n1bk.js +0 -3
  97. package/dist/cli/chunk-4jf0yq4v.js +0 -2
  98. package/dist/cli/chunk-6b474j5g.js +0 -2
  99. package/dist/cli/chunk-7x88845e.js +0 -2
  100. package/dist/cli/chunk-91f68r6e.js +0 -2
  101. package/dist/cli/chunk-959a71qj.js +0 -2
  102. package/dist/cli/chunk-a3a9gdc4.js +0 -3
  103. package/dist/cli/chunk-azsmk821.js +0 -2
  104. package/dist/cli/chunk-cdxme5y4.js +0 -2
  105. package/dist/cli/chunk-cfghdnev.js +0 -2
  106. package/dist/cli/chunk-dmdpsw2y.js +0 -2
  107. package/dist/cli/chunk-dzd1wy5a.js +0 -2
  108. package/dist/cli/chunk-kw0nnzdp.js +0 -2
  109. package/dist/cli/chunk-mhs6yywx.js +0 -2
  110. package/dist/cli/chunk-mp8v5gn8.js +0 -2
  111. package/dist/cli/chunk-mqqnk8w7.js +0 -3
  112. package/dist/cli/chunk-nm0pq5r6.js +0 -3
  113. package/dist/cli/chunk-rc668r26.js +0 -2
  114. package/dist/cli/chunk-w06vgba4.js +0 -3
  115. package/dist/cli/chunk-yzmvmt89.js +0 -2
  116. package/dist/cli/chunk-zftxrnwh.js +0 -3
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{KEY_HINTS_ENABLED_KEY,PANE_HINT_USED_KEYS,grammarHelpSections,guideCategory,keyHintsEnabled,keyHintsToggleOn,legendCap,paneHintTokens,paneHintVisible,scopeCategory,statusHintTokens,toggleKeyHints}from"./chunk-84s62bex.js";import{readOutdatedCache}from"./chunk-n4nntq73.js";import{listPaneLaunches}from"./chunk-9xt05etk.js";import{deriveTitleFromSessionId,startTaskSessionWithPromptAdapter}from"./chunk-z49thwax.js";import{canonPath,checkResolutionNotify}from"./chunk-vj2vdx3w.js";import{readLastActiveTaskId}from"./chunk-t7xhb2jx.js";import{formatBytes}from"./chunk-my20q579.js";import{detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-ny31s73y.js";import{ISSUE_STATUSES,isValidCron,nextCronAfter,tightenPluginPermissions}from"./chunk-39x1ztey.js";import"./chunk-41ahvk51.js";import{DEFAULT_EDITOR_KIND,EDITOR_CUSTOM_KEY,EDITOR_KINDS,EDITOR_KIND_KEY,normalizeEditorKind,resolveEditorLaunch}from"./chunk-aak5ttgt.js";import{embeddedTerminalEnv}from"./chunk-ef39ym8f.js";import{approxCellWidth,approxCharCells,charWidth,displayWidth,padEndCells}from"./chunk-dvcb6mk4.js";import{UpdatePage,openWithSystemViewer,resolveRowSelectionChrome,spawnDetached}from"./chunk-8vec42df.js";import{$Fragment,$jsx,$jsxs,DEFAULT_PREFIX_CONFIGURATION,DIRECT_GUIDE_PREFIX_ACTION_ID,FIXED_BINDING_IDS,KobeKeymap,PREFIX_GUIDE_DELAY_MS,PREFIX_HUD_TTL_MS,RemoteOrchestrator,armPrefixFromCurrentStack,attentionEdges,attentionKindFor,bindByIds,bootPaneHost,chipAttentionKind,currentBindingReachability,currentPrefixConfiguration,defaultChordsOf,findBinding,formatChord,imeAnchorController,invokeArmedPrefixActionFromCurrentStack,isKittyModifierKeyEvent,isNarrowWidth,keymapVersion,modalActive,narrowSurface,pageCloseBindings,pluginKeybindings,prefixAction,prefixHudClock,prefixHudState,reloadUserKeybindings,require_react_production,shortcutCaption,showDialog,subscribeKeymapVersion,taskJumpDigit,useAccessor,useBindingStackVersion,useBindings,useDialog,useDialogPaddingX,useFocus,useKV,useLatest,useNotifications,useOptionalDialog,useOptionalFocus,useOptionalKV,useOptionalNotifications,usePaste,useRenderer,useT,useTerminalDimensions,useTheme,userKeybindingsReport}from"./chunk-qr3e1m00.js";import"./chunk-764bsyb0.js";import{getGlobalDefaultVendor,resolvePreferredVendor,setGlobalDefaultVendor,setRepoLastActiveVendor}from"./chunk-caqpt09m.js";import{parseNumstatRows,parsePorcelain,pickPushedChanges,sameWorktreeChanges}from"./chunk-xqw5d5rv.js";import{parsePorcelainRows,unquoteGitPath}from"./chunk-h4n8ffqy.js";import{READ_ONLY_GIT_ENV,readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{reloadPluginEngines}from"./chunk-ntt7gy5a.js";import{submitFeedback}from"./chunk-myewzjst.js";import{DIRTY_WORKTREE_CODE,TASK_DELETING_CODE,TaskDeletingError}from"./chunk-r05r01nv.js";import{PROJECT_SIBLING_BASE,WORKTREE_BASE_CUSTOM_KEY,worktreeBaseKindOf}from"./chunk-6pt23vas.js";import{currentPluginPlatform,loadPluginRegistry,parsePluginManifest,pluginConfigDir,pluginLogPath,pluginManifestPath,qualifiedActionId,readPluginManifest,savePluginRegistry,supportsPlatform}from"./chunk-38272eqv.js";import{PROJECT_DIR_TOKEN,WORKTREE_BASE_KEY,hasProjectDirToken,normalizeWorktreeBase}from"./chunk-5f80ggc3.js";import{ulid}from"./chunk-qkehg2c1.js";import{matchPathGlob}from"./chunk-kg11c1py.js";import{CURRENT_VERSION}from"./chunk-e85ttr8r.js";import{tildify}from"./chunk-msr1xtay.js";import{addTab,closeActiveTab,closeTab,collapseSplit,cycleLeaf,cycleTab,engineTabSpawnFor,expandHome,filterSubdirs,findEditorTab,forgetTaskTabsSnapshot,hasEngineLeaf,initialShellTabs,initialSplit,initialTabs,isTabSplit,joinDrill,joinPicked,leaves,listSubdirs,moveTab,openCommandTab,openContentTab,openEditorTab,pathLeaf,recycleTabs,rehydrateTabs,removeLeaf,renameActiveTab,renameLeaf,reopenTabs,selectTab,setTabAutoTitle,setTabEngineCommand,setTabForkFrom,setTabInitialPrompt,setTabLastTitle,setTabLiveVendor,setTabSessionId,setTabSpawned,setTabSplit,setTabTitle,shellIdentityInput,splitActive,splitLeafNames,splitLeafPtyKey,splitPathForDirSuggest,stripTrailingSlash,sweepOrphanTabsSnapshots,tabCwdFor,tabExitAction,tabPtyKey,tabPtyKeyFor,tabTitle,tabTitleStable,terminalTabsKey,visibleNativeStatus}from"./chunk-9h4kbsk5.js";import{AUTO_STATUS_KEY,DELIVERY_GUARDS,DISPATCHER_KEY,Ke,deliveryGuardEnvOverride,deliveryGuardPreference,hostedTaskKeys,killHostedSessions,listHostedSessions,nextDeliveryGuard,openHostedSessionHost,pastePromptWhenEngineUp,require_xterm_headless,setDeliveryGuardPreference}from"./chunk-pas1rh6m.js";import{execHostForWorktreePath,remoteKeyForRepo}from"./chunk-ds9qf1w1.js";import"./chunk-bkba9c4n.js";import"./chunk-g2advs8t.js";import{ensurePtyHostReachable}from"./chunk-wdhcrcre.js";import{ENGINE_PROTOCOLS,engineCanFork,engineLaunchArgv,engineProtocolKey,getEngineProtocol,pickUnclaimedSessionId,protocolEntry,withPinnedSessionId}from"./chunk-y8yyk9hq.js";import{DEFAULT_TERMINAL_COLORS,formatDefaultColorReply,parseTerminalDefaultColors}from"./chunk-7q67dz4c.js";import"./chunk-1cjd7h8p.js";import{resolveLoginShell}from"./chunk-b99tf0jr.js";import{readFirstNonEmptyRepoFile}from"./chunk-t27t2x9b.js";import"./chunk-hape5vwj.js";import{defaultEngineCommand,engineCommandKey,engineDisplayName,engineNameKey,humanizeSlug,interactiveEngineCommand,kobeApiInvocation}from"./chunk-x6hevxs5.js";import{FOCUS_ACCENT_SLOTS,LOCALE_KEY}from"./chunk-ynknvkrw.js";import{currentLang,intlLocale,setLocaleLang,t,tKeys}from"./chunk-9wn8m2rt.js";import{LOCALES}from"./chunk-w06vgba4.js";import{createStateCell}from"./chunk-sdyzxayr.js";import"./chunk-zqfbyq0a.js";import"./chunk-jvxh93nz.js";import{connectOrStartDaemon}from"./chunk-4502n1bk.js";import"./chunk-nm0pq5r6.js";import"./chunk-mqqnk8w7.js";import{KobeDaemonClient}from"./chunk-0wnfq5sx.js";import{attentionInboxItemKey,automationRunNeedsAttention}from"./chunk-7j5372wb.js";import"./chunk-mnqxgvyb.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-ztx1pfqv.js";import{engineEntry,engineSessionIdFromTitle,engineTitleTurnHint,getCapabilities,stripEngineStatusPrefix}from"./chunk-zmvsqfad.js";import{availableEngineIds,installedEngineIds}from"./chunk-sfv15era.js";import"./chunk-w7zv47mp.js";import{maybeStartScheduledRun,spawnCapture}from"./chunk-gwcneg6c.js";import{roveCliInvocation}from"./chunk-a2xndedd.js";import"./chunk-7jkf3tvr.js";import"./chunk-2fypr41w.js";import{addSavedRepo,getSavedRepos,isGitRepo,isRemoteRepoKey,resolveMainRepoRoot}from"./chunk-kt1ppyje.js";import{loadStateFile}from"./chunk-5v893waj.js";import"./chunk-w68k2kdb.js";import{DEFAULT_TASK_VENDOR,TASK_STATUSES}from"./chunk-xy8be792.js";import"./chunk-a3a9gdc4.js";import{errorMessage,userFacingErrorMessage}from"./chunk-2brn8e1y.js";import"./chunk-3wj69b0a.js";import{isDev,promptAttachmentsDir,roveStateDir}from"./chunk-ch9b1d5y.js";import{ALL_VENDORS,isBuiltinVendor,nextVendorWithin,prevVendorWithin}from"./chunk-bq3fyc0p.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import{ROVE_PRODUCT_NAME}from"./chunk-g56kvet6.js";import{logClientError}from"./chunk-k2ckx8zw.js";import"./chunk-pw6yfj10.js";import{defaultDaemonSocketPath}from"./chunk-mcdv19rs.js";import{readRoveEnv}from"./chunk-r3k9rbwm.js";import{__require,__toESM}from"./chunk-wqfp8d9w.js";var import_react115=__toESM(require_react_production(),1);function truncateEnd(s,max){if(max<=0)return"";let points=[...s];if(points.length<=max)return s;return`${points.slice(0,Math.max(0,max-1)).join("")}\u2026`}function truncateEndCells(s,maxCells,cellsOf){if(maxCells<=0)return"";let total=0;for(let ch of s)total+=cellsOf(ch.codePointAt(0)??0);if(total<=maxCells)return s;let used=0,out="";for(let ch of s){let w=cellsOf(ch.codePointAt(0)??0);if(used+w>maxCells-1)break;used+=w,out+=ch}return`${out}\u2026`}function truncateStart(s,max){if(max<=0)return"";let points=[...s];if(points.length<=max)return s;return`\u2026${points.slice(points.length-Math.max(0,max-1)).join("")}`}function truncateStartCells(s,maxCells,cellsOf){if(maxCells<=0)return"";let points=[...s],total=0;for(let ch of points)total+=cellsOf(ch.codePointAt(0)??0);if(total<=maxCells)return s;let used=0,out="";for(let i=points.length-1;i>=0;i--){let ch=points[i],w=cellsOf(ch.codePointAt(0)??0);if(used+w>maxCells-1)break;used+=w,out=ch+out}return`\u2026${out}`}var SIDEBAR_WIDTH=24;function sidebarWidthFor(terminalWidth){return Math.max(SIDEBAR_WIDTH,Math.min(40,Math.floor(terminalWidth/6)))}var MAIN_BRANCH_POLL_MS=2000;function sidebarEmptyStateKey(opts){if(opts.searching)return"tasks.empty.noMatchSearch";if(opts.projectFilter)return"tasks.empty.noActiveProject";return"tasks.empty.noActive"}var BRANCH_LABEL_MAX=16;function truncateBranchLabel(branch,max=BRANCH_LABEL_MAX){return truncateEnd(branch,max)}function toneColor(theme,tone){switch(tone){case"success":return theme.success;case"warning":return theme.warning;case"primary":return theme.primary;case"error":return theme.error;default:return theme.textMuted}}function searchQueryKeystroke(query,evt){if(evt.defaultPrevented)return null;if(evt.ctrl||evt.meta||evt.option)return null;if(evt.name==="backspace")return query.slice(0,-1);let seq=evt.sequence;if(!seq||seq.length!==1)return null;let code=seq.charCodeAt(0);if(code<32||code===127)return null;return query+seq}var m=0,p=0,g=0,b=0,I;((r)=>{function u(t2,a,s,i){return i!==void 0?`#${B(t2)}${B(a)}${B(s)}${B(i)}`:`#${B(t2)}${B(a)}${B(s)}`}r.toCss=u;function o(t2,a,s,i=255){return(t2<<24|a<<16|s<<8|i)>>>0}r.toRgba=o;function e(t2,a,s,i){return{css:r.toCss(t2,a,s,i),rgba:r.toRgba(t2,a,s,i)}}r.toColor=e})(I||={});var $;((i)=>{function u(n,l){if(b=(l.rgba&255)/255,b===1)return{css:l.css,rgba:l.rgba};let f=l.rgba>>24&255,d=l.rgba>>16&255,c=l.rgba>>8&255,C=n.rgba>>24&255,h=n.rgba>>16&255,x=n.rgba>>8&255;m=C+Math.round((f-C)*b),p=h+Math.round((d-h)*b),g=x+Math.round((c-x)*b);let R=I.toCss(m,p,g),L=I.toRgba(m,p,g);return{css:R,rgba:L}}i.blend=u;function o(n){return(n.rgba&255)===255}i.isOpaque=o;function e(n,l,f){let d=y.ensureContrastRatio(n.rgba,l.rgba,f);if(d)return I.toColor(d>>24&255,d>>16&255,d>>8&255)}i.ensureContrastRatio=e;function r(n){let l=(n.rgba|255)>>>0;return[m,p,g]=y.toChannels(l),{css:I.toCss(m,p,g),rgba:l}}i.opaque=r;function t2(n,l){return b=Math.round(l*255),[m,p,g]=y.toChannels(n.rgba),{css:I.toCss(m,p,g,b),rgba:I.toRgba(m,p,g,b)}}i.opacity=t2;function a(n,l){return b=n.rgba&255,t2(n,b*l/255)}i.multiplyOpacity=a;function s(n){return[n.rgba>>24&255,n.rgba>>16&255,n.rgba>>8&255]}i.toColorRGB=s})($||={});var _;((r)=>{let u,o;try{let t2=document.createElement("canvas");t2.width=1,t2.height=1;let a=t2.getContext("2d",{willReadFrequently:!0});a&&(u=a,u.globalCompositeOperation="copy",o=u.createLinearGradient(0,0,1,1))}catch{}function e(t2){if(t2.match(/#[\da-f]{3,8}/i))switch(t2.length){case 4:return m=parseInt(t2.slice(1,2).repeat(2),16),p=parseInt(t2.slice(2,3).repeat(2),16),g=parseInt(t2.slice(3,4).repeat(2),16),I.toColor(m,p,g);case 5:return m=parseInt(t2.slice(1,2).repeat(2),16),p=parseInt(t2.slice(2,3).repeat(2),16),g=parseInt(t2.slice(3,4).repeat(2),16),b=parseInt(t2.slice(4,5).repeat(2),16),I.toColor(m,p,g,b);case 7:return{css:t2,rgba:(parseInt(t2.slice(1),16)<<8|255)>>>0};case 9:return{css:t2,rgba:parseInt(t2.slice(1),16)>>>0}}let a=t2.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(a)return m=parseInt(a[1]),p=parseInt(a[2]),g=parseInt(a[3]),b=Math.round((a[5]===void 0?1:parseFloat(a[5]))*255),I.toColor(m,p,g,b);if(!u||!o)throw Error("css.toColor: Unsupported css format");if(u.fillStyle=o,u.fillStyle=t2,typeof u.fillStyle!="string")throw Error("css.toColor: Unsupported css format");if(u.fillRect(0,0,1,1),[m,p,g,b]=u.getImageData(0,0,1,1).data,b!==255)throw Error("css.toColor: Unsupported css format");return{rgba:I.toRgba(m,p,g,b),css:t2}}r.toColor=e})(_||={});var v;((e)=>{function u(r){return o(r>>16&255,r>>8&255,r&255)}e.relativeLuminance=u;function o(r,t2,a){let s=r/255,i=t2/255,n=a/255,l=s<=0.03928?s/12.92:Math.pow((s+0.055)/1.055,2.4),f=i<=0.03928?i/12.92:Math.pow((i+0.055)/1.055,2.4),d=n<=0.03928?n/12.92:Math.pow((n+0.055)/1.055,2.4);return l*0.2126+f*0.7152+d*0.0722}e.relativeLuminance2=o})(v||={});var y;((a)=>{function u(s,i){if(b=(i&255)/255,b===1)return i;let n=i>>24&255,l=i>>16&255,f=i>>8&255,d=s>>24&255,c=s>>16&255,C=s>>8&255;return m=d+Math.round((n-d)*b),p=c+Math.round((l-c)*b),g=C+Math.round((f-C)*b),I.toRgba(m,p,g)}a.blend=u;function o(s,i,n){let l=v.relativeLuminance(s>>8),f=v.relativeLuminance(i>>8);if(F(l,f)<n){if(f<l){let h=e(s,i,n),x=F(l,v.relativeLuminance(h>>8));if(x<n){let R=r(s,i,n),L=F(l,v.relativeLuminance(R>>8));return x>L?h:R}return h}let c=r(s,i,n),C=F(l,v.relativeLuminance(c>>8));if(C<n){let h=e(s,i,n),x=F(l,v.relativeLuminance(h>>8));return C>x?c:h}return c}}a.ensureContrastRatio=o;function e(s,i,n){let l=s>>24&255,f=s>>16&255,d=s>>8&255,c=i>>24&255,C=i>>16&255,h=i>>8&255,x=F(v.relativeLuminance2(c,C,h),v.relativeLuminance2(l,f,d));for(;x<n&&(c>0||C>0||h>0);)c-=Math.max(0,Math.ceil(c*0.1)),C-=Math.max(0,Math.ceil(C*0.1)),h-=Math.max(0,Math.ceil(h*0.1)),x=F(v.relativeLuminance2(c,C,h),v.relativeLuminance2(l,f,d));return(c<<24|C<<16|h<<8|255)>>>0}a.reduceLuminance=e;function r(s,i,n){let l=s>>24&255,f=s>>16&255,d=s>>8&255,c=i>>24&255,C=i>>16&255,h=i>>8&255,x=F(v.relativeLuminance2(c,C,h),v.relativeLuminance2(l,f,d));for(;x<n&&(c<255||C<255||h<255);)c=Math.min(255,c+Math.ceil((255-c)*0.1)),C=Math.min(255,C+Math.ceil((255-C)*0.1)),h=Math.min(255,h+Math.ceil((255-h)*0.1)),x=F(v.relativeLuminance2(c,C,h),v.relativeLuminance2(l,f,d));return(c<<24|C<<16|h<<8|255)>>>0}a.increaseLuminance=r;function t2(s){return[s>>24&255,s>>16&255,s>>8&255,s&255]}a.toChannels=t2})(y||={});function B(u){let o=u.toString(16);return o.length<2?"0"+o:o}function F(u,o){return u<o?(o+0.05)/(u+0.05):(u+0.05)/(o+0.05)}var E=Object.freeze((()=>{let u=[_.toColor("#2e3436"),_.toColor("#cc0000"),_.toColor("#4e9a06"),_.toColor("#c4a000"),_.toColor("#3465a4"),_.toColor("#75507b"),_.toColor("#06989a"),_.toColor("#d3d7cf"),_.toColor("#555753"),_.toColor("#ef2929"),_.toColor("#8ae234"),_.toColor("#fce94f"),_.toColor("#729fcf"),_.toColor("#ad7fa8"),_.toColor("#34e2e2"),_.toColor("#eeeeec")],o=[0,95,135,175,215,255];for(let e=0;e<216;e++){let r=o[e/36%6|0],t2=o[e/6%6|0],a=o[e%6];u.push({css:I.toCss(r,t2,a),rgba:I.toRgba(r,t2,a)})}for(let e=0;e<24;e++){let r=8+e*10;u.push({css:I.toCss(r,r,r),rgba:I.toRgba(r,r,r)})}return u})());function A(u,o,e){return Math.max(o,Math.min(u,e))}function O(u){switch(u){case"&":return"&amp;";case"<":return"&lt;"}return u}var S=class{constructor(o){this._buffer=o}serialize(o,e){let r=this._buffer.getNullCell(),t2=this._buffer.getNullCell(),a=r,s=o.start.y,i=o.end.y,n=o.start.x,l=o.end.x;this._beforeSerialize(i-s,s,i);for(let f=s;f<=i;f++){let d=this._buffer.getLine(f);if(d){let c=f===o.start.y?n:0,C=f===o.end.y?l:d.length;for(let h=c;h<C;h++){let x=d.getCell(h,a===r?t2:r);if(!x){console.warn(`Can't get cell at row=${f}, col=${h}`);continue}this._nextCell(x,a,f,h),a=x}}this._rowEnd(f,f===i)}return this._afterSerialize(),this._serializeString(e)}_nextCell(o,e,r,t2){}_rowEnd(o,e){}_beforeSerialize(o,e,r){}_afterSerialize(){}_serializeString(o){return""}};function T(u,o){return u.getFgColorMode()===o.getFgColorMode()&&u.getFgColor()===o.getFgColor()}function w(u,o){return u.getBgColorMode()===o.getBgColorMode()&&u.getBgColor()===o.getBgColor()}function z(u,o){return u.isInverse()===o.isInverse()&&u.isBold()===o.isBold()&&u.isUnderline()===o.isUnderline()&&u.isOverline()===o.isOverline()&&u.isBlink()===o.isBlink()&&u.isInvisible()===o.isInvisible()&&u.isItalic()===o.isItalic()&&u.isDim()===o.isDim()&&u.isStrikethrough()===o.isStrikethrough()}var k=class extends S{constructor(e,r){super(e);this._terminal=r,this._rowIndex=0,this._allRows=[],this._allRowSeparators=[],this._currentRow="",this._nullCellCount=0,this._cursorStyle=this._buffer.getNullCell(),this._cursorStyleRow=0,this._cursorStyleCol=0,this._backgroundCell=this._buffer.getNullCell(),this._firstRow=0,this._lastCursorRow=0,this._lastCursorCol=0,this._lastContentCursorRow=0,this._lastContentCursorCol=0,this._thisRowLastChar=this._buffer.getNullCell(),this._thisRowLastSecondChar=this._buffer.getNullCell(),this._nextRowFirstChar=this._buffer.getNullCell()}_beforeSerialize(e,r,t2){this._allRows=Array(e),this._lastContentCursorRow=r,this._lastCursorRow=r,this._firstRow=r}_rowEnd(e,r){this._nullCellCount>0&&!w(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let t2="";if(!r){e-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);let a=this._buffer.getLine(e),s=this._buffer.getLine(e+1);if(!s.isWrapped)t2=`\r
2
+ import{KEY_HINTS_ENABLED_KEY,PANE_HINT_USED_KEYS,grammarHelpSections,guideCategory,keyHintsEnabled,keyHintsToggleOn,legendCap,paneHintTokens,paneHintVisible,scopeCategory,statusHintTokens,toggleKeyHints}from"./chunk-eezk0g2q.js";import{readOutdatedCache}from"./chunk-n4nntq73.js";import{listPaneLaunches}from"./chunk-9xt05etk.js";import{deriveTitleFromSessionId,startTaskSessionWithPromptAdapter}from"./chunk-8z7gz4pp.js";import{canonPath,checkResolutionNotify}from"./chunk-632q2pg7.js";import{readLastActiveTaskId}from"./chunk-tqat428f.js";import{formatBytes}from"./chunk-my20q579.js";import{detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-ftpbjbg9.js";import{ISSUE_STATUSES,isValidCron,nextCronAfter,tightenPluginPermissions}from"./chunk-044s3zc5.js";import"./chunk-41ahvk51.js";import{DEFAULT_EDITOR_KIND,EDITOR_CUSTOM_KEY,EDITOR_KINDS,EDITOR_KIND_KEY,normalizeEditorKind,resolveEditorLaunch}from"./chunk-hfh1wgtr.js";import{embeddedTerminalEnv}from"./chunk-ef39ym8f.js";import{approxCellWidth,approxCharCells,charWidth,displayWidth,padEndCells}from"./chunk-dvcb6mk4.js";import{UpdatePage,openWithSystemViewer,resolveRowSelectionChrome,spawnDetached}from"./chunk-ww0rwg80.js";import{$Fragment,$jsx,$jsxs,DEFAULT_PREFIX_CONFIGURATION,DIRECT_GUIDE_PREFIX_ACTION_ID,FIXED_BINDING_IDS,KobeKeymap,PREFIX_GUIDE_DELAY_MS,PREFIX_HUD_TTL_MS,RemoteOrchestrator,armPrefixFromCurrentStack,attentionEdges,attentionKindFor,bindByIds,bootPaneHost,chipAttentionKind,currentBindingReachability,currentPrefixConfiguration,defaultChordsOf,findBinding,formatChord,imeAnchorController,invokeArmedPrefixActionFromCurrentStack,isKittyModifierKeyEvent,isNarrowWidth,keymapVersion,modalActive,narrowSurface,pageCloseBindings,pluginKeybindings,prefixAction,prefixHudClock,prefixHudState,redrawScreen,reloadUserKeybindings,require_react_production,shortcutCaption,showDialog,subscribeKeymapVersion,taskJumpDigit,useAccessor,useBindingStackVersion,useBindings,useDialog,useDialogPaddingX,useFocus,useKV,useLatest,useNotifications,useOptionalDialog,useOptionalFocus,useOptionalKV,useOptionalNotifications,usePaste,useRenderer,useT,useTerminalDimensions,useTheme,userKeybindingsReport}from"./chunk-cjfc4hj1.js";import"./chunk-764bsyb0.js";import{getGlobalDefaultVendor,resolvePreferredVendor,setGlobalDefaultVendor,setRepoLastActiveVendor}from"./chunk-932ymm0m.js";import{parseNumstatRows,parsePorcelain,pickPushedChanges,sameWorktreeChanges}from"./chunk-xqw5d5rv.js";import{parsePorcelainRows,unquoteGitPath}from"./chunk-h4n8ffqy.js";import{READ_ONLY_GIT_ENV,readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{reloadPluginEngines}from"./chunk-ttd78mrr.js";import{submitFeedback}from"./chunk-pktxzp2v.js";import{DIRTY_WORKTREE_CODE,TASK_DELETING_CODE,TaskDeletingError}from"./chunk-r05r01nv.js";import{PROJECT_SIBLING_BASE,WORKTREE_BASE_CUSTOM_KEY,worktreeBaseKindOf}from"./chunk-b3pxf5xd.js";import{currentPluginPlatform,loadPluginRegistry,parsePluginManifest,pluginConfigDir,pluginLogPath,pluginManifestPath,qualifiedActionId,readPluginManifest,savePluginRegistry,supportsPlatform}from"./chunk-38272eqv.js";import{PROJECT_DIR_TOKEN,WORKTREE_BASE_KEY,hasProjectDirToken,normalizeWorktreeBase}from"./chunk-5f80ggc3.js";import{ulid}from"./chunk-qkehg2c1.js";import{matchPathGlob}from"./chunk-kg11c1py.js";import{CURRENT_VERSION}from"./chunk-1x5wrm14.js";import{tildify}from"./chunk-msr1xtay.js";import{addTab,closeActiveTab,closeTab,collapseSplit,cycleLeaf,cycleTab,engineTabSpawnFor,expandHome,filterSubdirs,findEditorTab,forgetTaskTabsSnapshot,hasEngineLeaf,initialShellTabs,initialSplit,initialTabs,isTabSplit,joinDrill,joinPicked,leaves,listSubdirs,moveTab,openCommandTab,openContentTab,openEditorTab,pathLeaf,recycleTabs,rehydrateTabs,removeLeaf,renameActiveTab,renameLeaf,reopenTabs,selectTab,setTabAutoTitle,setTabEngineCommand,setTabForkFrom,setTabInitialPrompt,setTabLastTitle,setTabLiveVendor,setTabSessionId,setTabSpawned,setTabSplit,setTabTitle,shellIdentityInput,splitActive,splitLeafNames,splitLeafPtyKey,splitPathForDirSuggest,stripTrailingSlash,sweepOrphanTabsSnapshots,tabCwdFor,tabExitAction,tabPtyKey,tabPtyKeyFor,tabTitle,tabTitleStable,terminalTabsKey,visibleNativeStatus}from"./chunk-q6c30g0b.js";import{AUTO_STATUS_KEY,DELIVERY_GUARDS,DISPATCHER_KEY,Ke,deliveryGuardEnvOverride,deliveryGuardPreference,hostedTaskKeys,killHostedSessions,listHostedSessions,nextDeliveryGuard,openHostedSessionHost,pastePromptWhenEngineUp,require_xterm_headless,setDeliveryGuardPreference}from"./chunk-epjh74m5.js";import{execHostForWorktreePath,remoteKeyForRepo}from"./chunk-dx4xyegr.js";import"./chunk-bkba9c4n.js";import"./chunk-g2advs8t.js";import{ensurePtyHostReachable}from"./chunk-0f6hf3bv.js";import{ENGINE_PROTOCOLS,engineCanFork,engineLaunchArgv,engineProtocolKey,getEngineProtocol,pickUnclaimedSessionId,protocolEntry,withPinnedSessionId}from"./chunk-k43kf7qa.js";import"./chunk-rcyasw34.js";import{resolveLoginShell}from"./chunk-b99tf0jr.js";import{DEFAULT_TERMINAL_COLORS,formatDefaultColorReply,parseTerminalDefaultColors}from"./chunk-7q67dz4c.js";import{readFirstNonEmptyRepoFile}from"./chunk-xcgb5q15.js";import"./chunk-hape5vwj.js";import{defaultEngineCommand,engineCommandKey,engineDisplayName,engineNameKey,humanizeSlug,interactiveEngineCommand,kobeApiInvocation}from"./chunk-y9xr3c66.js";import{FOCUS_ACCENT_SLOTS,LOCALE_KEY}from"./chunk-gvm4ss24.js";import{currentLang,intlLocale,setLocaleLang,t,tKeys}from"./chunk-nwe9c7x6.js";import{LOCALES}from"./chunk-5h3bhg45.js";import{createStateCell}from"./chunk-sdyzxayr.js";import"./chunk-zqfbyq0a.js";import"./chunk-jvxh93nz.js";import{connectOrStartDaemon}from"./chunk-2840nxj7.js";import"./chunk-gyc4fj15.js";import{KobeDaemonClient}from"./chunk-0wnfq5sx.js";import{attentionInboxItemKey,automationRunNeedsAttention}from"./chunk-7j5372wb.js";import"./chunk-mnqxgvyb.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-7027e3rb.js";import{engineEntry,engineSessionIdFromTitle,engineTitleTurnHint,getCapabilities,stripEngineStatusPrefix}from"./chunk-07m61r5j.js";import{availableEngineIds,installedEngineIds}from"./chunk-9esrwvqc.js";import"./chunk-w7zv47mp.js";import{maybeStartScheduledRun,spawnCapture}from"./chunk-gwcneg6c.js";import{roveCliInvocation}from"./chunk-6tvrvekq.js";import"./chunk-7jkf3tvr.js";import"./chunk-2fypr41w.js";import{addSavedRepo,getSavedRepos,isGitRepo,isRemoteRepoKey,resolveMainRepoRoot}from"./chunk-1kz2syvp.js";import{loadStateFile}from"./chunk-j75axe29.js";import"./chunk-k1qe5qqa.js";import{DEFAULT_TASK_VENDOR,TASK_STATUSES}from"./chunk-xy8be792.js";import"./chunk-ayhhgfsz.js";import{errorMessage,userFacingErrorMessage}from"./chunk-2brn8e1y.js";import"./chunk-3wj69b0a.js";import{isDev,promptAttachmentsDir,roveStateDir}from"./chunk-ch9b1d5y.js";import{ALL_VENDORS,isBuiltinVendor,nextVendorWithin,prevVendorWithin}from"./chunk-bq3fyc0p.js";import"./chunk-mv7ptt5w.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import{ROVE_PRODUCT_NAME}from"./chunk-g56kvet6.js";import{logClientError}from"./chunk-k2ckx8zw.js";import"./chunk-pw6yfj10.js";import{defaultDaemonSocketPath}from"./chunk-mcdv19rs.js";import{readRoveEnv}from"./chunk-r3k9rbwm.js";import{__require,__toESM}from"./chunk-wqfp8d9w.js";var import_react115=__toESM(require_react_production(),1);function truncateEnd(s,max){if(max<=0)return"";let points=[...s];if(points.length<=max)return s;return`${points.slice(0,Math.max(0,max-1)).join("")}\u2026`}function truncateEndCells(s,maxCells,cellsOf){if(maxCells<=0)return"";let total=0;for(let ch of s)total+=cellsOf(ch.codePointAt(0)??0);if(total<=maxCells)return s;let used=0,out="";for(let ch of s){let w=cellsOf(ch.codePointAt(0)??0);if(used+w>maxCells-1)break;used+=w,out+=ch}return`${out}\u2026`}function truncateStart(s,max){if(max<=0)return"";let points=[...s];if(points.length<=max)return s;return`\u2026${points.slice(points.length-Math.max(0,max-1)).join("")}`}function truncateStartCells(s,maxCells,cellsOf){if(maxCells<=0)return"";let points=[...s],total=0;for(let ch of points)total+=cellsOf(ch.codePointAt(0)??0);if(total<=maxCells)return s;let used=0,out="";for(let i=points.length-1;i>=0;i--){let ch=points[i],w=cellsOf(ch.codePointAt(0)??0);if(used+w>maxCells-1)break;used+=w,out=ch+out}return`\u2026${out}`}var SIDEBAR_WIDTH=24;function sidebarWidthFor(terminalWidth){return Math.max(SIDEBAR_WIDTH,Math.min(40,Math.floor(terminalWidth/6)))}var MAIN_BRANCH_POLL_MS=2000;function sidebarEmptyStateKey(opts){if(opts.searching)return"tasks.empty.noMatchSearch";if(opts.projectFilter)return"tasks.empty.noActiveProject";return"tasks.empty.noActive"}var BRANCH_LABEL_MAX=16;function truncateBranchLabel(branch,max=BRANCH_LABEL_MAX){return truncateEnd(branch,max)}function toneColor(theme,tone){switch(tone){case"success":return theme.success;case"warning":return theme.warning;case"primary":return theme.primary;case"error":return theme.error;default:return theme.textMuted}}function searchQueryKeystroke(query,evt){if(evt.defaultPrevented)return null;if(evt.ctrl||evt.meta||evt.option)return null;if(evt.name==="backspace")return query.slice(0,-1);let seq=evt.sequence;if(!seq||seq.length!==1)return null;let code=seq.charCodeAt(0);if(code<32||code===127)return null;return query+seq}var m=0,p=0,g=0,b=0,I;((r)=>{function u(t2,a,s,i){return i!==void 0?`#${B(t2)}${B(a)}${B(s)}${B(i)}`:`#${B(t2)}${B(a)}${B(s)}`}r.toCss=u;function o(t2,a,s,i=255){return(t2<<24|a<<16|s<<8|i)>>>0}r.toRgba=o;function e(t2,a,s,i){return{css:r.toCss(t2,a,s,i),rgba:r.toRgba(t2,a,s,i)}}r.toColor=e})(I||={});var $;((i)=>{function u(n,l){if(b=(l.rgba&255)/255,b===1)return{css:l.css,rgba:l.rgba};let f=l.rgba>>24&255,d=l.rgba>>16&255,c=l.rgba>>8&255,C=n.rgba>>24&255,h=n.rgba>>16&255,x=n.rgba>>8&255;m=C+Math.round((f-C)*b),p=h+Math.round((d-h)*b),g=x+Math.round((c-x)*b);let R=I.toCss(m,p,g),L=I.toRgba(m,p,g);return{css:R,rgba:L}}i.blend=u;function o(n){return(n.rgba&255)===255}i.isOpaque=o;function e(n,l,f){let d=y.ensureContrastRatio(n.rgba,l.rgba,f);if(d)return I.toColor(d>>24&255,d>>16&255,d>>8&255)}i.ensureContrastRatio=e;function r(n){let l=(n.rgba|255)>>>0;return[m,p,g]=y.toChannels(l),{css:I.toCss(m,p,g),rgba:l}}i.opaque=r;function t2(n,l){return b=Math.round(l*255),[m,p,g]=y.toChannels(n.rgba),{css:I.toCss(m,p,g,b),rgba:I.toRgba(m,p,g,b)}}i.opacity=t2;function a(n,l){return b=n.rgba&255,t2(n,b*l/255)}i.multiplyOpacity=a;function s(n){return[n.rgba>>24&255,n.rgba>>16&255,n.rgba>>8&255]}i.toColorRGB=s})($||={});var _;((r)=>{let u,o;try{let t2=document.createElement("canvas");t2.width=1,t2.height=1;let a=t2.getContext("2d",{willReadFrequently:!0});a&&(u=a,u.globalCompositeOperation="copy",o=u.createLinearGradient(0,0,1,1))}catch{}function e(t2){if(t2.match(/#[\da-f]{3,8}/i))switch(t2.length){case 4:return m=parseInt(t2.slice(1,2).repeat(2),16),p=parseInt(t2.slice(2,3).repeat(2),16),g=parseInt(t2.slice(3,4).repeat(2),16),I.toColor(m,p,g);case 5:return m=parseInt(t2.slice(1,2).repeat(2),16),p=parseInt(t2.slice(2,3).repeat(2),16),g=parseInt(t2.slice(3,4).repeat(2),16),b=parseInt(t2.slice(4,5).repeat(2),16),I.toColor(m,p,g,b);case 7:return{css:t2,rgba:(parseInt(t2.slice(1),16)<<8|255)>>>0};case 9:return{css:t2,rgba:parseInt(t2.slice(1),16)>>>0}}let a=t2.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(a)return m=parseInt(a[1]),p=parseInt(a[2]),g=parseInt(a[3]),b=Math.round((a[5]===void 0?1:parseFloat(a[5]))*255),I.toColor(m,p,g,b);if(!u||!o)throw Error("css.toColor: Unsupported css format");if(u.fillStyle=o,u.fillStyle=t2,typeof u.fillStyle!="string")throw Error("css.toColor: Unsupported css format");if(u.fillRect(0,0,1,1),[m,p,g,b]=u.getImageData(0,0,1,1).data,b!==255)throw Error("css.toColor: Unsupported css format");return{rgba:I.toRgba(m,p,g,b),css:t2}}r.toColor=e})(_||={});var v;((e)=>{function u(r){return o(r>>16&255,r>>8&255,r&255)}e.relativeLuminance=u;function o(r,t2,a){let s=r/255,i=t2/255,n=a/255,l=s<=0.03928?s/12.92:Math.pow((s+0.055)/1.055,2.4),f=i<=0.03928?i/12.92:Math.pow((i+0.055)/1.055,2.4),d=n<=0.03928?n/12.92:Math.pow((n+0.055)/1.055,2.4);return l*0.2126+f*0.7152+d*0.0722}e.relativeLuminance2=o})(v||={});var y;((a)=>{function u(s,i){if(b=(i&255)/255,b===1)return i;let n=i>>24&255,l=i>>16&255,f=i>>8&255,d=s>>24&255,c=s>>16&255,C=s>>8&255;return m=d+Math.round((n-d)*b),p=c+Math.round((l-c)*b),g=C+Math.round((f-C)*b),I.toRgba(m,p,g)}a.blend=u;function o(s,i,n){let l=v.relativeLuminance(s>>8),f=v.relativeLuminance(i>>8);if(F(l,f)<n){if(f<l){let h=e(s,i,n),x=F(l,v.relativeLuminance(h>>8));if(x<n){let R=r(s,i,n),L=F(l,v.relativeLuminance(R>>8));return x>L?h:R}return h}let c=r(s,i,n),C=F(l,v.relativeLuminance(c>>8));if(C<n){let h=e(s,i,n),x=F(l,v.relativeLuminance(h>>8));return C>x?c:h}return c}}a.ensureContrastRatio=o;function e(s,i,n){let l=s>>24&255,f=s>>16&255,d=s>>8&255,c=i>>24&255,C=i>>16&255,h=i>>8&255,x=F(v.relativeLuminance2(c,C,h),v.relativeLuminance2(l,f,d));for(;x<n&&(c>0||C>0||h>0);)c-=Math.max(0,Math.ceil(c*0.1)),C-=Math.max(0,Math.ceil(C*0.1)),h-=Math.max(0,Math.ceil(h*0.1)),x=F(v.relativeLuminance2(c,C,h),v.relativeLuminance2(l,f,d));return(c<<24|C<<16|h<<8|255)>>>0}a.reduceLuminance=e;function r(s,i,n){let l=s>>24&255,f=s>>16&255,d=s>>8&255,c=i>>24&255,C=i>>16&255,h=i>>8&255,x=F(v.relativeLuminance2(c,C,h),v.relativeLuminance2(l,f,d));for(;x<n&&(c<255||C<255||h<255);)c=Math.min(255,c+Math.ceil((255-c)*0.1)),C=Math.min(255,C+Math.ceil((255-C)*0.1)),h=Math.min(255,h+Math.ceil((255-h)*0.1)),x=F(v.relativeLuminance2(c,C,h),v.relativeLuminance2(l,f,d));return(c<<24|C<<16|h<<8|255)>>>0}a.increaseLuminance=r;function t2(s){return[s>>24&255,s>>16&255,s>>8&255,s&255]}a.toChannels=t2})(y||={});function B(u){let o=u.toString(16);return o.length<2?"0"+o:o}function F(u,o){return u<o?(o+0.05)/(u+0.05):(u+0.05)/(o+0.05)}var E=Object.freeze((()=>{let u=[_.toColor("#2e3436"),_.toColor("#cc0000"),_.toColor("#4e9a06"),_.toColor("#c4a000"),_.toColor("#3465a4"),_.toColor("#75507b"),_.toColor("#06989a"),_.toColor("#d3d7cf"),_.toColor("#555753"),_.toColor("#ef2929"),_.toColor("#8ae234"),_.toColor("#fce94f"),_.toColor("#729fcf"),_.toColor("#ad7fa8"),_.toColor("#34e2e2"),_.toColor("#eeeeec")],o=[0,95,135,175,215,255];for(let e=0;e<216;e++){let r=o[e/36%6|0],t2=o[e/6%6|0],a=o[e%6];u.push({css:I.toCss(r,t2,a),rgba:I.toRgba(r,t2,a)})}for(let e=0;e<24;e++){let r=8+e*10;u.push({css:I.toCss(r,r,r),rgba:I.toRgba(r,r,r)})}return u})());function A(u,o,e){return Math.max(o,Math.min(u,e))}function O(u){switch(u){case"&":return"&amp;";case"<":return"&lt;"}return u}var S=class{constructor(o){this._buffer=o}serialize(o,e){let r=this._buffer.getNullCell(),t2=this._buffer.getNullCell(),a=r,s=o.start.y,i=o.end.y,n=o.start.x,l=o.end.x;this._beforeSerialize(i-s,s,i);for(let f=s;f<=i;f++){let d=this._buffer.getLine(f);if(d){let c=f===o.start.y?n:0,C=f===o.end.y?l:d.length;for(let h=c;h<C;h++){let x=d.getCell(h,a===r?t2:r);if(!x){console.warn(`Can't get cell at row=${f}, col=${h}`);continue}this._nextCell(x,a,f,h),a=x}}this._rowEnd(f,f===i)}return this._afterSerialize(),this._serializeString(e)}_nextCell(o,e,r,t2){}_rowEnd(o,e){}_beforeSerialize(o,e,r){}_afterSerialize(){}_serializeString(o){return""}};function T(u,o){return u.getFgColorMode()===o.getFgColorMode()&&u.getFgColor()===o.getFgColor()}function w(u,o){return u.getBgColorMode()===o.getBgColorMode()&&u.getBgColor()===o.getBgColor()}function z(u,o){return u.isInverse()===o.isInverse()&&u.isBold()===o.isBold()&&u.isUnderline()===o.isUnderline()&&u.isOverline()===o.isOverline()&&u.isBlink()===o.isBlink()&&u.isInvisible()===o.isInvisible()&&u.isItalic()===o.isItalic()&&u.isDim()===o.isDim()&&u.isStrikethrough()===o.isStrikethrough()}var k=class extends S{constructor(e,r){super(e);this._terminal=r,this._rowIndex=0,this._allRows=[],this._allRowSeparators=[],this._currentRow="",this._nullCellCount=0,this._cursorStyle=this._buffer.getNullCell(),this._cursorStyleRow=0,this._cursorStyleCol=0,this._backgroundCell=this._buffer.getNullCell(),this._firstRow=0,this._lastCursorRow=0,this._lastCursorCol=0,this._lastContentCursorRow=0,this._lastContentCursorCol=0,this._thisRowLastChar=this._buffer.getNullCell(),this._thisRowLastSecondChar=this._buffer.getNullCell(),this._nextRowFirstChar=this._buffer.getNullCell()}_beforeSerialize(e,r,t2){this._allRows=Array(e),this._lastContentCursorRow=r,this._lastCursorRow=r,this._firstRow=r}_rowEnd(e,r){this._nullCellCount>0&&!w(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let t2="";if(!r){e-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);let a=this._buffer.getLine(e),s=this._buffer.getLine(e+1);if(!s.isWrapped)t2=`\r
3
3
  `,this._lastCursorRow=e+1,this._lastCursorCol=0;else{t2="";let i=a.getCell(a.length-1,this._thisRowLastChar),n=a.getCell(a.length-2,this._thisRowLastSecondChar),l=s.getCell(0,this._nextRowFirstChar),f=l.getWidth()>1,d=!1;(l.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||i.getWidth()===0)&&w(i,l)&&(d=!0),f&&(n.getChars()||n.getWidth()===0)&&w(i,l)&&w(n,l)&&(d=!0)),d||(t2="-".repeat(this._nullCellCount+1),t2+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(t2+="\x1B[A",t2+=`\x1B[${a.length-this._nullCellCount}C`,t2+=`\x1B[${this._nullCellCount}X`,t2+=`\x1B[${a.length-this._nullCellCount}D`,t2+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=t2,this._currentRow="",this._nullCellCount=0}_diffStyle(e,r){let t2=[],a=!T(e,r),s=!w(e,r),i=!z(e,r);if(a||s||i)if(e.isAttributeDefault())r.isAttributeDefault()||t2.push(0);else{if(a){let n=e.getFgColor();e.isFgRGB()?t2.push(38,2,n>>>16&255,n>>>8&255,n&255):e.isFgPalette()?n>=16?t2.push(38,5,n):t2.push(n&8?90+(n&7):30+(n&7)):t2.push(39)}if(s){let n=e.getBgColor();e.isBgRGB()?t2.push(48,2,n>>>16&255,n>>>8&255,n&255):e.isBgPalette()?n>=16?t2.push(48,5,n):t2.push(n&8?100+(n&7):40+(n&7)):t2.push(49)}i&&(e.isInverse()!==r.isInverse()&&t2.push(e.isInverse()?7:27),e.isBold()!==r.isBold()&&t2.push(e.isBold()?1:22),e.isUnderline()!==r.isUnderline()&&t2.push(e.isUnderline()?4:24),e.isOverline()!==r.isOverline()&&t2.push(e.isOverline()?53:55),e.isBlink()!==r.isBlink()&&t2.push(e.isBlink()?5:25),e.isInvisible()!==r.isInvisible()&&t2.push(e.isInvisible()?8:28),e.isItalic()!==r.isItalic()&&t2.push(e.isItalic()?3:23),e.isDim()!==r.isDim()&&t2.push(e.isDim()?2:22),e.isStrikethrough()!==r.isStrikethrough()&&t2.push(e.isStrikethrough()?9:29))}return t2}_nextCell(e,r,t2,a){if(e.getWidth()===0)return;let i=e.getChars()==="",n=this._diffStyle(e,this._cursorStyle);if(i?!w(this._cursorStyle,e):n.length>0){this._nullCellCount>0&&(w(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=t2,this._lastContentCursorCol=this._lastCursorCol=a,this._currentRow+=`\x1B[${n.join(";")}m`;let f=this._buffer.getLine(t2);f!==void 0&&(f.getCell(a,this._cursorStyle),this._cursorStyleRow=t2,this._cursorStyleCol=a)}i?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(w(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=t2,this._lastContentCursorCol=this._lastCursorCol=a+e.getWidth())}_serializeString(e){let r=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(r=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let t2="";for(let i=0;i<r;i++)t2+=this._allRows[i],i+1<r&&(t2+=this._allRowSeparators[i]);if(!e){let i=this._buffer.baseY+this._buffer.cursorY,n=this._buffer.cursorX,l=i!==this._lastCursorRow||n!==this._lastCursorCol,f=(c)=>{c>0?t2+=`\x1B[${c}C`:c<0&&(t2+=`\x1B[${-c}D`)};l&&(((c)=>{c>0?t2+=`\x1B[${c}B`:c<0&&(t2+=`\x1B[${-c}A`)})(i-this._lastCursorRow),f(n-this._lastCursorCol))}let a=this._terminal._core._inputHandler._curAttrData,s=this._diffStyle(a,this._cursorStyle);return s.length>0&&(t2+=`\x1B[${s.join(";")}m`),t2}},D=class{activate(o){this._terminal=o}_serializeBufferByScrollback(o,e,r){let t2=e.length,a=r===void 0?t2:A(r+o.rows,0,t2);return this._serializeBufferByRange(o,e,{start:t2-a,end:t2-1},!1)}_serializeBufferByRange(o,e,r,t2){return new k(e,o).serialize({start:{x:0,y:typeof r.start=="number"?r.start:r.start.line},end:{x:o.cols,y:typeof r.end=="number"?r.end:r.end.line}},t2)}_serializeBufferAsHTML(o,e){let r=o.buffer.active,t2=new M(r,o,e),a=e.onlySelection??!1,s=e.range;if(s)return t2.serialize({start:{x:s.startCol,y:(s.startLine,s.startLine)},end:{x:o.cols,y:(s.endLine,s.endLine)}});if(!a){let n=r.length,l=e.scrollback,f=l===void 0?n:A(l+o.rows,0,n);return t2.serialize({start:{x:0,y:n-f},end:{x:o.cols,y:n-1}})}let i=this._terminal?.getSelectionPosition();return i!==void 0?t2.serialize({start:{x:i.start.x,y:i.start.y},end:{x:i.end.x,y:i.end.y}}):""}_serializeModes(o){let e="",r=o.modes;if(r.applicationCursorKeysMode&&(e+="\x1B[?1h"),r.applicationKeypadMode&&(e+="\x1B[?66h"),r.bracketedPasteMode&&(e+="\x1B[?2004h"),r.insertMode&&(e+="\x1B[4h"),r.originMode&&(e+="\x1B[?6h"),r.reverseWraparoundMode&&(e+="\x1B[?45h"),r.sendFocusMode&&(e+="\x1B[?1004h"),r.wraparoundMode===!1&&(e+="\x1B[?7l"),r.mouseTrackingMode!=="none")switch(r.mouseTrackingMode){case"x10":e+="\x1B[?9h";break;case"vt200":e+="\x1B[?1000h";break;case"drag":e+="\x1B[?1002h";break;case"any":e+="\x1B[?1003h";break}return e}serialize(o){if(!this._terminal)throw Error("Cannot use addon until it has been loaded");let e=o?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,o.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,o?.scrollback);if(!o?.excludeAltBuffer&&this._terminal.buffer.active.type==="alternate"){let r=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);e+=`\x1B[?1049h\x1B[H${r}`}return o?.excludeModes||(e+=this._serializeModes(this._terminal)),e}serializeAsHTML(o){if(!this._terminal)throw Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,o||{})}dispose(){}},M=class extends S{constructor(e,r,t2){super(e);this._terminal=r,this._options=t2,this._currentRow="",this._htmlContent="",r._core._themeService?this._ansiColors=r._core._themeService.colors.ansi:this._ansiColors=E}_padStart(e,r,t2){return r=r>>0,t2=t2??" ",e.length>r?e:(r-=e.length,r>t2.length&&(t2+=t2.repeat(r/t2.length)),t2.slice(0,r)+e)}_beforeSerialize(e,r,t2){this._htmlContent+="<html><body><!--StartFragment--><pre>";let a="#000000",s="#ffffff";(this._options.includeGlobalBackground??!1)&&(a=this._terminal.options.theme?.foreground??"#ffffff",s=this._terminal.options.theme?.background??"#000000");let i=[];i.push("color: "+a+";"),i.push("background-color: "+s+";"),i.push("font-family: "+this._terminal.options.fontFamily+";"),i.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="<div style='"+i.join(" ")+"'>"}_afterSerialize(){this._htmlContent+="</div>",this._htmlContent+="</pre><!--EndFragment--></body></html>"}_rowEnd(e,r){this._htmlContent+="<div><span>"+this._currentRow+"</span></div>",this._currentRow=""}_getHexColor(e,r){let t2=r?e.getFgColor():e.getBgColor();if(r?e.isFgRGB():e.isBgRGB())return"#"+[t2>>16&255,t2>>8&255,t2&255].map((s)=>this._padStart(s.toString(16),2,"0")).join("");if(r?e.isFgPalette():e.isBgPalette())return this._ansiColors[t2].css}_diffStyle(e,r){let t2=[],a=!T(e,r),s=!w(e,r),i=!z(e,r);if(a||s||i){let n=this._getHexColor(e,!0);n&&t2.push("color: "+n+";");let l=this._getHexColor(e,!1);return l&&t2.push("background-color: "+l+";"),e.isInverse()&&t2.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&t2.push("font-weight: bold;"),e.isUnderline()&&e.isOverline()?t2.push("text-decoration: overline underline;"):e.isUnderline()?t2.push("text-decoration: underline;"):e.isOverline()&&t2.push("text-decoration: overline;"),e.isBlink()&&t2.push("text-decoration: blink;"),e.isInvisible()&&t2.push("visibility: hidden;"),e.isItalic()&&t2.push("font-style: italic;"),e.isDim()&&t2.push("opacity: 0.5;"),e.isStrikethrough()&&t2.push("text-decoration: line-through;"),t2}}_nextCell(e,r,t2,a){if(e.getWidth()===0)return;let i=e.getChars()==="",n=this._diffStyle(e,r);n&&(this._currentRow+=n.length===0?"</span><span>":"</span><span style='"+n.join(" ")+"'>"),i?this._currentRow+=" ":this._currentRow+=O(e.getChars())}_serializeString(){return this._htmlContent}};var D2=new Set(["<","=",">"]);var M2=new Set(["P","_","^","X"]);var F2=/[;:]/,I2={TEXT:"TEXT",INTRODUCER:"INTRODUCER",DATA:"DATA",FINAL:"FINAL"},L={CSI:"CSI",DCS:"DCS",DEC:"DEC",ESC:"ESC",OSC:"OSC",PRIVATE:"PRIVATE",SGR:"SGR",STRING:"STRING",TEXT:"TEXT"};function R(e){if(e.length===1)return e[0].raw;if(e.length===0)return"";let t2="";for(let n of e)t2+=n.raw;return t2}function z2(e,t2,n){let r=R(t2),i=e.raw+r+(n?.raw||"");return{type:L.STRING,pos:e.pos,raw:i,command:"APC",params:r?[r]:[]}}function B2(e,t2,n){let r=R(t2),i=n?.raw??"",a=e.raw+r+i,o=[],s=L.CSI,c=0;if(r)for(;c<r.length;){let e2=r.charCodeAt(c);if(e2<48||e2>63)break;c++}let l=c>0?r.substring(0,c):"",u=c<r.length?r.substring(c):"";if(l){let e2=0;for(let t3=0;t3<=l.length;t3++)(t3===l.length||l.charCodeAt(t3)===59||l.charCodeAt(t3)===58)&&(o.push(t3>e2?l.substring(e2,t3):"0"),e2=t3+1)}let d=u+i,f=o[0];if(f!==void 0&&f.charCodeAt(0)===63)return s=L.DEC,f.length>1?o[0]=f.substring(1):o.shift(),{type:s,pos:e.pos,raw:a,command:d,params:o};for(let t3 of o)if(t3.length>0&&D2.has(t3[0])){s=L.PRIVATE;let n2=t3[0]+d;for(let e2=0;e2<o.length;e2++)if(o[e2].length>0&&D2.has(o[e2][0])){o[e2].length>1?o[e2]=o[e2].substring(1):o.splice(e2,1);break}return{type:s,pos:e.pos,raw:a,command:n2,params:o}}return d==="m"&&o.length===5&&o[1]==="2"&&(f==="38"||f==="48")&&o.splice(2,0,"0"),d==="r"&&o.length===2&&o[1]==="0"&&(o[1]="-1"),{type:s,pos:e.pos,raw:a,command:d,params:o}}var V=new Map([["$q",2],["+q",2],["+p",2],["|",1],["{",1]]);function H(e,t2,n){let r=R(t2),i=e.raw+r+(n?.raw??"");if(!r)return{type:L.DCS,pos:e.pos,raw:i,command:"",params:[]};for(let[t3,n2]of V)if(r.startsWith(t3)){let a=r.slice(n2),o=[];if(a)for(let e2 of a.split(F2))o.push(e2||"-1");return{type:L.DCS,pos:e.pos,raw:i,command:t3,params:o}}return{type:L.DCS,pos:e.pos,raw:i,command:"",params:[r]}}function U(e,t2,n){let r=R(t2),i=e.intermediate||(t2[0]?.raw??n?.raw??""),a=e.intermediate&&n?.raw?[n.raw]:[],o=e.raw+r+(n?.raw??"");return{type:L.ESC,pos:e.pos,raw:o,command:i,params:a}}function W(e,t2,n){let r=R(t2),i=e.raw+r+(n?.raw||""),a=r.indexOf(";");if(a===-1)return{type:L.OSC,pos:e.pos,raw:i,command:r,params:[]};let o=r.slice(0,a),s=r.slice(a+1);if(o==="1337")return{type:L.OSC,pos:e.pos,raw:i,command:o,params:[s]};let c=s?s.split(";"):[];return{type:L.OSC,pos:e.pos,raw:i,command:o,params:c}}function G(e,t2,n){let r=R(t2),i=e.raw+r+(n?.raw||"");return{type:L.STRING,pos:e.pos,raw:i,command:"PM",params:r?[r]:[]}}function K(e,t2,n){let r=R(t2),i=e.raw+r+(n?.raw||"");return{type:L.STRING,pos:e.pos,raw:i,command:"SOS",params:r?[r]:[]}}function q(e){return e===24||e===26||e===27||e===155||e===157||e===144||e===159||e===158||e===152}function J(e){return e===24||e===26}function Y(e){return e===27||e===155||e===157||e===144||e===159||e===158||e===152}function X(e){return e===155||e===157||e===144||e===159||e===158||e===152}function Z(e){let t2=[],n=0,r=0,i=0,a=e.length;for(;n<a;)if(r===0){let o=n,s=e.charCodeAt(n);for(;n<a&&!Y(s);)s=e.charCodeAt(++n);if(n>o&&t2.push({type:I2.TEXT,pos:o,raw:e.substring(o,n)}),n>=a)break;if(X(s))t2.push({type:I2.INTRODUCER,pos:n,raw:e[n],code:e[n]}),n++,r=1,i=s;else{let o2=e.charCodeAt(n+1);if(o2===91)t2.push({type:I2.INTRODUCER,pos:n,raw:e.substring(n,n+2),code:"\x9B"}),n+=2,r=1,i=155;else if(o2===93)t2.push({type:I2.INTRODUCER,pos:n,raw:e.substring(n,n+2),code:"\x9D"}),n+=2,r=1,i=157;else if(n+1<a&&M2.has(e[n+1]))t2.push({type:I2.INTRODUCER,pos:n,raw:e.substring(n,n+2),code:e[n+1]}),n+=2,r=1,i=o2;else if(n+1<a){let o3=n+1;for(;o3<a&&e.charCodeAt(o3)>=32&&e.charCodeAt(o3)<=47;)o3++;if(o3>n+1){let r2=e.substring(n+1,o3);t2.push({type:I2.INTRODUCER,pos:n,raw:e.substring(n,o3),code:"\x1B",intermediate:r2})}else t2.push({type:I2.INTRODUCER,pos:n,raw:e[n],code:"\x1B"});n=o3,o3<a&&(r=1,i=27)}else t2.push({type:I2.INTRODUCER,pos:n,raw:e[n],code:"\x1B"}),n++}}else{let o=n;if(i===155){let i2=n;for(;n<a;){let a2=e.charCodeAt(n);if(q(a2)){n>i2&&t2.push({type:I2.DATA,pos:o,raw:e.substring(i2,n)}),r=0,J(a2)&&(t2.push({type:I2.TEXT,pos:n,raw:e[n]}),n++);break}if(a2>=64&&a2<=126){n>i2&&t2.push({type:I2.DATA,pos:o,raw:e.substring(i2,n)}),t2.push({type:I2.FINAL,pos:n,raw:e[n]}),n++,r=0;break}n++}r===1&&n>i2&&t2.push({type:I2.DATA,pos:o,raw:e.substring(i2,n)})}else if(i===27){if(n<a){let i2=e.charCodeAt(n);q(i2)?(r=0,J(i2)&&(t2.push({type:I2.TEXT,pos:n,raw:e[n]}),n++)):(t2.push({type:I2.FINAL,pos:n,raw:e[n]}),n++,r=0)}}else{let s=n;for(;n<a;){let a2=e.charCodeAt(n),c;if(a2===27&&e.charCodeAt(n+1)===92?c="\x1B\\":a2===156?c="\x9C":a2===7&&i===157&&(c="\x07"),c){n>s&&t2.push({type:I2.DATA,pos:o,raw:e.substring(s,n)}),t2.push({type:I2.FINAL,pos:n,raw:c}),n+=c.length,r=0;break}if(q(a2)){n>s&&t2.push({type:I2.DATA,pos:o,raw:e.substring(s,n)}),r=0,J(a2)&&(t2.push({type:I2.TEXT,pos:n,raw:e[n]}),n++);break}n++}r===1&&n>s&&t2.push({type:I2.DATA,pos:o,raw:e.substring(s,n)})}r===1&&(r=0)}return t2}function Q(e,t2,n){switch(e.code){case"\x9B":return B2(e,t2,n);case"\x9D":return W(e,t2,n);case"\x90":case"P":return H(e,t2,n);case"\x9F":case"_":return z2(e,t2,n);case"\x9E":case"X":return G(e,t2,n);case"\x98":case"^":return K(e,t2,n);case"\x1B":return U(e,t2,n);default:return{type:L.TEXT,pos:e.pos,raw:e.raw}}}function $2(e){let t2=[],n=0,r=e.length;for(;n<r;){let i=e[n];if(i.type===I2.TEXT){t2.push({type:L.TEXT,pos:i.pos,raw:i.raw}),n++;continue}if(i.type===I2.INTRODUCER){let a=i,o=[],s;for(n++;n<r;){let t3=e[n];if(t3.type===I2.DATA)o.push(t3);else if(t3.type===I2.FINAL){s=t3,n++;break}else break;n++}t2.push(Q(a,o,s))}else n++}return t2}function ie(e){return $2(Z(e))}var DEFAULT_COLS=80,DEFAULT_ROWS=24,PIPE_SCROLLBACK_LIMIT=200000;function defaultShell(){return resolveLoginShell()}function extractOscTitle(chunk){let title=null;for(let code of ie(chunk))if(code.type==="OSC"&&(code.command==="0"||code.command==="2")&&code.params[0])title=code.params[0];return title}function resolveArgv(opts){if(opts.command&&opts.command.length>0)return[...opts.command];return[opts.shell??defaultShell()]}var shared=null,hostedByKey=new Map;function routeAdd(handle){let set=hostedByKey.get(handle.taskId);if(!set)set=new Set,hostedByKey.set(handle.taskId,set);set.add(handle)}function routeRemove(handle){let set=hostedByKey.get(handle.taskId);if(!set)return 0;if(set.delete(handle),set.size===0)hostedByKey.delete(handle.taskId);return set.size}function routeCount(key){return hostedByKey.get(key)?.size??0}var dispatchInstalled=new WeakSet;function installDispatch(client){if(dispatchInstalled.has(client))return;dispatchInstalled.add(client),client.on("pty.data",(frame)=>{let payload=frame.payload,handles=hostedByKey.get(payload.key);if(handles)for(let handle of handles)handle.feedFrame(payload.data)}),client.on("pty.exit",(frame)=>{let payload=frame.payload,handles=hostedByKey.get(payload.key);if(handles)for(let handle of[...handles])handle.remoteExited(payload.pid)})}function getSharedPtyClient(){if(shared)return shared;let p3=(async()=>{let socketPath=await ensurePtyHostReachable(),client=new KobeDaemonClient(socketPath);return await client.connect(),installDispatch(client),client.onLifecycle("close",()=>{if(shared===p3)shared=null}),client})();return p3.catch(()=>{if(shared===p3)shared=null}),shared=p3,p3}function peekSharedPtyClient(){return shared}function warmHostedShell(cwd,shell=defaultShell()){if((process.env.KOBE_TERMINAL_BACKEND??"hosted")!=="hosted")return;getSharedPtyClient().then((client)=>client.request("pty.warm",{cwd,shell})).catch(()=>{})}var import_headless=__toESM(require_xterm_headless(),1);var SCROLLBACK_ROWS_KEY="terminal.scrollbackRows",DEFAULT_SCROLLBACK_ROWS=1000,SCROLLBACK_ROWS_MIN=100,SCROLLBACK_ROWS_MAX=1e5;function normalizeScrollbackRows(value){let n2=typeof value==="number"?Math.floor(value):typeof value==="string"?Number.parseInt(value.trim(),10):Number.NaN;if(!Number.isFinite(n2))return DEFAULT_SCROLLBACK_ROWS;return Math.min(SCROLLBACK_ROWS_MAX,Math.max(SCROLLBACK_ROWS_MIN,n2))}function persistedScrollbackRows(){return normalizeScrollbackRows(loadStateFile()[SCROLLBACK_ROWS_KEY])}var target=process.env.ROVE_RENDER_PROFILE,renderProfileOn=Boolean(target),counts=new Map,totals=new Map,started=0;function flush(){if(counts.size===0)return;let row={sec:Math.round((Date.now()-started)/1000)};for(let[k3,n2]of counts){row[`${k3}_n`]=n2;let ms=totals.get(k3);if(ms!==void 0)row[`${k3}_ms`]=+ms.toFixed(3)}counts.clear(),totals.clear();try{__require("fs").appendFileSync(target,`${JSON.stringify(row)}
4
4
  `)}catch{}}if(renderProfileOn)started=Date.now(),setInterval(flush,1000).unref?.();function profileTick(stage){if(!renderProfileOn)return;counts.set(stage,(counts.get(stage)??0)+1)}function profileSpan(stage,fn){if(!renderProfileOn)return fn();let t0=performance.now();try{return fn()}finally{counts.set(stage,(counts.get(stage)??0)+1),totals.set(stage,(totals.get(stage)??0)+(performance.now()-t0))}}var KITTY_CSI_U_RE=/^\x1b\[[\d:;]*u$/;function containsControlCharacter(value){for(let character of value){let codePoint=character.codePointAt(0);if(codePoint===void 0||codePoint<=31||codePoint>=127&&codePoint<=159)return!0}return!1}var CTRL_PUNCT_C0={"@":"\x00","[":"\x1B","\\":"\x1C","]":"\x1D","^":"\x1E",_:"\x1F","?":"\x7F"},LEGACY_FUNCTION_KEYS={f1:{kind:"ss3",final:"P"},f2:{kind:"ss3",final:"Q"},f3:{kind:"ss3",final:"R"},f4:{kind:"ss3",final:"S"},f5:{kind:"tilde",number:15},f6:{kind:"tilde",number:17},f7:{kind:"tilde",number:18},f8:{kind:"tilde",number:19},f9:{kind:"tilde",number:20},f10:{kind:"tilde",number:21},f11:{kind:"tilde",number:23},f12:{kind:"tilde",number:24}},XTERM_MODIFIER_NAMED_KEYS=new Set(["delete","kpdelete","insert","kpinsert","up","kpup","down","kpdown","right","kpright","left","kpleft","home","kphome","end","kpend","pageup","kppageup","pagedown","kppagedown"]);function legacyModifier(evt){return 1+(evt.shift?1:0)+(evt.option||evt.meta?2:0)+(evt.ctrl?4:0)+(evt.super?8:0)+(evt.hyper?16:0)}function legacyCursorSequence(evt,final,applicationCursorKeys){let modifier=legacyModifier(evt);if(modifier!==1)return`\x1B[1;${modifier}${final}`;return applicationCursorKeys?`\x1BO${final}`:`\x1B[${final}`}function legacyTildeSequence(evt,number){let modifier=legacyModifier(evt);return modifier===1?`\x1B[${number}~`:`\x1B[${number};${modifier}~`}function legacyFunctionSequence(evt,key){if(key.kind==="tilde")return legacyTildeSequence(evt,key.number);let modifier=legacyModifier(evt);return modifier===1?`\x1BO${key.final}`:`\x1B[1;${modifier}${key.final}`}var NORMAL_TERMINAL_INPUT_MODES={applicationCursorKeys:!1,applicationKeypad:!1};function keyEventToShellBytes(evt,modes=NORMAL_TERMINAL_INPUT_MODES){if(isKittyModifierKeyEvent(evt))return null;let e2=evt,seq=typeof e2.sequence==="string"&&e2.sequence.length>0?e2.sequence:null,kittyInput=e2.source==="kitty"||typeof e2.raw==="string"&&KITTY_CSI_U_RE.test(e2.raw)||seq!=null&&KITTY_CSI_U_RE.test(seq);if(seq!=null&&!kittyInput)return seq;if(seq!=null&&!containsControlCharacter(seq)&&!evt.ctrl&&!e2.option&&!e2.meta)return seq;return synthesizeShellBytes(evt,modes)}function synthesizeShellBytes(evt,modes){let name=evt.name;if(!name)return null;if(evt.shift&&name==="tab")return"\x1B[Z";let functionKey=LEGACY_FUNCTION_KEYS[name],xtermModifiedNamedKey=functionKey!==void 0||XTERM_MODIFIER_NAMED_KEYS.has(name);if((evt.option||evt.meta)&&!xtermModifiedNamedKey){let inner=synthesizeShellBytes({...evt,option:!1,meta:!1},modes);return inner==null?null:`\x1B${inner}`}if(functionKey)return legacyFunctionSequence(evt,functionKey);switch(name){case"return":case"enter":return"\r";case"kpenter":return modes.applicationKeypad&&legacyModifier(evt)===1?"\x1BOM":"\r";case"tab":return"\t";case"backspace":return"\x7F";case"delete":case"kpdelete":return legacyTildeSequence(evt,3);case"insert":case"kpinsert":return legacyTildeSequence(evt,2);case"up":case"kpup":return legacyCursorSequence(evt,"A",modes.applicationCursorKeys);case"down":case"kpdown":return legacyCursorSequence(evt,"B",modes.applicationCursorKeys);case"right":case"kpright":return legacyCursorSequence(evt,"C",modes.applicationCursorKeys);case"left":case"kpleft":return legacyCursorSequence(evt,"D",modes.applicationCursorKeys);case"home":case"kphome":return legacyCursorSequence(evt,"H",modes.applicationCursorKeys);case"end":case"kpend":return legacyCursorSequence(evt,"F",modes.applicationCursorKeys);case"pageup":case"kppageup":return legacyTildeSequence(evt,5);case"pagedown":case"kppagedown":return legacyTildeSequence(evt,6);case"clear":return"\x1B[E";case"escape":return"\x1B";case"space":return evt.ctrl?"\x00":" ";default:if(name.length===1){if(evt.ctrl){let code=name.toLowerCase().charCodeAt(0);if(code>=97&&code<=122)return String.fromCharCode(code-96);let c0=CTRL_PUNCT_C0[name];if(c0!=null)return c0;return null}if(evt.shift&&name>="a"&&name<="z")return name.toUpperCase();return name}return null}}var DEFAULT_PAGE_SIZE=10;var RESERVED_SPEC=[{id:"help.open"},{id:"focus.sidebar"},{id:"chat.tab.new"},{id:"chat.tab.close"},{id:"chat.tab.cycle-next"},{id:"chat.tab.cycle-prev"},{id:"chat.tab.rename"},"ctrl+e","ctrl+f",{id:"workspace.split.right"},{id:"workspace.split.down"},{id:"workspace.split.focus-next"},{id:"focus.next"},{id:"terminal.reset"},{id:"attention.next"},{id:"tasks.jump"}],RESERVED_GLOBAL_CHORDS=[...new Set(RESERVED_SPEC.flatMap((entry)=>typeof entry==="string"?[entry]:defaultChordsOf(entry.id)))],PASSTHROUGH_NAMES=[..."abcdefghijklmnopqrstuvwxyz".split(""),..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),..."0123456789".split(""),..." `~!@#$%^&*()-_=+[]{}\\|;:'\",.<>/?".split(""),"return","enter","space","tab","backspace","delete","up","down","left","right","home","end","pageup","pagedown","escape","insert","f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","f11","f12"],PASSTHROUGH_MODIFIER_PREFIXES=["","ctrl+","alt+","shift+","ctrl+shift+","alt+shift+","ctrl+alt+"],PASSTHROUGH_CHORDS=PASSTHROUGH_NAMES.flatMap((name)=>PASSTHROUGH_MODIFIER_PREFIXES.map((prefix)=>`${prefix}${name}`)).filter((chord)=>!RESERVED_GLOBAL_CHORDS.includes(chord));function encodeWheel(modes,direction,col,row){if(modes.mouseTracking)return`\x1B[<${direction==="up"?64:65};${Math.max(1,col)};${Math.max(1,row)}M`;if(modes.alternateScreen)return(modes.applicationCursorKeys?direction==="up"?"\x1BOA":"\x1BOB":direction==="up"?"\x1B[A":"\x1B[B").repeat(3);return null}function encodeMouseButton(modes,kind,button,col,row,modifiers){if(modes.mouseTracking==="none")return null;if(kind==="drag"&&modes.mouseTracking!=="drag"&&modes.mouseTracking!=="any")return null;let code=button;if(kind==="drag")code+=32;if(modifiers?.shift)code+=4;if(modifiers?.alt)code+=8;if(modifiers?.ctrl)code+=16;return`\x1B[<${code};${Math.max(1,col)};${Math.max(1,row)}${kind==="up"?"m":"M"}`}class PtyListeners{data=new Set;exits=new Set;titles=new Set;get dataCount(){return this.data.size}addData(listener){return this.data.add(listener),()=>this.data.delete(listener)}addExit(listener){return this.exits.add(listener),()=>this.exits.delete(listener)}addTitle(listener){return this.titles.add(listener),()=>this.titles.delete(listener)}publishData(snapshot,cursor,window,wrapped){for(let listener of this.data)try{listener(snapshot,cursor,window,wrapped)}catch{}}publishTitle(title){for(let listener of this.titles)try{listener(title)}catch{}}drainExits(){let listeners=[...this.exits];return this.exits.clear(),listeners}clearData(){this.data.clear()}clearAll(){this.data.clear(),this.exits.clear(),this.titles.clear()}}function sameRgb(a2,b3){if(a2===b3)return!0;return a2!==void 0&&b3!==void 0&&a2[0]===b3[0]&&a2[1]===b3[1]&&a2[2]===b3[2]}function sameChunk(a2,b3){return a2.text===b3.text&&(a2.attributes??0)===(b3.attributes??0)&&sameRgb(a2.fg,b3.fg)&&sameRgb(a2.bg,b3.bg)}function sameRow(a2,b3){if(a2===b3)return!0;if(a2.length!==b3.length)return!1;for(let i2=0;i2<a2.length;i2++)if(!sameChunk(a2[i2],b3[i2]))return!1;return!0}function reconcileTerminalRow(previous,next){return previous&&sameRow(previous,next)?previous:next}function reconcileTerminalRows(previous,next){if(previous.length!==next.length)return next;let changed=!1;for(let i2=0;i2<next.length;i2++){let stable=reconcileTerminalRow(previous[i2],next[i2]);if(next[i2]=stable,stable!==previous[i2])changed=!0}return changed?next:previous}function reconcileTerminalCursor(previous,next){if(previous===next)return previous;if(previous&&next&&previous.x===next.x&&previous.y===next.y)return previous;return next}var ATTR=Object.freeze({BOLD:1,DIM:2,ITALIC:4,UNDERLINE:8,BLINK:16,INVERSE:32,HIDDEN:64,STRIKETHROUGH:128}),EMPTY_STYLE=Object.freeze({fg:void 0,bg:void 0,attributes:0});function ansi256ToRgb(index){if(index<0)return[0,0,0];if(index<16)return SYSTEM_PALETTE[index]??[0,0,0];if(index<232){let i2=index-16,r2=Math.floor(i2/36),g3=Math.floor(i2/6%6),b3=i2%6,step=(n2)=>n2===0?0:55+40*n2;return[step(r2),step(g3),step(b3)]}if(index<256){let gray=8+10*(index-232);return[gray,gray,gray]}return[0,0,0]}var SYSTEM_PALETTE=[[21,22,30],[247,118,142],[158,206,106],[224,175,104],[122,162,247],[187,154,247],[125,207,255],[169,177,214],[65,72,104],[255,137,157],[158,224,68],[250,186,74],[141,176,255],[199,169,255],[164,218,255],[192,202,245]];function applySgr(prev,rawParams){let params=rawParams.length===0?[0]:rawParams.map((p3)=>p3===""?0:Number.parseInt(p3,10)||0),fg=prev.fg,bg=prev.bg,attr=prev.attributes,i2=0;while(i2<params.length){let p3=params[i2];if(p3===void 0)break;if(p3===0){fg=void 0,bg=void 0,attr=0,i2+=1;continue}if(p3===1){attr|=ATTR.BOLD,i2+=1;continue}if(p3===2){attr|=ATTR.DIM,i2+=1;continue}if(p3===3){attr|=ATTR.ITALIC,i2+=1;continue}if(p3===4){attr|=ATTR.UNDERLINE,i2+=1;continue}if(p3===5||p3===6){attr|=ATTR.BLINK,i2+=1;continue}if(p3===7){attr|=ATTR.INVERSE,i2+=1;continue}if(p3===8){attr|=ATTR.HIDDEN,i2+=1;continue}if(p3===9){attr|=ATTR.STRIKETHROUGH,i2+=1;continue}if(p3===22){attr&=~(ATTR.BOLD|ATTR.DIM),i2+=1;continue}if(p3===23){attr&=~ATTR.ITALIC,i2+=1;continue}if(p3===24){attr&=~ATTR.UNDERLINE,i2+=1;continue}if(p3===25){attr&=~ATTR.BLINK,i2+=1;continue}if(p3===27){attr&=~ATTR.INVERSE,i2+=1;continue}if(p3===28){attr&=~ATTR.HIDDEN,i2+=1;continue}if(p3===29){attr&=~ATTR.STRIKETHROUGH,i2+=1;continue}if(p3>=30&&p3<=37){fg=ansi256ToRgb(p3-30),i2+=1;continue}if(p3>=90&&p3<=97){fg=ansi256ToRgb(p3-90+8),i2+=1;continue}if(p3===39){fg=void 0,i2+=1;continue}if(p3>=40&&p3<=47){bg=ansi256ToRgb(p3-40),i2+=1;continue}if(p3>=100&&p3<=107){bg=ansi256ToRgb(p3-100+8),i2+=1;continue}if(p3===49){bg=void 0,i2+=1;continue}if(p3===38){let sub=params[i2+1];if(sub===5){let idx=params[i2+2]??0;fg=ansi256ToRgb(idx),i2+=3;continue}if(sub===2){let r2=params[i2+2]??0,g3=params[i2+3]??0,b3=params[i2+4]??0;fg=[r2,g3,b3],i2+=5;continue}i2+=1;continue}if(p3===48){let sub=params[i2+1];if(sub===5){let idx=params[i2+2]??0;bg=ansi256ToRgb(idx),i2+=3;continue}if(sub===2){let r2=params[i2+2]??0,g3=params[i2+3]??0,b3=params[i2+4]??0;bg=[r2,g3,b3],i2+=5;continue}i2+=1;continue}i2+=1}return{fg,bg,attributes:attr}}function sgrParamsFromRaw(raw){let body=raw;if(body.charCodeAt(0)===27)body=body.slice(2);else if(body.charCodeAt(0)===155)body=body.slice(1);if(body.endsWith("m"))body=body.slice(0,-1);return body.split(";")}function parseAnsiLine(input,initial=EMPTY_STYLE){if(input.length===0)return{chunks:[],endStyle:initial};let out=[],style={...initial},buf="",flush2=()=>{if(buf.length===0)return;let c2={text:buf,...style.fg?{fg:style.fg}:{},...style.bg?{bg:style.bg}:{},...style.attributes!==0?{attributes:style.attributes}:{}};out.push(c2),buf=""},codes=ie(input);for(let code of codes){if(code.type==="TEXT"){buf+=code.raw;continue}if(code.type==="CSI"&&code.command==="m"){flush2(),style=applySgr(style,sgrParamsFromRaw(code.raw));continue}if(code.type==="OSC"&&code.command==="8"){flush2();let url=code.params[code.params.length-1]??"";style={...style,attributes:url?style.attributes|ATTR.UNDERLINE:style.attributes&~ATTR.UNDERLINE}}}return flush2(),{chunks:out,endStyle:style}}function parseAnsiSnapshot(input){let lines=input.split(`
5
5
  `),rows=[],carry=EMPTY_STYLE;for(let line of lines){let{chunks,endStyle}=parseAnsiLine(line,carry);rows.push(chunks),carry=endStyle}return rows}var XTERM_COLOR_MODE_DEFAULT=0,XTERM_COLOR_MODE_PALETTE=16777216,XTERM_COLOR_MODE_RGB=50331648,DEFAULT_RENDER_STYLE=Object.freeze({fg:"",bg:"",attrs:0});function colorKeyToRGB(key){if(key==="")return;let sep=key.indexOf(":"),value=Number(key.slice(sep+1));if(key.startsWith("rgb:"))return[value>>16&255,value>>8&255,value&255];if(key.startsWith("pal:"))return ansi256ToRgb(value);return}function colorKey(cell,kind){if(kind==="fg"?cell.isFgDefault():cell.isBgDefault())return"";let mode=kind==="fg"?cell.getFgColorMode():cell.getBgColorMode(),color=kind==="fg"?cell.getFgColor():cell.getBgColor();if(mode===XTERM_COLOR_MODE_RGB||(kind==="fg"?cell.isFgRGB():cell.isBgRGB()))return`rgb:${color}`;if(mode===XTERM_COLOR_MODE_PALETTE||(kind==="fg"?cell.isFgPalette():cell.isBgPalette()))return`pal:${color}`;if(mode===XTERM_COLOR_MODE_DEFAULT)return"";return""}function cellAttributes(cell){let attrs=0;if(cell.isBold())attrs|=ATTR.BOLD;if(cell.isDim())attrs|=ATTR.DIM;if(cell.isItalic())attrs|=ATTR.ITALIC;if(cell.isUnderline())attrs|=ATTR.UNDERLINE;if(cell.isBlink())attrs|=ATTR.BLINK;if(cell.isInverse())attrs|=ATTR.INVERSE;if(cell.isInvisible())attrs|=ATTR.HIDDEN;if(cell.isStrikethrough())attrs|=ATTR.STRIKETHROUGH;return attrs}function matchingStyleRewrite(cell,styleRewrites){if(!styleRewrites||styleRewrites.length===0||!cell.isFgDefault()||cell.isBgDefault())return;let background=colorKeyToRGB(colorKey(cell,"bg"));return styleRewrites.find((rewrite)=>sameRgb2(background,rewrite.matchBackground))}function rgbKey([red,green,blue]){return`rgb:${red<<16|green<<8|blue}`}function cellStyle(cell,styleRewrites){let style={fg:colorKey(cell,"fg"),bg:colorKey(cell,"bg"),attrs:cellAttributes(cell)},rewrite=matchingStyleRewrite(cell,styleRewrites);return rewrite?{...style,fg:rgbKey(rewrite.foreground),bg:rgbKey(rewrite.background)}:style}function styleEquals(a2,b3){return a2.fg===b3.fg&&a2.bg===b3.bg&&a2.attrs===b3.attrs}function renderStyleToChunkFields(style){let fg=colorKeyToRGB(style.fg),bg=colorKeyToRGB(style.bg);return{...fg?{fg}:{},...bg?{bg}:{},...style.attrs!==0?{attributes:style.attrs}:{}}}function isSolidBlock(chars){return chars==="\u2580"||chars==="\u2584"||chars==="\u2588"}function paintsSamePixel(fg,bg){if(fg===void 0||bg===void 0)return!1;return fg[0]===bg[0]&&fg[1]===bg[1]&&fg[2]===bg[2]}function isVisibleCell(cell){let chars=cell.getChars();if(chars!==""&&chars!==" ")return!0;return!cell.isAttributeDefault()||!cell.isFgDefault()||!cell.isBgDefault()}var scratchCell;function getCellReusing(line,x2){if(scratchCell===void 0){let seeded=line.getCell(x2);if(seeded)scratchCell=seeded;return seeded}return line.getCell(x2,scratchCell)}function xtermLineToChunks(line,minLast=-1,styleRewrites){let last=Math.min(line.length-1,minLast);for(let x2=0;x2<line.length;x2++){let cell=getCellReusing(line,x2);if(!cell||cell.getWidth()===0)continue;if(isVisibleCell(cell))last=Math.max(last,x2)}if(last===-1)return[];let out=[],active=DEFAULT_RENDER_STYLE,activeIsFill=!1,buf="",flush2=()=>{if(buf==="")return;out.push({text:buf,...renderStyleToChunkFields(active)}),buf=""};for(let x2=0;x2<=last;x2++){let cell=getCellReusing(line,x2);if(!cell||cell.getWidth()===0)continue;let next=cellStyle(cell,styleRewrites);if(!styleEquals(active,next))flush2(),active=next,activeIsFill=paintsSamePixel(colorKeyToRGB(next.fg),colorKeyToRGB(next.bg));let chars=cell.getChars()||" ";buf+=isSolidBlock(chars)&&activeIsFill?" ":chars}return flush2(),out}function chunkColorMatchesCell(rgb,cell,kind){if(kind==="fg"?cell.isFgDefault():cell.isBgDefault())return rgb===void 0;if(!rgb)return!1;let mode=kind==="fg"?cell.getFgColorMode():cell.getBgColorMode(),color=kind==="fg"?cell.getFgColor():cell.getBgColor();if(mode===XTERM_COLOR_MODE_RGB||(kind==="fg"?cell.isFgRGB():cell.isBgRGB()))return rgb[0]===(color>>16&255)&&rgb[1]===(color>>8&255)&&rgb[2]===(color&255);if(mode===XTERM_COLOR_MODE_PALETTE||(kind==="fg"?cell.isFgPalette():cell.isBgPalette())){let palette=ansi256ToRgb(color);return rgb[0]===palette[0]&&rgb[1]===palette[1]&&rgb[2]===palette[2]}return!1}function sameRgb2(a2,b3){return Boolean(a2&&b3&&a2[0]===b3[0]&&a2[1]===b3[1]&&a2[2]===b3[2])}function chunkStyleMatchesCell(chunk,cell,styleRewrites){let rewrite=matchingStyleRewrite(cell,styleRewrites);if(rewrite)return(chunk.attributes??0)===cellAttributes(cell)&&sameRgb2(chunk.fg,rewrite.foreground)&&sameRgb2(chunk.bg,rewrite.background);return(chunk.attributes??0)===cellAttributes(cell)&&chunkColorMatchesCell(chunk.fg,cell,"fg")&&chunkColorMatchesCell(chunk.bg,cell,"bg")}function xtermLineMatchesChunks(line,row,minLast=-1,styleRewrites){if(!line)return row.length===0;let last=Math.min(line.length-1,minLast);for(let x2=0;x2<line.length;x2++){let cell=getCellReusing(line,x2);if(!cell||cell.getWidth()===0)continue;if(isVisibleCell(cell))last=Math.max(last,x2)}if(last===-1)return row.length===0;let chunkIndex=0,textOffset=0;for(let x2=0;x2<=last;x2++){let cell=getCellReusing(line,x2);if(!cell||cell.getWidth()===0)continue;let chunk=row[chunkIndex];if(!chunk||!chunkStyleMatchesCell(chunk,cell,styleRewrites))return!1;let raw=cell.getChars()||" ",text=isSolidBlock(raw)&&paintsSamePixel(chunk.fg,chunk.bg)?" ":raw;if(!chunk.text.startsWith(text,textOffset))return!1;if(textOffset+=text.length,textOffset===chunk.text.length)chunkIndex++,textOffset=0;else if(textOffset>chunk.text.length)return!1}return chunkIndex===row.length&&textOffset===0}function wireXtermChannels(term,hooks){term.onData(hooks.onReply),term.onTitleChange(hooks.onTitle)}function wireXtermDefaultColorQueries(term,colors,reply){let resolved=parseTerminalDefaultColors(colors)??DEFAULT_TERMINAL_COLORS;for(let slot of[10,11])term.parser.registerOscHandler(slot,(payload)=>{if(payload!=="?")return!1;return reply(formatDefaultColorReply(slot,resolved)),!0})}class XtermRefreshTracker{dirty=null;subscription;supported;constructor(term){let event=term._core?._inputHandler?.onRequestRefreshRows;if(!event){this.supported=!1,this.subscription=null;return}this.supported=!0,this.subscription=event((range)=>{if(!range){this.dirty={kind:"all"};return}if(!this.dirty)this.dirty={kind:"range",start:range.start,end:range.end};else if(this.dirty.kind==="range")this.dirty.start=Math.min(this.dirty.start,range.start),this.dirty.end=Math.max(this.dirty.end,range.end)})}markAll(){this.dirty={kind:"all"}}peek(){return this.dirty}clear(){this.dirty=null}dispose(){this.subscription?.dispose()}}function snapshotMeta(active,viewportRows,scrollbackRows){return{type:active.type,baseY:active.baseY,length:active.length,start:Math.max(0,active.length-(viewportRows+scrollbackRows))}}function sameMeta(a2,b3){return a2.type===b3.type&&a2.baseY===b3.baseY&&a2.length===b3.length&&a2.start===b3.start}function dirtyRowsMatchSnapshot(active,snapshot,previousMeta,currentMeta,dirty,cursorHidden,frozen=null,styleRewrites){if(!previousMeta||!sameMeta(previousMeta,currentMeta)||!dirty)return!1;let first=currentMeta.start,last=currentMeta.length-1;if(dirty.kind==="range")first=Math.max(first,active.baseY+dirty.start),last=Math.min(last,active.baseY+dirty.end);let cursorY=active.baseY+active.cursorY;for(let y3=first;y3<=last;y3++){let row=snapshot[y3-currentMeta.start];if(!row)return!1;if(frozen&&y3<frozen.baseY&&frozen.cache.get(frozen.absBase+y3)===row)continue;let minLast=!cursorHidden&&y3===cursorY?active.cursorX-1:-1;if(!xtermLineMatchesChunks(active.getLine(y3),row,minLast,styleRewrites))return!1}return!0}function xtermSynchronizedOutput(term){try{return term.modes.synchronizedOutputMode===!0}catch{return!1}}function xtermCursorHidden(term){try{return term._core?.coreService?.isCursorHidden===!0}catch{return!1}}function sameFlags(previous,next){if(previous.length!==next.length)return!1;for(let i2=0;i2<next.length;i2++)if(previous[i2]!==next[i2])return!1;return!0}class XtermSnapshotEngine{alternateScreenStyleRewrites;scrollbackCache=new Map;wrappedCache=new Map;wrapped=[];anchor;anchorId=0;snapshotEpoch=0;publishedMeta=null;constructor(alternateScreenStyleRewrites){this.alternateScreenStyleRewrites=alternateScreenStyleRewrites}invalidate(){this.scrollbackCache.clear(),this.wrappedCache.clear(),this.wrapped=[],this.anchor?.dispose(),this.anchor=void 0,this.anchorId=0,this.publishedMeta=null}refresh(term,rows,scrollbackRows,refreshTracker,previousSnapshot,previousCursor,previousWindow){let active=term.buffer.active,styleRewrites=active.type==="alternate"?this.alternateScreenStyleRewrites:void 0,cursorHidden=xtermCursorHidden(term),currentMeta=snapshotMeta(active,rows,scrollbackRows),nextCursor=reconcileTerminalCursor(previousCursor,cursorHidden?null:{x:active.cursorX,y:active.baseY+active.cursorY-currentMeta.start}),verifyAnchor=this.anchor,verifyFrozen=active.type!=="alternate"&&verifyAnchor!==void 0&&!verifyAnchor.isDisposed?{baseY:active.baseY,absBase:this.anchorId-verifyAnchor.line,cache:this.scrollbackCache}:null;if(dirtyRowsMatchSnapshot(active,previousSnapshot,this.publishedMeta,currentMeta,refreshTracker.peek(),cursorHidden,verifyFrozen,styleRewrites))return refreshTracker.clear(),this.publishedMeta=currentMeta,{snapshot:previousSnapshot,cursor:nextCursor,snapshotWindow:previousWindow,wrapped:this.wrapped,changed:nextCursor!==previousCursor};if(xtermSynchronizedOutput(term))return null;let canAnchor=active.type!=="alternate"&&active.baseY>0;if(canAnchor&&(this.anchor===void 0||this.anchor.isDisposed)){this.scrollbackCache.clear(),this.wrappedCache.clear();let fresh=term.registerMarker(-active.cursorY-1);if(fresh)this.snapshotEpoch+=1,this.anchor=fresh,this.anchorId=fresh.line}let anchorAlive=canAnchor&&this.anchor!==void 0&&!this.anchor.isDisposed,absBase=anchorAlive?this.anchorId-this.anchor.line:0,cache=this.scrollbackCache,wrappedCache=this.wrappedCache,rowsOut=[],wrappedOut=[],cursorY=active.baseY+active.cursorY,start=currentMeta.start;for(let y3=start;y3<active.length;y3++){let frozen=anchorAlive&&y3<active.baseY;if(frozen){let cached=cache.get(absBase+y3);if(cached){rowsOut.push(cached),wrappedOut.push(wrappedCache.get(absBase+y3)??!1);continue}}let line=active.getLine(y3),minLast=!cursorHidden&&y3===cursorY?active.cursorX-1:-1,row=line?xtermLineToChunks(line,minLast,styleRewrites):[],wraps=y3>start&&line?.isWrapped===!0,stableRow=frozen?reconcileTerminalRow(previousSnapshot[rowsOut.length],row):row;if(rowsOut.push(stableRow),wrappedOut.push(wraps),frozen)cache.set(absBase+y3,stableRow),wrappedCache.set(absBase+y3,wraps)}if(anchorAlive){let min=absBase+start;for(let id of cache.keys())if(id<min)cache.delete(id);for(let id of wrappedCache.keys())if(id<min)wrappedCache.delete(id)}if(canAnchor){let next=term.registerMarker(-active.cursorY-1);if(next)this.anchorId=anchorAlive?absBase+next.line:0,this.anchor?.dispose(),this.anchor=next}let snapshot=reconcileTerminalRows(previousSnapshot,rowsOut),nextStartLine=absBase+start,snapshotWindow=anchorAlive?previousWindow?.epoch===this.snapshotEpoch&&previousWindow.startLine===nextStartLine?previousWindow:{epoch:this.snapshotEpoch,startLine:nextStartLine}:null;refreshTracker.clear(),this.publishedMeta=currentMeta;let wrapLayoutMoved=!sameFlags(this.wrapped,wrappedOut);if(wrapLayoutMoved)this.wrapped=wrappedOut;let changed=snapshot!==previousSnapshot||nextCursor!==previousCursor||snapshotWindow!==previousWindow||wrapLayoutMoved;return{snapshot,cursor:nextCursor,snapshotWindow,wrapped:this.wrapped,changed}}}var SNAPSHOT_COALESCE_MS=33;class XtermTaskPty{taskId;cwd;term;listeners=new PtyListeners;snapshot=[];cursor=null;snapshotWindow=null;snapshotWrapped=[];snapshotDirty=!1;snapshotEngine;_title=null;_unwatchedSince=Date.now();_killed=!1;muteReplies=!1;cols;rows;refreshQueued=!1;refreshTracker;scrollbackRows;constructor(opts,options={}){if(this.taskId=opts.taskId,this.cwd=opts.cwd,this.cols=opts.cols??DEFAULT_COLS,this.rows=opts.rows??DEFAULT_ROWS,opts.restore?.title)this._title=opts.restore.title;this.scrollbackRows=opts.scrollback??persistedScrollbackRows(),this.term=new import_headless.Terminal({allowProposedApi:!0,cols:this.cols,rows:this.rows,scrollback:this.scrollbackRows}),this.snapshotEngine=new XtermSnapshotEngine(opts.alternateScreenStyleRewrites),this.term.loadAddon(new Ke),this.term.unicode.activeVersion="11",this.refreshTracker=new XtermRefreshTracker(this.term);let reply=(data)=>{if(this._killed||this.muteReplies)return;try{this.transportWrite(data)}catch{}};if(wireXtermChannels(this.term,{onReply:reply,onTitle:(title)=>{if(!title||title===this._title)return;this._title=title,this.listeners.publishTitle(title)}}),options.respondToDefaultColorQueries!==!1)wireXtermDefaultColorQueries(this.term,opts.defaultColors,reply)}get killed(){return this._killed}write(data){if(this._killed||data.length===0)return;try{this.transportWrite(data)}catch{this.markDead(!1)}}inputModes(){try{return{applicationCursorKeys:this.term.modes.applicationCursorKeysMode===!0,applicationKeypad:this.term.modes.applicationKeypadMode===!0}}catch{return{applicationCursorKeys:!1,applicationKeypad:!1}}}onExit(cb){if(this._killed)return cb(),()=>{};return this.listeners.addExit(cb)}onTitleChange(cb){let off=this.listeners.addTitle(cb);if(this._title)try{cb(this._title)}catch{}return off}paste(text){if(this._killed||text.length===0)return;let bracketed=!1;try{bracketed=this.term.modes.bracketedPasteMode===!0}catch{}this.write(bracketed?`\x1B[200~${text}\x1B[201~`:text)}wheel(direction,col,row){if(this._killed)return!1;try{let modes=this.term.modes,seq=encodeWheel({mouseTracking:modes.mouseTrackingMode!=="none",applicationCursorKeys:modes.applicationCursorKeysMode===!0,alternateScreen:this.term.buffer.active.type==="alternate"},direction,col,row);if(seq!==null)return this.write(seq),!0}catch{}return!1}click(kind,button,col,row,modifiers){if(this._killed)return!1;try{let seq=encodeMouseButton({mouseTracking:this.term.modes.mouseTrackingMode},kind,button,col,row,modifiers);if(seq!==null)return this.write(seq),!0}catch{}return!1}get appOwnsMouse(){if(this._killed)return!1;try{return this.term.modes.mouseTrackingMode!=="none"}catch{return!1}}get onAlternateScreen(){if(this._killed)return!1;try{return this.term.buffer.active.type==="alternate"}catch{return!1}}onData(cb){this.ensureFreshSnapshot();let off=this.listeners.addData(cb);if(this._unwatchedSince=null,this.snapshot.length>0)try{cb(this.snapshot,this.cursor,this.snapshotWindow,this.snapshotWrapped)}catch{}return()=>{if(off(),this.listeners.dataCount===0&&this._unwatchedSince===null)this._unwatchedSince=Date.now()}}unwatchedSinceMs(){return this._unwatchedSince}get windowTitle(){return this._title}get scrollback(){return this.scrollbackRows}resizeEmulator(cols,rows){this.cols=cols,this.rows=rows,this.term.resize(cols,rows),this.invalidateScrollbackCache(),this.refreshTracker.markAll()}get size(){return{cols:this.cols,rows:this.rows}}resize(cols,rows){if(this._killed)return;this.cols=cols,this.rows=rows;try{this.term.resize(cols,rows),this.invalidateScrollbackCache(),this.transportResize(cols,rows),this.refreshTracker.markAll(),this.refreshSnapshot()}catch{this.markDead(!1)}}invalidateScrollbackCache(){this.snapshotEngine.invalidate(),this.snapshotWindow=null}capture(){return this.ensureFreshSnapshot(),this.snapshot}captureCursor(){return this.ensureFreshSnapshot(),this.cursor}captureWindow(){return this.ensureFreshSnapshot(),this.snapshotWindow}captureWrapped(){return this.ensureFreshSnapshot(),this.snapshotWrapped}ensureFreshSnapshot(){if(!this.snapshotDirty||this._killed)return;this.refreshSnapshot()}kill(){if(this._killed)return;this.markDead(!0)}feed(data){this.feedInternal(data,!1)}feedReplay(data){this.feedInternal(data,!0)}feedInternal(data,muteReplies){if(this._killed)return;if(muteReplies)this.muteReplies=!0;profileTick("feed"),this.term.write(data,()=>{if(muteReplies)this.muteReplies=!1;if(!this.refreshTracker.supported)this.refreshTracker.markAll();this.queueRefresh()})}queueRefresh(){if(this.listeners.dataCount===0){this.snapshotDirty=!0;return}if(this.refreshQueued)return;this.refreshQueued=!0,setTimeout(()=>{this.refreshQueued=!1,this.refreshSnapshot()},SNAPSHOT_COALESCE_MS)}refreshSnapshot(){if(this._killed)return;let result=profileSpan("refresh",()=>this.snapshotEngine.refresh(this.term,this.rows,this.scrollbackRows,this.refreshTracker,this.snapshot,this.cursor,this.snapshotWindow));if(result===null){this.queueRefresh();return}if(this.snapshot=result.snapshot,this.cursor=result.cursor,this.snapshotWindow=result.snapshotWindow,this.snapshotWrapped=result.wrapped,this.snapshotDirty=!1,result.changed)this.publishSnapshot()}publishSnapshot(){profileTick("publish"),this.listeners.publishData(this.snapshot,this.cursor,this.snapshotWindow,this.snapshotWrapped)}disposeEmulator(){try{this.term.dispose()}catch{}}markDead(killProcess){if(this._killed)return;if(this._killed=!0,this.refreshTracker.dispose(),this.disposeEmulator(),killProcess)try{this.transportKill()}catch{}let exitCbs=this.listeners.drainExits();this.listeners.clearData();for(let cb of exitCbs)try{cb()}catch{}}silentDispose(){this._killed=!0,this.refreshTracker.dispose(),this.disposeEmulator(),this.listeners.clearAll()}}var WIGGLE_MIN_GAP_MS=150;class HostedTaskPty extends XtermTaskPty{client=null;opened=!1;pendingInput=[];pendingResize=null;unsubs=[];deadOnAttach=!1;sessionPid=void 0;pendingExitPid=null;get shellPid(){return this.sessionPid??null}serializer=new D;hostOffset=null;constructor(opts){super(opts,{respondToDefaultColorQueries:!1});this.term.loadAddon(this.serializer),this.openRemote(opts)}static createdFresh(res){return res.alive&&(res.created??res.replay.length===0)}async openRemote(opts){try{let client=await getSharedPtyClient();if(this.killed)return;this.client=client,routeAdd(this),this.unsubs.push(client.onLifecycle("close",()=>this.remoteGone()));let res=await client.request("pty.open",{key:this.taskId,cwd:this.cwd,command:opts.command,shell:opts.shell,cols:this.cols,rows:this.rows,defaultColors:opts.defaultColors,sinceOffset:opts.restore?.byteOffset,sincePid:opts.restore?.pid??void 0});if(this.killed)return;this.sessionPid=res.pid??null,this.hostOffset=res.offset??null;let restored=opts.restore!==void 0&&res.sinceValid===!0&&res.created!==!0&&(res.pid??null)===opts.restore.pid;if(restored&&opts.restore){if(await this.restoreParked(opts.restore,Buffer.from(res.replay,"base64")),this.killed)return}else if(res.replay.length>0)this.feedReplay(Buffer.from(res.replay,"base64"));if(this.opened=!0,this.pendingResize){let{cols,rows}=this.pendingResize;this.pendingResize=null,this.sendResize(cols,rows)}let fresh=HostedTaskPty.createdFresh(res);if(opts.initialInput&&fresh)this.sendInput(opts.initialInput);if(opts.firstMessage&&fresh)pastePromptWhenEngineUp(client,this.taskId,opts.engineBin,opts.firstMessage).catch((err)=>logClientError("pty-hosted",err));for(let data of this.pendingInput.splice(0))this.sendInput(data);let parkedExitPid=this.pendingExitPid;if(this.pendingExitPid=null,!res.alive)this.deadOnAttach=res.replay.length>0||restored,this.remoteGone();else if(parkedExitPid!==null&&parkedExitPid===this.sessionPid)this.remoteGone();else if(res.replay.length>0&&!restored){if(this.sendResize(this.cols,Math.max(1,this.rows-1)),await Promise.all([this.nextDataOrTimeout(500),new Promise((r2)=>setTimeout(r2,WIGGLE_MIN_GAP_MS))]),!this.killed)this.sendResize(this.cols,this.rows)}}catch(err){logClientError("pty-hosted",err),this.remoteGone()}}transportWrite(data){if(!this.opened){this.pendingInput.push(data);return}this.sendInput(data)}transportResize(cols,rows){if(!this.opened){this.pendingResize={cols,rows};return}this.sendResize(cols,rows)}transportKill(){let client=this.client;if(client)client.request("pty.kill",{key:this.taskId}).catch(()=>{});this.cleanup()}kill(){if(this.killed){this.client?.request("pty.kill",{key:this.taskId}).catch(()=>{});return}super.kill()}capturePark(){if(this.killed||!this.opened||this.hostOffset===null||this.sessionPid===void 0)return null;try{return{serialized:Buffer.from(this.serializer.serialize({scrollback:this.scrollback}),"utf8").toString(),title:this.windowTitle,cursorHidden:xtermCursorHidden(this.term),cols:this.cols,rows:this.rows,byteOffset:this.hostOffset,pid:this.sessionPid}}catch{return null}}async restoreParked(state,delta){let targetCols=this.cols,targetRows=this.rows;if(state.cols!==targetCols||state.rows!==targetRows)this.resizeEmulator(state.cols,state.rows);if(this.feedReplay(state.serialized+(state.cursorHidden?"\x1B[?25l":"")),delta.byteLength>0)this.feedReplay(delta);if(await new Promise((resolve)=>{let off=this.onExit(resolve);this.term.write("",()=>{off(),resolve()})}),!this.killed&&(this.cols!==targetCols||this.rows!==targetRows))this.resizeEmulator(targetCols,targetRows)}detach(opts={}){let client=this.client;this.cleanup();let siblings=routeCount(this.taskId);if(client&&siblings===0)client.request("pty.detach",{key:this.taskId,parked:opts.parked===!0,parkedScreenBytes:opts.parkedScreenBytes}).catch(()=>{});this.silentDispose()}sendInput(data){this.client?.request("pty.write",{key:this.taskId,data}).catch(()=>this.remoteGone())}sendResize(cols,rows){this.client?.request("pty.resize",{key:this.taskId,cols,rows}).catch(()=>{})}dataWaiter=null;_lastOutputAt=null;lastOutputAtMs(){return this._lastOutputAt}nextDataOrTimeout(ms){return new Promise((resolve)=>{let timer=setTimeout(()=>{this.dataWaiter=null,resolve()},ms);this.dataWaiter=()=>{this.dataWaiter=null,clearTimeout(timer),resolve()}})}feedFrame(dataB64){this.dataWaiter?.(),this._lastOutputAt=Date.now();let buf=Buffer.from(dataB64,"base64");if(this.hostOffset!==null)this.hostOffset+=buf.byteLength;this.feed(buf)}remoteExited(pid){if(this.killed)return;if(pid===void 0){this.remoteGone();return}if(this.sessionPid===void 0){this.pendingExitPid=pid;return}if(pid!==null&&pid===this.sessionPid)this.remoteGone()}remoteGone(){this.cleanup(),this.markDead(!1)}cleanup(){routeRemove(this);for(let unsub of this.unsubs.splice(0))try{unsub()}catch{}}}class MockTaskPty{taskId;cwd;listeners=new Set;buffer="";writes=[];_killed=!1;_title=null;exitListeners=new Set;titleListeners=new Set;pastes=[];deadOnAttach=!1;wheels=[];clicks=[];appOwnsMouse=!1;onAlternateScreen=!1;_cols;_rows;_cursor=null;modes={applicationCursorKeys:!1,applicationKeypad:!1};constructor(opts){if(this.taskId=opts.taskId,this.cwd=opts.cwd,this._cols=opts.cols??DEFAULT_COLS,this._rows=opts.rows??DEFAULT_ROWS,opts.initialInput)this.writes.push(opts.initialInput)}get killed(){return this._killed}get writeLog(){return this.writes}get geometry(){return{cols:this._cols,rows:this._rows}}feed(data){if(this._killed)return;this.buffer+=data;let title=extractOscTitle(data);if(title&&title!==this._title){this._title=title;for(let cb of this.titleListeners)try{cb(title)}catch{}}let rows=this.capture();for(let cb of this.listeners)try{cb(rows,this._cursor,null)}catch{}}write(data){if(this._killed)return;this.writes.push(data)}inputModes(){return this.modes}replaceScreen(data){if(this._killed)return;this.buffer="",this.feed(data)}onData(cb){if(this.listeners.add(cb),this.buffer!=="")try{cb(this.capture(),this._cursor,null)}catch{}return()=>{this.listeners.delete(cb)}}resize(cols,rows){if(this._killed)return;this._cols=cols,this._rows=rows}capture(){return parseAnsiSnapshot(this.buffer)}setCursor(pos){this._cursor=pos}captureCursor(){if(this._killed)return null;return this._cursor}captureWindow(){return null}kill(){if(this._killed)return;this._killed=!0,this.listeners.clear();let exitCbs=[...this.exitListeners];this.exitListeners.clear();for(let cb of exitCbs)cb()}paste(text){if(this._killed)return;this.pastes.push(text)}wheel(direction,col,row){if(this._killed)return!1;return this.wheels.push({direction,col,row}),!1}click(kind,button,col,row){if(this._killed)return!1;return this.clicks.push({kind,button,col,row}),this.appOwnsMouse}onExit(cb){if(this._killed)return cb(),()=>{};return this.exitListeners.add(cb),()=>{this.exitListeners.delete(cb)}}onTitleChange(cb){if(this.titleListeners.add(cb),this._title)try{cb(this._title)}catch{}return()=>{this.titleListeners.delete(cb)}}}import{spawn}from"child_process";class PipeTaskPty{taskId;cwd;proc;listeners=new Set;buffer="";_killed=!1;_title=null;exitListeners=new Set;titleListeners=new Set;cols;rows;constructor(opts){this.taskId=opts.taskId,this.cwd=opts.cwd,this.cols=opts.cols??DEFAULT_COLS,this.rows=opts.rows??DEFAULT_ROWS;let argv=resolveArgv(opts),exe=argv[0]??defaultShell(),args=argv.slice(1);if(this.proc=spawn(exe,args,{cwd:opts.cwd,env:embeddedTerminalEnv(process.env,{TERM:process.env.TERM??"xterm-256color",COLUMNS:String(this.cols),LINES:String(this.rows),KOBE_TERMINAL_PIPE:"1"}),stdio:["pipe","pipe","pipe"]}),this.proc.stdout?.setEncoding("utf8"),this.proc.stderr?.setEncoding("utf8"),this.proc.stdout?.on("data",(chunk)=>this.append(chunk)),this.proc.stderr?.on("data",(chunk)=>this.append(chunk)),this.proc.stdin?.on("error",()=>this.markDead(!1)),this.proc.on("error",(err)=>{this.append(`
@@ -17,7 +17,7 @@ ${refs}`}async function capture(cmd){try{let proc=Bun.spawn(cmd,{stdin:"ignore",
17
17
  `).filter((l2)=>l2.length>0);attachUntrackedChildren(merged,others)}catch{}let untracked=[];for(let e2 of merged){if(e2.status!=="?")continue;if(e2.children)untracked.push(...e2.children);else if(e2.added==null&&!e2.path.endsWith("/"))untracked.push(e2)}if(untracked.length>0)await Promise.all(untracked.map(async(e2)=>{let added=await countAddedLines(worktreePath,e2.path,signal);if(added!=null)e2.added=added,e2.deleted=0}));for(let e2 of merged){if(!e2.children)continue;let sum=0,counted=!1;for(let c2 of e2.children)if(c2.added!=null)sum+=c2.added,counted=!0;if(counted)e2.added=sum,e2.deleted=0}return merged}function isUntrackedDir(e2){return e2.status==="?"&&e2.path.endsWith("/")}function attachUntrackedChildren(entries,others){for(let e2 of entries){if(!isUntrackedDir(e2))continue;e2.children=others.filter((p3)=>p3.startsWith(e2.path)).map((p3)=>({path:p3,status:"?"}))}}async function resolveBase(worktreePath,prBaseRef,signal){if(prBaseRef&&prBaseRef.trim().length>0)return prBaseRef.trim();try{let head2=(await runGit(["symbolic-ref","--short","refs/remotes/origin/HEAD"],worktreePath,signal)).trim();if(head2.length>0)return head2}catch{}for(let guess of["origin/main","origin/master"])try{return await runGit(["rev-parse","--verify","--quiet",guess],worktreePath,signal),guess}catch{}let head=await revParse("HEAD",worktreePath,signal);for(let guess of["main","master"]){let sha=await revParse(guess,worktreePath,signal);if(sha!=null&&sha!==head)return guess}return null}async function revParse(ref,worktreePath,signal){try{let out=(await runGit(["rev-parse","--verify","--quiet",ref],worktreePath,signal)).trim();return out.length>0?out:null}catch{return null}}async function statusFilesBranch(worktreePath,base,signal){let range=`${base}...HEAD`,[nameStatusOut,numstatOut]=await Promise.all([runGit(["diff","--no-color","--name-status",range],worktreePath,signal),runGit(["diff","--no-color","--numstat","-z",range],worktreePath,signal)]),counts2=new Map(parseNumstat(numstatOut).map((n2)=>[n2.path,{added:n2.added,deleted:n2.deleted}])),entries=[];for(let{status,path}of parseNameStatus(nameStatusOut)){let c2=counts2.get(path);entries.push({path,status,added:c2?.added,deleted:c2?.deleted})}return entries}function parseNameStatus(raw){let out=[];for(let rawLine of raw.split(`
18
18
  `)){let line=rawLine.replace(/\r$/,"");if(line.length===0)continue;let tab1=line.indexOf("\t");if(tab1<0)continue;let code=line[0],path;if(code==="R"||code==="C"){let tab2=line.indexOf("\t",tab1+1);path=unquoteGitPath(tab2<0?line.slice(tab1+1):line.slice(tab2+1))}else path=unquoteGitPath(line.slice(tab1+1));if(path.length===0||path.endsWith("/"))continue;let status=code==="M"||code==="A"||code==="D"||code==="T"?code:code==="R"?"R":code==="C"?"C":null;if(status)out.push({status,path})}return out}async function countAddedLines(worktreePath,relPath,signal){if(signal?.aborted)return null;let text=await readWorktreeFile(worktreePath,relPath);if(text==null)return null;if(text.includes("\x00"))return null;if(text.length===0)return 0;let count=0;for(let i2=0;i2<text.length;i2++)if(text[i2]===`
19
19
  `)count++;if(!text.endsWith(`
20
- `))count++;return count}function parseNumstat(raw){return parseNumstatRows(raw).map((r2)=>({path:r2.path,added:r2.added,deleted:r2.deleted}))}function parseStatusEntries(raw){let out=[];for(let row of parsePorcelainRows(raw)){let status;if(row.x==="?"&&row.y==="?")status="?";else{let candidate=row.y!==" "?row.y:row.x;if(candidate==="M"||candidate==="A"||candidate==="D"||candidate==="R"||candidate==="C"||candidate==="U"||candidate==="T")status=candidate;else continue}let path=row.path;if(path.length===0)continue;if(path.endsWith("/")&&status!=="?")continue;out.push({path,status})}return out}var TAB_ORDER=["all","changes"];function tabLabelKey(tab){switch(tab){case"all":return"files.tabs.all";case"changes":return"files.tabs.changes"}}function fileTreeBindings(opts){return bindByIds({"files.nav":(_evt,slot)=>{if((slot??0)%2===0)opts.moveDown();else opts.moveUp()},"files.hierarchy":(_evt,slot)=>{if((slot??0)%2===0)opts.collapseOrParent();else opts.expandOrDescend()},"files.tab":(_evt,slot)=>{let cur=opts.currentTab(),idx=TAB_ORDER.indexOf(cur);if(idx<0)return;let delta=(slot??0)%2===0?-1:1,next=TAB_ORDER[(idx+delta+TAB_ORDER.length)%TAB_ORDER.length];if(next)opts.setTab(next)},"files.open":()=>opts.openCurrent(),"files.mention":()=>opts.mentionCurrent?.(),"files.openExternal":()=>opts.openExternal(),"files.refresh":()=>opts.refresh(),"files.scope":()=>opts.toggleScope?.(),"files.diff":()=>opts.openDiff?.(),"files.diffAll":()=>opts.openDiffAll?.()})}import{spawn as spawn3}from"child_process";import{existsSync as existsSync2}from"fs";import{platform}from"os";function openExternally(absPath){if(!absPath)return;let plat=platform();if(plat==="linux"){if(existsSync2("/proc/sys/fs/binfmt_misc/WSLInterop")||process.env.WSL_DISTRO_NAME){spawnDetachedWithFallback("wslview",[absPath],()=>{let child=spawn3("wslpath",["-w",absPath],{stdio:["ignore","pipe","ignore"]}),out="";child.stdout?.on("data",(b3)=>{out+=b3.toString()}),child.on("close",(code)=>{if(code===0)spawnDetachedWithFallback("explorer.exe",[out.trim()])})});return}spawnDetachedWithFallback("xdg-open",[absPath]);return}if(plat==="darwin"){spawnDetachedWithFallback("open",[absPath]);return}if(plat==="win32"){spawnDetachedWithFallback("cmd.exe",["/c","start","",absPath]);return}}function spawnDetachedWithFallback(cmd,args,onError){spawnDetached(cmd,args,{onError:onError?()=>onError():void 0})}import{watch}from"fs";function statusToken(s2){switch(s2){case"M":return"warning";case"A":return"success";case"D":return"error";case"?":return"textMuted";case"R":case"C":case"U":case"T":return"info"}}function summarizeGitError(raw,t3){let kind=classifyGitError(raw);if(kind)return t3(`files.error.${kind}`);let colon=raw.indexOf(": ");if(colon>=0&&raw.startsWith("git "))return raw.slice(colon+2).trim()||t3("files.error.gitFailed");return raw.trim()||t3("files.error.gitFailed")}function classifyGitError(raw){let m3=raw.toLowerCase();if(m3.includes("not a git repository"))return"notGitRepo";if(m3.includes("does not exist")||m3.includes("enoent"))return"pathMissing";if(m3.includes("permission denied")||m3.includes("eacces"))return"permissionDenied";if(m3.includes("git: not found")||m3.includes("command not found"))return"gitNotInstalled";return null}function gitErrorIsRetryable(raw){let kind=classifyGitError(raw);return kind!=="notGitRepo"&&kind!=="gitNotInstalled"}function computeStatWidths(rows){let added=0,deleted=0;for(let row of rows){if(row.kind!=="status")continue;if(row.added!=null)added=Math.max(added,String(row.added).length+1);if(row.deleted!=null)deleted=Math.max(deleted,String(row.deleted).length+1)}return{added,deleted}}function computePathBudget(paneWidth,w3){let stats=(w3.added>0?w3.added+1:0)+(w3.deleted>0?w3.deleted+1:0);return Math.max(8,paneWidth-6-stats)}function statCell(value,width,sign){let glyph=sign==="-"?"\u2212":sign;return value==null?" ".repeat(width):`${glyph}${value}`.padStart(width)}function toggleDir(expanded,path){let next=new Set(expanded);if(next.has(path))next.delete(path);else next.add(path);return next}function expandOrDescendAction(rows,cursorIndex){let row=rows[cursorIndex];if(!row)return null;if(row.kind==="status"){if(row.fileCount==null)return null;if(!row.expanded)return{type:"expand",path:row.path};return cursorIndex+1<rows.length?{type:"cursor",index:cursorIndex+1}:null}if(row.kind!=="dir")return null;if(!row.expanded&&row.hasChildren)return{type:"expand",path:row.path};if(row.expanded&&cursorIndex+1<rows.length)return{type:"cursor",index:cursorIndex+1};return null}function collapseOrParentAction(rows,cursorIndex){let row=rows[cursorIndex];if(!row)return null;if(row.kind==="dir"&&row.expanded)return{type:"collapse",path:row.path};if(row.kind==="status")return row.fileCount!=null&&row.expanded?{type:"collapse",path:row.path}:null;if(row.kind!=="dir"&&row.kind!=="file")return null;let targetDepth=row.depth-1;if(targetDepth<0)return null;for(let j2=cursorIndex-1;j2>=0;j2--){let candidate=rows[j2];if(!candidate)continue;if(candidate.kind==="dir"&&candidate.depth===targetDepth)return{type:"cursor",index:j2}}return null}function followScrollTop(scrollTop,viewportHeight,cursorIndex){if(viewportHeight<=0)return null;if(cursorIndex<scrollTop)return cursorIndex;if(cursorIndex>=scrollTop+viewportHeight)return cursorIndex-viewportHeight+1;return null}function watchEventRelevant(filename){if(filename===".git"||filename.startsWith(".git/")||filename.startsWith(".git\\"))return!1;if(filename.startsWith("node_modules/")||filename.startsWith("node_modules\\"))return!1;return!0}function watchWorktree(path,onChange,debounceMs=500){let debounceTimer=null,watcher=null;try{watcher=watch(path,{recursive:!0},(_event,filename)=>{if(filename==null)return;if(!watchEventRelevant(filename.toString()))return;if(debounceTimer!=null)clearTimeout(debounceTimer);debounceTimer=setTimeout(()=>{debounceTimer=null,onChange()},debounceMs)}),watcher.on("error",()=>{})}catch{}return()=>{if(debounceTimer!=null)clearTimeout(debounceTimer);if(watcher!=null)watcher.close()}}function reconcileStableRows(prev,next,keyOf,equals,opts={}){if(prev.length===0)return next;let prevByKey=new Map;for(let row of prev)prevByKey.set(keyOf(row),row);let allReused=prev.length===next.length,out=Array(next.length);for(let i2=0;i2<next.length;i2++){let fresh=next[i2],old=prevByKey.get(keyOf(fresh));if(old&&equals(old,fresh)&&(!opts.samePosition||prev[i2]===old)){if(out[i2]=old,allReused&&prev[i2]!==old)allReused=!1}else out[i2]=fresh,allReused=!1}return allReused?prev:out}function flattenTree(node,expanded,depth,out){for(let child of node.children)if(child.isDir){let isOpen=expanded.has(child.path);if(out.push({kind:"dir",path:child.path,name:child.name,depth,expanded:isOpen,hasChildren:child.children.length>0}),isOpen)flattenTree(child,expanded,depth+1,out)}else out.push({kind:"file",path:child.path,name:child.name,depth})}function truncatePathTail(path,maxCells){return truncateStartCells(path,maxCells,charWidth)}var NO_EXPANSION=new Set;function statusRows(entries,expanded=NO_EXPANSION){let out=[];for(let e2 of entries){if(e2.children==null){out.push({kind:"status",path:e2.path,status:e2.status,added:e2.added,deleted:e2.deleted});continue}let isOpen=expanded.has(e2.path);if(out.push({kind:"status",path:e2.path,status:e2.status,added:e2.added,deleted:e2.deleted,fileCount:e2.children.length,expanded:isOpen}),isOpen)for(let c2 of e2.children)out.push({kind:"status",path:c2.path,status:c2.status,added:c2.added,deleted:c2.deleted,child:!0})}return out}function rowKey(row){return`${row.kind}\x00${row.path}`}function rowEquals(a2,b3){if(a2.kind!==b3.kind||a2.path!==b3.path)return!1;switch(a2.kind){case"file":{let o2=b3;return a2.name===o2.name&&a2.depth===o2.depth}case"dir":{let o2=b3;return a2.name===o2.name&&a2.depth===o2.depth&&a2.expanded===o2.expanded&&a2.hasChildren===o2.hasChildren}case"status":{let o2=b3;return a2.status===o2.status&&a2.added===o2.added&&a2.deleted===o2.deleted&&a2.fileCount===o2.fileCount&&a2.expanded===o2.expanded&&a2.child===o2.child}}}function reconcileRows(prev,next){return reconcileStableRows(prev,next,rowKey,rowEquals)}function sameFileList(a2,b3){if(a2===b3)return!0;if(a2==null||b3==null)return!1;if(a2.length!==b3.length)return!1;for(let i2=0;i2<a2.length;i2++)if(a2[i2]!==b3[i2])return!1;return!0}function sameStatusEntries(a2,b3){if(a2===b3)return!0;if(a2==null||b3==null)return!1;if(a2.length!==b3.length)return!1;for(let i2=0;i2<a2.length;i2++){let x2=a2[i2],y3=b3[i2];if(x2.path!==y3.path||x2.status!==y3.status||x2.added!==y3.added||x2.deleted!==y3.deleted)return!1;let xc=x2.children,yc=y3.children;if(xc==null!==(yc==null))return!1;if(xc&&yc){if(xc.length!==yc.length)return!1;for(let j2=0;j2<xc.length;j2++){let cx=xc[j2],cy=yc[j2];if(cx.path!==cy.path||cx.status!==cy.status||cx.added!==cy.added||cx.deleted!==cy.deleted)return!1}}}return!0}function buildTree(paths){let root={name:"",path:"",isDir:!0,children:[]},indexes=new Map;for(let p3 of paths){if(!p3)continue;let segs=p3.split("/").filter((s2)=>s2.length>0);if(segs.length===0)continue;let cur=root;for(let i2=0;i2<segs.length;i2++){let seg=segs[i2],isDir=i2!==segs.length-1,index=indexes.get(cur);if(!index)index=new Map,indexes.set(cur,index);let key=`${isDir?"d":"f"}:${seg}`,child=index.get(key);if(!child)child={name:seg,path:segs.slice(0,i2+1).join("/"),isDir,children:[]},cur.children.push(child),index.set(key,child);cur=child}}return sortTree(root),root}function sortTree(node){node.children.sort((a2,b3)=>{if(a2.isDir!==b3.isDir)return a2.isDir?-1:1;return a2.name.localeCompare(b3.name)});for(let c2 of node.children)sortTree(c2)}var import_react29=__toESM(require_react_production(),1);var import_react28=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes7}from"@opentui/core";function displayCap(cap){return cap.split(" + ").map((part)=>formatChord(part)).join(" + ")}function sectionTitle(section,t3){if(section.kind==="here")return t3("help.here",{surface:tKeys("category",scopeCategory(section.scope))});if(section.kind==="direct")return t3("help.direct");if(section.kind==="prefix")return t3("help.afterPrefix");return t3("help.otherPane",{surface:tKeys("category",scopeCategory(section.scope))})}function HelpDialog(props){let dialog=useDialog(),{theme}=useTheme(),t3=useT(),padX=useDialogPaddingX(),keymapVersion2=useKeymapVersion(),pureTuiPrefix=currentPrefixConfiguration(),sections=import_react28.useMemo(()=>grammarHelpSections(KobeKeymap,props.currentScope??null,pureTuiPrefix.key,props.reachability),[keymapVersion2,props.currentScope,props.reachability,pureTuiPrefix.key]),close=()=>props.onClose?props.onClose():dialog.clear(),scrollRef=import_react28.useRef(null),scrollBy=(lines)=>{let scroll=scrollRef.current;if(!scroll)return;scroll.scrollTo({x:0,y:Math.max(0,scroll.scrollTop+lines)})},scrollToEdge=(edge)=>{let scroll=scrollRef.current;if(!scroll)return;scroll.scrollTo({x:0,y:edge==="top"?0:Number.MAX_SAFE_INTEGER})};return useBindings(()=>({bindings:[{key:"?",cmd:close},{key:"up",cmd:()=>scrollBy(-1)},{key:"down",cmd:()=>scrollBy(1)},{key:"pageup",cmd:()=>scrollBy(-(scrollRef.current?.viewport.height??10))},{key:"pagedown",cmd:()=>scrollBy(scrollRef.current?.viewport.height??10)},{key:"home",cmd:()=>scrollToEdge("top")},{key:"end",cmd:()=>scrollToEdge("bottom")}]})),$jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:1,flexShrink:1,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",flexShrink:0,children:[$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{attributes:TextAttributes7.BOLD,fg:theme.text,children:t3("help.title")}),$jsx("text",{fg:theme.textMuted,children:props.currentScope?t3("help.focused",{surface:tKeys("category",scopeCategory(props.currentScope))}):t3("help.allBindings")}),$jsx("text",{fg:theme.textMuted,children:t3("help.grammar",{prefix:pureTuiPrefix.key?formatChord(pureTuiPrefix.key):t3("help.disabled")})})]}),$jsxs("box",{flexDirection:"row",gap:2,flexShrink:0,children:[$jsx("text",{fg:theme.textMuted,attributes:TextAttributes7.DIM,children:t3("help.scrollKeys")}),$jsx("text",{fg:theme.textMuted,onMouseUp:close,children:t3("help.esc")})]})]}),$jsx("scrollbox",{ref:(r2)=>{scrollRef.current=r2},flexShrink:1,flexGrow:1,stickyScroll:!1,verticalScrollbarOptions:{trackOptions:{backgroundColor:theme.backgroundDialog,foregroundColor:theme.borderActive}},children:$jsx("box",{paddingBottom:1,gap:1,paddingRight:1,children:sections.map((section,sectionIndex)=>$jsxs("box",{gap:0,children:[$jsx("text",{fg:theme.accent,attributes:TextAttributes7.BOLD,children:sectionTitle(section,t3)}),section.rows.map((row)=>{return $jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,children:[$jsx("box",{width:18,children:$jsx("text",{fg:theme.primary,children:displayCap(row.primary)})}),$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.text,children:tKeys("desc",row.binding.id)})}),row.aliases.length>0?$jsx("box",{children:$jsx("text",{fg:theme.textMuted,children:`(${row.aliases.map(displayCap).join(", ")})`})}):null]},`${section.kind}-${row.binding.id}`)})]},`${section.kind}-${section.scope??sectionIndex}`))})})]})}HelpDialog.show=(dialog,currentScope)=>{let reachability=currentBindingReachability(),inputScope=reachability.inputPassthrough?"terminal":currentScope;dialog.replace(()=>$jsx(HelpDialog,{currentScope:inputScope,reachability}))};function useStatusKeyHintItems(opts){let t3=useT(),kv=useOptionalKV(),focus=useOptionalFocus(),dialog=useOptionalDialog(),keymapVersion2=useKeymapVersion(),stackVersion=useBindingStackVersion(),hintsEnabled=keyHintsEnabled(kv?.get(KEY_HINTS_ENABLED_KEY,!0)),[snapshot,setSnapshot]=import_react29.useState({tokens:[],modal:!1});import_react29.useEffect(()=>{let enabled=hintsEnabled,nextModal=modalActive()||(dialog?.stack.length??0)>0,fresh=enabled&&!nextModal?statusHintTokens(currentBindingReachability(),currentPrefixConfiguration().key):null;setSnapshot((prev)=>{let nextTokens=fresh??(enabled?prev.tokens:[]);return prev.modal===nextModal&&prev.tokens.length===nextTokens.length&&prev.tokens.every((tok,i2)=>tok.chord===nextTokens[i2]?.chord&&tok.msg===nextTokens[i2]?.msg)?prev:{tokens:nextTokens,modal:nextModal}})},[keymapVersion2,stackVersion,focus?.focused,dialog?.stack.length,hintsEnabled]);let actions=snapshot.modal?{commands:void 0,sidebar:void 0,help:void 0}:{commands:()=>void armPrefixFromCurrentStack(),sidebar:focus?()=>focus.setFocused("sidebar"):void 0,help:dialog?()=>HelpDialog.show(dialog,focus?.focused??"sidebar"):void 0},items=snapshot.tokens.map((tok)=>({text:opts?.compact?formatChord(tok.chord):t3(`hints.status.${tok.msg}`,{key:formatChord(tok.chord)}),onPress:actions[tok.msg]}));if(opts?.onOpenSettings&&!opts.compact&&hintsEnabled)items.push({text:`[${t3("hints.status.settings")}]`,bindingId:"settings.open",onPress:snapshot.modal?void 0:opts.onOpenSettings});return items}function StatusKeyHintBar(props){let{theme}=useTheme(),items=useStatusKeyHintItems({onOpenSettings:props.onOpenSettings,compact:props.compact});if(items.length===0)return null;return $jsx("box",{flexDirection:"row",flexShrink:0,children:items.flatMap((item,index)=>[index>0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:" \xB7 "},`sep-${item.text}`):null,$jsxs("box",{position:"relative",onMouseUp:item.onPress,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:item.text}),item.bindingId?$jsx(ShortcutRevealBadge,{bindingId:item.bindingId,cover:!0}):null]},item.text)])})}function usePaneHintMark(pane){let kv=useOptionalKV();return import_react29.useCallback(()=>{if(!kv)return;if(kv.get(PANE_HINT_USED_KEYS[pane],!1)!==!0)kv.set(PANE_HINT_USED_KEYS[pane],!0)},[kv,pane])}function PaneKeyHint(props){let t3=useT(),{theme}=useTheme(),kv=useOptionalKV();useKeymapVersion();let enabledRaw=kv?.get(KEY_HINTS_ENABLED_KEY,!0),usedRaw=kv?.get(PANE_HINT_USED_KEYS[props.pane],!1);if(!keyHintsEnabled(enabledRaw))return null;let tokens=paneHintTokens(props.pane,paneHintVisible(enabledRaw,usedRaw)?"firstUse":"always");if(tokens.length===0)return null;return $jsx("text",{fg:theme.textMuted,wrapMode:"none",children:tokens.map((tok)=>`${formatChord(tok.cap)} ${t3(`hints.pane.${tok.msg}`)}`).join(" \xB7 ")})}var import_react33=__toESM(require_react_production(),1);var import_react30=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes8}from"@opentui/core";var FileTreeRowView=import_react30.memo(function(props){let{theme}=useTheme(),selection=resolveRowSelectionChrome(theme,{cursor:props.cursor}),bar=$jsx("text",{fg:selection.markerColor,wrapMode:"none",children:selection.marker}),rowBg=selection.backgroundColor,row=props.row;if(row.kind==="dir"){let indent2=" ".repeat(row.depth);return $jsxs("box",{flexDirection:"row",gap:0,backgroundColor:rowBg,onMouseUp:()=>props.onActivate(props.row,props.index),children:[bar,$jsx("box",{flexGrow:1,paddingRight:1,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes8.BOLD,wrapMode:"none",children:`${indent2}${row.expanded?"\u25BE":"\u25B8"} ${row.name}/`})})]})}if(row.kind==="file"){let indent2=" ".repeat(row.depth);return $jsxs("box",{flexDirection:"row",gap:0,backgroundColor:rowBg,onMouseUp:()=>props.onActivate(props.row,props.index),children:[bar,$jsx("box",{flexGrow:1,paddingRight:1,children:$jsx("text",{fg:theme.text,wrapMode:"none",children:`${indent2} ${row.name}`})})]})}let isUntrackedDir2=row.fileCount!==void 0,marker=isUntrackedDir2?row.expanded?"\u25BE ":"\u25B8 ":"",countSuffix=isUntrackedDir2?` (${row.fileCount})`:"",indent=row.child?" ":"",pathBudget=props.pathBudget-displayWidth(marker)-displayWidth(countSuffix)-displayWidth(indent),tone=statusToken(row.status),statusColor=tone==="success"?theme.success:tone==="warning"?theme.warning:tone==="error"?theme.error:tone==="info"?theme.info:theme.textMuted;return $jsxs("box",{flexDirection:"row",gap:0,backgroundColor:rowBg,onMouseUp:()=>props.onActivate(props.row,props.index),children:[bar,$jsxs("box",{flexDirection:"row",flexGrow:1,gap:1,paddingRight:1,children:[$jsx("text",{fg:statusColor,wrapMode:"none",children:row.status}),$jsx("text",{fg:isUntrackedDir2?theme.textMuted:theme.text,wrapMode:"none",flexGrow:1,children:`${indent}${marker}${truncatePathTail(row.path,pathBudget)}${countSuffix}`}),props.statWidths.added>0?$jsx("text",{fg:theme.success,wrapMode:"none",children:statCell(row.added,props.statWidths.added,"+")}):null,props.statWidths.deleted>0?$jsx("text",{fg:theme.error,wrapMode:"none",children:statCell(row.deleted,props.statWidths.deleted,"-")}):null]})]})});var import_react32=__toESM(require_react_production(),1);function rowWindowRange(top,height,rowCount){if(rowCount<=0)return{start:0,end:0};if(height<=0)return{start:0,end:Math.min(rowCount,64)};let end=Math.min(rowCount,Math.ceil(top+height)+16);return{start:Math.max(0,Math.min(Math.floor(top)-16,end-1)),end}}function useRowWindow(opts){let{scrollEl,rowCount}=opts,renderer=useRenderer(),[view,setView]=import_react32.useState({top:0,height:0}),sample=import_react32.useCallback(()=>{if(!scrollEl||scrollEl.isDestroyed)return;let top=scrollEl.scrollTop,height=scrollEl.viewport.height;setView((cur)=>cur.top===top&&cur.height===height?cur:{top,height})},[scrollEl]);import_react32.useEffect(()=>{if(!renderer)return;return sample(),renderer.on("frame",sample),()=>{renderer.off("frame",sample)}},[renderer,sample]);let{start,end}=rowWindowRange(view.top,view.height,rowCount);return{start,end,sample}}function FileTreeBodyView(props){let{theme}=useTheme(),t3=useT(),{rows,cursorIndex}=props,[scrollEl,setScrollEl]=import_react33.useState(null),rowWindow=useRowWindow({scrollEl,rowCount:rows.length}),rowCount=rows.length,sample=rowWindow.sample;return import_react33.useEffect(()=>{if(!scrollEl||rowCount===0)return;let y3=followScrollTop(scrollEl.scrollTop,scrollEl.viewport.height,cursorIndex);if(y3!=null)scrollEl.scrollTo({x:0,y:y3});sample()},[cursorIndex,rowCount,scrollEl,sample]),$jsx("scrollbox",{ref:setScrollEl,flexGrow:1,verticalScrollbarOptions:{trackOptions:{foregroundColor:"transparent"}},children:props.worktreePath==null?$jsx("box",{paddingTop:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:t3("files.empty.noTask")})}):props.error!=null?$jsxs("box",{paddingTop:1,paddingLeft:1,flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.error,wrapMode:"word",children:summarizeGitError(props.error,t3)}),gitErrorIsRetryable(props.error)?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("files.error.retryHint")}):null]}):rows.length===0&&props.loaded?$jsx("box",{paddingTop:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:props.tab==="all"?t3("files.empty.noFiles"):t3("files.empty.noChanges")})}):rows.length>0?$jsxs("box",{flexShrink:0,gap:0,paddingRight:1,children:[rowWindow.start>0?$jsx("box",{flexShrink:0,height:rowWindow.start}):null,rows.slice(rowWindow.start,rowWindow.end).map((row,offset)=>{let index=rowWindow.start+offset;return $jsx(FileTreeRowView,{row,index,cursor:index===cursorIndex,statWidths:props.statWidths,pathBudget:props.pathBudget,onActivate:props.onActivate},`${row.kind}:${row.path}`)}),rows.length>rowWindow.end?$jsx("box",{flexShrink:0,height:rows.length-rowWindow.end}):null]}):null})}import{TextAttributes as TextAttributes9}from"@opentui/core";function FileTreeHeaderView(props){let{theme}=useTheme(),t3=useT(),prefixKey=currentPrefixConfiguration().key,createPRChord=prefixKey?`[${formatChord(prefixKey)} P]`:null,zenStroke=findBinding("workspace.zenToggle")?.prefixKeys?.[0],zenChord=prefixKey&&zenStroke?`[${formatChord(prefixKey)} ${zenStroke.toUpperCase()}]`:null;return $jsxs($Fragment,{children:[props.onZenToggle||props.onCreatePR?$jsxs("box",{flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-end",columnGap:2,paddingBottom:1,flexShrink:0,children:[props.onZenToggle?$jsxs("box",{position:"relative",flexDirection:"row",gap:1,flexShrink:0,onMouseUp:(e2)=>{e2.stopPropagation(),props.onZenToggle?.()},children:[zenChord?$jsx("text",{fg:theme.accent,attributes:TextAttributes9.BOLD,wrapMode:"none",children:zenChord}):null,$jsx("text",{fg:theme.text,wrapMode:"none",children:t3("files.actions.zen")}),$jsx(ShortcutRevealBadge,{bindingId:"workspace.zenToggle"})]}):null,props.onCreatePR?$jsxs("box",{flexDirection:"row",gap:1,flexShrink:0,onMouseUp:(e2)=>{e2.stopPropagation(),props.onCreatePR?.()},children:[createPRChord?$jsxs("box",{position:"relative",children:[$jsx("text",{fg:theme.accent,attributes:TextAttributes9.BOLD,wrapMode:"none",children:createPRChord}),$jsx(ShortcutRevealBadge,{bindingId:"files.createPR",cover:!0})]}):null,$jsx("text",{fg:theme.text,wrapMode:"none",children:t3("files.actions.createPR")})]}):null]}):null,$jsx("box",{flexDirection:"row",paddingBottom:0,flexShrink:0,gap:2,children:TAB_ORDER.map((tabId)=>{let isActive=props.tab===tabId;return $jsx("text",{fg:isActive?theme.primary:theme.textMuted,attributes:isActive?TextAttributes9.BOLD:void 0,wrapMode:"none",onMouseUp:()=>props.onSelectTab(tabId),children:t3(tabLabelKey(tabId))},tabId)})}),props.tab==="changes"?$jsxs("box",{flexDirection:"column",paddingBottom:1,flexShrink:0,gap:0,children:[$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:[props.scope==="branch"&&props.base!=null?t3("files.scope.branch",{base:props.base}):t3("files.scope.working"),props.base!=null?` ${t3("files.scope.toggleHint")}`:` ${t3("files.scope.noBase")}`]}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("files.legend.changes")}),props.onDiffAll?$jsx("text",{fg:theme.accent,wrapMode:"none",onMouseUp:(e2)=>{e2.stopPropagation(),props.onDiffAll?.()},children:t3("files.actions.diffAll")}):null]}):$jsx("box",{flexDirection:"row",paddingBottom:1,flexShrink:0})]})}function FileTree(props){let{theme}=useTheme(),t3=useT(),dims=useTerminalDimensions(),[tab,setTab]=import_react35.useState("all"),[scope,setScope]=import_react35.useState("working"),[scopeManual,setScopeManual]=import_react35.useState(!1),[base,setBase]=import_react35.useState(null),[cursorIndex,setCursorIndex]=import_react35.useState(0),[refreshTick,setRefreshTick]=import_react35.useState(0),[allFiles,setAllFiles]=import_react35.useState(null),[changes,setChanges]=import_react35.useState(null),[error,setError]=import_react35.useState(null),[expandedDirs,setExpandedDirs]=import_react35.useState(()=>new Set),pathRef=useLatest(props.worktreePath),tabRef=useLatest(tab),allFilesRef=useLatest(allFiles),changesRef=useLatest(changes),scopeRef=useLatest(scope),baseRef=useLatest(base),scopeManualRef=useLatest(scopeManual),onOpenFileRef=useLatest(props.onOpenFile),fetchSeq=import_react35.useRef(0),refetch=import_react35.useCallback(async(currentTab,path,signal)=>{let seq=++fetchSeq.current;if(path==null){setAllFiles(null),setChanges(null),setError(null);return}setError(null);try{if(currentTab==="all"){let files=await listFiles(path,signal);if(signal?.aborted||seq!==fetchSeq.current||pathRef.current!==path)return;setAllFiles((prev)=>sameFileList(prev,files)?prev:files)}else if(currentTab==="changes"){let wantBranch=scopeRef.current==="branch"&&baseRef.current!=null,entries=wantBranch?await statusFilesBranch(path,baseRef.current,signal):await statusFiles(path,signal);if(signal?.aborted||seq!==fetchSeq.current||pathRef.current!==path)return;if(!wantBranch&&entries.length===0&&!scopeManualRef.current&&baseRef.current!=null){setScope("branch");return}setChanges((prev)=>sameStatusEntries(prev,entries)?prev:entries)}}catch(err){if(signal?.aborted)return;let message=errorMessage(err);if(seq===fetchSeq.current&&pathRef.current===path)setError(message)}},[]);import_react35.useEffect(()=>{setAllFiles(null),setChanges(null),setError(null),setCursorIndex(0),setExpandedDirs(new Set),setScope("working"),setScopeManual(!1);let controller=new AbortController;return refetch(tabRef.current,props.worktreePath,controller.signal),()=>controller.abort()},[props.worktreePath,refetch]),import_react35.useEffect(()=>{let path=props.worktreePath;if(path==null){setBase(null);return}let disposed=!1,controller=new AbortController;return resolveBase(path,props.prBaseRef,controller.signal).then((b3)=>{if(!disposed)setBase(b3)}).catch(()=>{if(!disposed)setBase(null)}),()=>{disposed=!0,controller.abort()}},[props.worktreePath,props.prBaseRef]),import_react35.useEffect(()=>{if(tabRef.current!=="changes")return;let path=pathRef.current;if(path==null)return;let controller=new AbortController;return refetch("changes",path,controller.signal),()=>controller.abort()},[scope,base,refetch]),import_react35.useEffect(()=>{let path=props.worktreePath;if(path==null)return;if(readRoveEnv("FILETREE_WATCH")==="0")return;return watchWorktree(path,()=>setRefreshTick((n2)=>n2+1))},[props.worktreePath]),import_react35.useEffect(()=>{setCursorIndex(0);let path=pathRef.current;if(path==null)return;let controller=new AbortController;if(tab==="all"){if(allFilesRef.current==null)refetch("all",path,controller.signal)}else if(tab==="changes"){if(changesRef.current==null)refetch("changes",path,controller.signal)}return()=>controller.abort()},[tab,refetch]),import_react35.useEffect(()=>{if(refreshTick===0)return;let path=pathRef.current;if(path==null)return;let controller=new AbortController;return refetch(tabRef.current,path,controller.signal),()=>controller.abort()},[refreshTick,refetch]);let tree=import_react35.useMemo(()=>allFiles==null?null:buildTree(allFiles),[allFiles]),prevRows=import_react35.useRef([]),rows=import_react35.useMemo(()=>{let next=[];if(tab==="all"){if(tree!=null)flattenTree(tree,expandedDirs,0,next)}else if(tab==="changes"){if(changes!=null)next.push(...statusRows(changes,expandedDirs))}let reconciled=reconcileRows(prevRows.current,next);return prevRows.current=reconciled,reconciled},[tab,tree,expandedDirs,changes]);import_react35.useEffect(()=>{if(rows.length===0)return;setCursorIndex((i2)=>i2>rows.length-1?rows.length-1:i2)},[rows]);let statWidths=import_react35.useMemo(()=>computeStatWidths(rows),[rows]),paneWidth=props.paneWidth??dims.width,pathBudget=import_react35.useMemo(()=>computePathBudget(paneWidth,statWidths),[paneWidth,statWidths]);function applyNav(action){if(!action)return;if(action.type==="cursor")setCursorIndex(action.index);else if(action.type==="expand")setExpandedDirs((prev)=>new Set(prev).add(action.path));else setExpandedDirs((prev)=>toggleDir(prev,action.path))}let activateRow=import_react35.useCallback((row)=>{if(row.kind==="dir"||row.path.endsWith("/"))setExpandedDirs((prev)=>toggleDir(prev,row.path));else onOpenFileRef.current(row.path)},[]),handleRowActivate=import_react35.useCallback((row,index)=>{setCursorIndex(index),activateRow(row)},[activateRow]),markKeysUsed=usePaneHintMark("files");useBindings(()=>({enabled:props.focused??!0,bindings:fileTreeBindings({moveDown:()=>{if(markKeysUsed(),rows.length===0)return;setCursorIndex((i2)=>Math.min(i2+1,rows.length-1))},moveUp:()=>{if(markKeysUsed(),rows.length===0)return;setCursorIndex((i2)=>Math.max(i2-1,0))},setTab,currentTab:()=>tab,openCurrent:()=>{markKeysUsed();let row=rows[cursorIndex];if(row)activateRow(row)},mentionCurrent:()=>{let row=rows[cursorIndex];if(!row||row.kind==="dir"||row.path.endsWith("/"))return;props.onMention?.(row.path)},openExternal:()=>{let row=rows[cursorIndex];if(!row||row.kind==="dir"||row.path.endsWith("/"))return;if(!props.worktreePath)return;openExternally(`${props.worktreePath}/${row.path}`)},refresh:()=>{setRefreshTick((n2)=>n2+1)},toggleScope:()=>{if(tab!=="changes")return;if(base==null)return;setScopeManual(!0),setScope((s2)=>s2==="working"?"branch":"working")},openDiff:()=>{let row=rows[cursorIndex];if(!row)return;let spec=row.kind==="dir"||row.path.endsWith("/")?`${row.path.replace(/\/+$/,"")}/`:row.path;props.onOpenDiff?.(spec,scope==="branch"&&base!=null?base:void 0)},openDiffAll:()=>{props.onOpenDiff?.(".",scope==="branch"&&base!=null?base:void 0)},expandOrDescend:()=>applyNav(expandOrDescendAction(rows,cursorIndex)),collapseOrParent:()=>applyNav(collapseOrParentAction(rows,cursorIndex))})}));let loaded=tab==="all"&&allFiles!=null||tab==="changes"&&changes!=null;return $jsxs("box",{flexDirection:"column",flexGrow:1,paddingLeft:0,paddingRight:0,children:[$jsx(FileTreeHeaderView,{tab,scope,base,onSelectTab:setTab,onZenToggle:props.onZenToggle,onCreatePR:props.onCreatePR,onDiffAll:props.onOpenDiff?()=>props.onOpenDiff?.(".",scope==="branch"&&base!=null?base:void 0):void 0}),$jsx(FileTreeBodyView,{rows,cursorIndex,statWidths,pathBudget,onActivate:handleRowActivate,worktreePath:props.worktreePath,error,loaded,tab}),props.worktreePath!=null?$jsx("box",{flexDirection:"row",justifyContent:"flex-end",paddingTop:1,flexShrink:0,children:$jsx(PaneKeyHint,{pane:"files"})}):null]})}var WORKTREE_TOOLS_MIN_WIDTH=22,WORKTREE_TOOLS_MAX_WIDTH=34;function HostFilesPane(props){let{theme}=useTheme(),focus=useFocus(),dims=useTerminalDimensions(),inactiveBorder=theme.borderActive,available=Math.max(WORKTREE_TOOLS_MIN_WIDTH,dims.width-sidebarWidthFor(dims.width)),width=Math.max(WORKTREE_TOOLS_MIN_WIDTH,Math.min(WORKTREE_TOOLS_MAX_WIDTH,Math.floor(available/3)));return $jsx("box",{width,flexShrink:0,borderStyle:"rounded",borderColor:focus.focused==="files"?theme.focusAccent:inactiveBorder,onMouseUp:()=>focus.setFocused("files"),children:$jsx(FileTree,{worktreePath:props.worktree,paneWidth:width-2,prBaseRef:props.prBaseRef,focused:props.focused,onOpenFile:props.onOpenFile,onOpenDiff:props.onOpenDiff,onMention:props.onMention,onZenToggle:props.onZenToggle,onCreatePR:props.taskKind==="main"?void 0:props.onCreatePR})})}var EIGHTHS=["","\u258F","\u258E","\u258D","\u258C","\u258B","\u258A","\u2589"];function ratioBar(ratio,width=8){let cells=Math.min(1,Math.max(0,ratio))*width,full=Math.floor(cells),eighth=Math.round((cells-full)*8);if(eighth===8)full+=1,eighth=0;let partial=full<width?EIGHTHS[eighth]??"":"";return`${"\u2588".repeat(full)}${partial}`.padEnd(width,"\u2591")}var USAGE_BAR_WIDTH=10,toneOf=(percent)=>percent>=95?"crit":percent>=75?"warn":"ok",pad2=(n2)=>String(n2).padStart(2,"0");function formatReset(resetsAt,nowMs){if(resetsAt==null||resetsAt<=nowMs)return"";let d2=new Date(resetsAt),clock=`${pad2(d2.getHours())}:${pad2(d2.getMinutes())}`;if(resetsAt-nowMs<86400000)return`\u2192 ${clock}`;return`\u2192 ${d2.getMonth()+1}/${d2.getDate()} ${clock}`}function usageChips(usage,nowMs){return usage.windows.map((w3)=>({label:w3.label,percentText:`${w3.percent}%`,resetText:formatReset(w3.resetsAt,nowMs),tone:toneOf(w3.percent)}))}function narrowUsageChip(usage,nowMs){let w3=usage.windows.find((win)=>win.kind==="session")??usage.windows[0];if(!w3)return null;return{label:w3.label,percentText:`${w3.percent}%`,resetText:formatReset(w3.resetsAt,nowMs),tone:toneOf(w3.percent)}}function fullChipCells(chip,index){let label=index===0?chip.label:`\xB7 ${chip.label}`,parts=[displayWidth(label),displayWidth(chip.percentText)];if(chip.resetText)parts.push(displayWidth(chip.resetText));return parts.reduce((a2,b3)=>a2+b3,0)+(parts.length-1)}function fullVendorCells(vendor){return displayWidth(vendor.vendor)+vendor.chips.reduce((sum,chip,i2)=>sum+fullChipCells(chip,i2),0)+vendor.chips.length}function usageChipsBudget(opts){return Math.max(0,opts.terminalWidth-4-opts.hintCells)}function buildFooterChips(opts){let entries=[...opts.usage.entries()].map(([id,snapshot])=>({vendor:opts.vendorLabel(id).toUpperCase(),snapshot,chips:usageChips(snapshot,opts.nowMs)})).filter((entry)=>entry.chips.length>0);if(entries.length===0)return null;if(!opts.forceCompact){let fulls=entries.map((entry)=>({vendor:entry.vendor,chips:entry.chips}));if(fulls.reduce((sum,v3)=>sum+fullVendorCells(v3),0)+(fulls.length-1)*2<=opts.budget)return{form:"full",vendors:fulls}}let vendors=[],remaining=opts.budget;for(let entry of entries){let chip=narrowUsageChip(entry.snapshot,opts.nowMs);if(!chip)continue;let gap=vendors.length>0?2:0,need=displayWidth(entry.vendor)+1+displayWidth(chip.percentText);if(need+gap<=remaining){vendors.push({vendor:entry.vendor,percentText:chip.percentText,tone:chip.tone}),remaining-=need+gap;continue}let nameBudget=remaining-gap-1-displayWidth(chip.percentText);if(nameBudget>=3)vendors.push({vendor:truncateEndCells(entry.vendor,nameBudget,approxCharCells),percentText:chip.percentText,tone:chip.tone});break}return{form:"compact",vendors}}function contextChip(usage){if(!usage)return null;let window=usage.contextWindowTokens;if(window===void 0||window<=0)return null;let percent=Math.min(100,Math.max(0,Math.round(usage.contextTokens/window*100)));return{label:"ctx",percentText:`${percent}%${usage.approximate?"~":""}`,resetText:"",tone:toneOf(percent)}}function tokenTotalChip(usage){if(!usage)return null;if(usage.inputTokens===void 0&&usage.outputTokens===void 0)return null;return{label:"\u03A3",text:humanTokens((usage.inputTokens??0)+(usage.outputTokens??0))}}function humanTokens(total){if(total<1000)return String(total);if(total<1e6)return`${Math.floor(total/1000)}k`;return`${(Math.floor(total/1e5)/10).toFixed(1)}M`}function usageRows(usage,nowMs){let labelWidth=Math.min(8,usage.windows.reduce((w3,win)=>Math.max(w3,win.label.length),2));return usage.windows.map((w3)=>({label:(w3.label.length>labelWidth?w3.label.slice(0,labelWidth):w3.label).padEnd(labelWidth),bar:ratioBar(w3.percent/100,USAGE_BAR_WIDTH),percentText:`${String(w3.percent).padStart(3)}%`,resetText:formatReset(w3.resetsAt,nowMs),tone:toneOf(w3.percent)}))}function ContextChip(props){let{theme}=useTheme(),chip=props.chip;if(!chip)return null;let toneColor2={ok:theme.success,warn:theme.warning,crit:theme.error};return $jsxs("box",{flexDirection:"row",gap:1,flexShrink:0,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:chip.label}),$jsx("text",{fg:toneColor2[chip.tone],wrapMode:"none",children:chip.percentText})]})}function TokenChip(props){let{theme}=useTheme(),chip=props.chip;if(!chip)return null;return $jsxs("box",{flexDirection:"row",gap:1,flexShrink:0,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:chip.label}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:chip.text})]})}function UsageChips(props){let{theme}=useTheme(),usage=useAccessor(props.orchestrator.usageSnapshotSignal()),toneColor2={ok:theme.success,warn:theme.warning,crit:theme.error},now=Date.now(),view=usage&&usage.size>0?buildFooterChips({usage,budget:props.budget,nowMs:now,vendorLabel:engineDisplayName,forceCompact:props.narrow}):null;if(!view)return null;if(view.form==="full")return $jsx("box",{flexDirection:"row",gap:2,children:view.vendors.map((vendor)=>$jsxs("box",{flexDirection:"row",gap:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:vendor.vendor}),vendor.chips.map((chip,i2)=>$jsxs("box",{flexDirection:"row",gap:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:i2===0?chip.label:`\xB7 ${chip.label}`}),$jsx("text",{fg:toneColor2[chip.tone],wrapMode:"none",children:chip.percentText}),chip.resetText?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:chip.resetText}):null]},chip.label))]},vendor.vendor))});return $jsx("box",{flexDirection:"row",gap:2,children:view.vendors.map((vendor,index)=>$jsxs("box",{flexDirection:"row",gap:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:vendor.vendor}),$jsx("text",{fg:toneColor2[vendor.tone],wrapMode:"none",children:vendor.percentText})]},`${vendor.vendor}-${index}`))})}function WorkspaceFrame(props){let{theme}=useTheme(),dims=useTerminalDimensions(),narrow=isNarrowWidth(dims.width),usage=useAccessor(props.orchestrator.usageSnapshotSignal()),context=useAccessor(props.orchestrator.contextUsageSignal()),usageEntry=props.activeTaskId&&props.activeTabId?context?.get(`${props.activeTaskId}::${props.activeTabId}`):void 0,ctxChip=contextChip(usageEntry),tokChip=tokenTotalChip(usageEntry),hintItems=useStatusKeyHintItems({onOpenSettings:narrow?void 0:props.onOpenSettings,compact:narrow}),footerVisible=usage!=null&&usage.size>0||ctxChip!==null||tokChip!==null||hintItems.length>0,hintCells=hintItems.reduce((sum,item,index)=>sum+displayWidth(item.text)+(index>0?3:0),0),contextCells=11,tokenCells=tokChip?10:0,chipsBudget=Math.max(0,usageChipsBudget({terminalWidth:dims.width,hintCells})-11-tokenCells);return $jsx(ShortcutRevealProvider,{children:$jsxs("box",{flexDirection:"column",flexGrow:1,backgroundColor:theme.background,children:[props.banner,$jsx("box",{flexDirection:"row",flexGrow:1,children:props.children}),footerVisible?$jsxs("box",{flexDirection:"row",flexShrink:0,height:1,paddingLeft:1,paddingRight:1,gap:2,children:[$jsxs("box",{flexGrow:1,flexShrink:1,flexDirection:"row",gap:2,overflow:"hidden",children:[$jsx(ContextChip,{chip:ctxChip}),$jsx(TokenChip,{chip:tokChip}),$jsx(UsageChips,{orchestrator:props.orchestrator,narrow,budget:chipsBudget})]}),$jsx(StatusKeyHintBar,{onOpenSettings:narrow?void 0:props.onOpenSettings,compact:narrow})]}):null]})})}function workspacePagesClosed(s2){return!s2.dialogOpen&&!s2.settingsOpen&&!s2.worktreesOpen&&!s2.updateOpen}function settingsCloseKeysEnabled(s2){return s2.settingsOpen&&!s2.dialogOpen}var PANE_CYCLE=["sidebar","workspace","files"];function nextFocusedPane(current,delta,opts){let reachable=PANE_CYCLE.filter((pane)=>pane!=="files"||opts.filesVisible),idx=reachable.indexOf(current);if(idx<0)return(delta>0?reachable[reachable.length-1]:reachable[0])??null;let next=Math.min(Math.max(idx+delta,0),reachable.length-1);return next===idx?null:reachable[next]??null}function firePluginBinding(binding){let verb=binding.kind==="pane"?["plugin","pane","open",binding.target]:["plugin","action","invoke",binding.target],[cmd,...rest]=[...roveCliInvocation(),...verb];spawnDetached(cmd,rest,{onError:(err)=>console.warn(`[rove/plugins] ${binding.target}: ${String(err)}`)})}function usePluginKeybindings(enabled){useBindings(()=>({enabled,bindings:pluginKeybindings().map((binding)=>({key:binding.chord,cmd:()=>firePluginBinding(binding)}))}))}function useWorkspaceKeybindings(deps){let{focus,dialog}=deps,t3=useT(),renderer=useRenderer();function exitApp(){try{renderer?.destroy()}catch(err){console.error("Rove: renderer.destroy() failed during quit:",err)}process.exit(0)}async function quit(){if(await DialogConfirm.show(dialog,t3("workspace.quit.confirmTitle"),t3("workspace.quit.confirmBody"),t3("common.cancel"),t3("workspace.quit.confirmLabel")))exitApp()}function cyclePane(delta){let next=nextFocusedPane(focus.focused,delta,{filesVisible:deps.filesPaneVisible!==!1});if(next)focus.setFocused(next)}let pages={dialogOpen:deps.dialog.stack.length>0,settingsOpen:deps.pages.settingsOpen,worktreesOpen:deps.pages.worktreesOpen,updateOpen:deps.pages.updateOpen,kanbanOpen:deps.pages.kanbanOpen,automationsOpen:deps.pages.automationsOpen,workItemsOpen:deps.pages.workItemsOpen},pagesClosed=workspacePagesClosed(pages);useBindings(()=>({enabled:pagesClosed,bindings:[...bindByIds({"help.open":()=>HelpDialog.show(dialog,focus.focused),"focus.previous":prefixAction(()=>cyclePane(-1)),"focus.next":prefixAction(()=>cyclePane(1)),"workspace.zenToggle":prefixAction(()=>deps.toggleZen()),"attention.next":()=>deps.jumpToNextAttention(),"inbox.show":prefixAction(()=>deps.openInbox()),"kanban.open":prefixAction(()=>deps.pages.openKanban()),"automations.open":prefixAction(()=>deps.pages.openAutomations()),"workItems.open":prefixAction(()=>deps.pages.openWorkItems()),"task.moveMode":prefixAction(()=>deps.enterMoveMode()),"settings.open":prefixAction(()=>deps.pages.openSettings()),"files.createPR":prefixAction(()=>{let row=focus.focused==="sidebar"?deps.cursorTaskId():null;if(row!==null&&row!==deps.selectedId)deps.createPRFor(row);else deps.createPR()}),"files.fixChecks":prefixAction(()=>{let id=(focus.focused==="sidebar"?deps.cursorTaskId():null)??deps.selectedId;if(id)deps.fixChecksFor(id)}),"files.syncBase":prefixAction(()=>{let id=(focus.focused==="sidebar"?deps.cursorTaskId():null)??deps.selectedId;if(id)deps.syncBaseFor(id)}),"task.openEditor":prefixAction(()=>{let id=(focus.focused==="sidebar"?deps.cursorTaskId():null)??deps.selectedId;if(id)deps.openTaskWorktree(id)})})]})),useBindings(()=>({enabled:!pages.dialogOpen&&!pages.settingsOpen&&!deps.searchActive,bindings:bindByIds({"task.new.global":()=>deps.createTask()})})),useBindings(()=>({enabled:pagesClosed&&focus.focused!=="sidebar",bindings:bindByIds({"focus.sidebar":()=>focus.setFocused("sidebar")})})),useBindings(()=>({enabled:pagesClosed&&focus.focused==="sidebar"&&!deps.searchActive,bindings:bindByIds({"app.quit":(_evt,slot)=>{if(slot===1){exitApp();return}quit()},"settings.open.sidebar":()=>deps.pages.openSettings(),"worktrees.open.sidebar":()=>deps.pages.openWorktrees(),"tasks.update":()=>deps.pages.openUpdate()})})),useBindings(()=>({enabled:pagesClosed&&focus.focused==="sidebar"&&!deps.searchActive,bindings:bindByIds({"task.new":()=>deps.createTask(),"tasks.openWorktree":()=>{let id=deps.cursorTaskId();if(id)deps.openTaskWorktree(id)},"tasks.renameBranch":()=>{let id=deps.cursorTaskId();if(id)deps.renameBranch(id)},"tasks.cycleEngine":()=>{let id=deps.cursorTaskId();if(id)deps.cycleVendor(id)},"tasks.focusEngine":()=>focus.setFocused("workspace"),"sidebar.sort":()=>deps.toggleSortMode()})})),useBindings(()=>({enabled:settingsCloseKeysEnabled(pages),bindings:pageCloseBindings(deps.pages.closeSettings)})),usePluginKeybindings(pagesClosed)}var import_react60=__toESM(require_react_production(),1);var SIDEBAR_NAV_ITEMS=[{nav:"kanban",labelKey:"tasks.nav.kanban",bindingId:"kanban.open"},{nav:"automations",labelKey:"tasks.nav.automations",bindingId:"automations.open"},{nav:"issues",labelKey:"tasks.nav.issues",bindingId:"workItems.open"}];function focusPaneForNav(nav){return nav==="terminal"?"sidebar":"workspace"}import{TextAttributes as TextAttributes13}from"@opentui/core";var import_react42=__toESM(require_react_production(),1);function dividerRule(terminalWidth){return"\u2500".repeat(Math.max(1,terminalWidth))}var import_react39=__toESM(require_react_production(),1);function useCursorFollow(cursor){let scrolls=import_react39.useRef(new Set),rows=import_react39.useRef(new Map);return import_react39.useEffect(()=>{let el=rows.current.get(cursor);if(!el)return;for(let scroll of scrolls.current)if(scroll.viewport.height>0)scroll.scrollChildIntoView(el.id)},[cursor]),{scrollRef:(r2)=>{if(!r2)return;return scrolls.current.add(r2),()=>{scrolls.current.delete(r2)}},rowRef:(key)=>(r2)=>{if(!r2)return;return rows.current.set(key,r2),()=>{if(rows.current.get(key)===r2)rows.current.delete(key)}}}}var import_react40=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes11}from"@opentui/core";function relativeBuckets(absMs){let minutes=Math.floor(absMs/60000),hours=Math.floor(minutes/60);return{minutes,hours,days:Math.floor(hours/24)}}function relativeCountdown(deadlineMs,nowMs=Date.now()){return relativeAge(nowMs,deadlineMs)}function relativeAge(ms,nowMs=Date.now()){let delta=Math.max(0,nowMs-ms),secs=Math.floor(delta/1000);if(secs<60)return`${secs}s`;let{minutes,hours,days}=relativeBuckets(delta);if(minutes<60)return`${minutes}m`;if(hours<24)return`${hours}h`;return`${days}d`}var COMPOSER_FIELDS=["name","repo","target","targetTab","prompt","schedule","confirm"];function nextComposerField(field,delta=1,bound=!1){let fields=bound?COMPOSER_FIELDS:COMPOSER_FIELDS.filter((f2)=>f2!=="targetTab"),index=fields.indexOf(field);if(index<0)return"name";let next=(index+delta+fields.length)%fields.length;return fields[next]??"name"}var EMPTY_DRAFT={name:"",repo:"",prompt:"",schedule:"0 9 * * MON-FRI"};function canSubmitDraft(draft){return draft.name.trim().length>0&&draft.repo.trim().length>0&&draft.prompt.trim().length>0&&(!draft.target||draft.target.taskId.trim().length>0&&/^tab-[\w-]+$/.test(draft.target.tabId))&&isValidCron(draft.schedule.trim())}function firstIncompleteField(draft){if(draft.name.trim().length===0)return"name";if(draft.repo.trim().length===0)return"repo";if(draft.target&&!draft.target.taskId.trim())return"target";if(draft.target&&!/^tab-[\w-]+$/.test(draft.target.tabId))return"targetTab";if(draft.prompt.trim().length===0)return"prompt";if(!isValidCron(draft.schedule.trim()))return"schedule";return null}function previewSchedule(expression,nowMs){let trimmed=expression.trim();if(!isValidCron(trimmed))return{kind:"invalid"};let nextRunMs;try{nextRunMs=nextCronAfter(trimmed,nowMs)}catch{return{kind:"never"}}return{kind:"ok",nextRunMs,relative:formatRelative(nextRunMs-nowMs),absolute:formatAbsolute(nextRunMs,nowMs)}}function formatRelative(deltaMs){let{minutes,hours,days}=relativeBuckets(deltaMs);if(minutes<60)return t("automations.when.inMinutes",{n:Math.max(1,minutes)});if(hours<24)return t("automations.when.inHours",{n:hours});return t("automations.when.inDays",{n:days})}function formatAbsolute(atMs,nowMs){let at=new Date(atMs),time=`${String(at.getHours()).padStart(2,"0")}:${String(at.getMinutes()).padStart(2,"0")}`,now=new Date(nowMs);if(at.getFullYear()===now.getFullYear()&&at.getMonth()===now.getMonth()&&at.getDate()===now.getDate())return time;let withinWeek=atMs-nowMs<518400000,date=at.toLocaleDateString(intlLocale(),withinWeek?{weekday:"short"}:{weekday:"short",month:"short",day:"numeric"});return withinWeek?`${date} ${time}`:t("automations.when.dateTime",{date,time})}var CRON_SEGMENTS=["minute","hour","dayOfMonth","month","dayOfWeek"];function splitCron(expression){let parts=expression.trim().split(/\s+/).filter(Boolean);return CRON_SEGMENTS.map((_3,index)=>parts[index]??"*")}function joinCron(parts){return CRON_SEGMENTS.map((_3,index)=>parts[index]??"*").join(" ")}var MINUTE_LADDER=["*","*/5","*/10","*/15","*/30",...range(0,59)],HOUR_LADDER=["*","*/2","*/3","*/4","*/6","*/12",...range(0,23)],DOM_LADDER=["*",...range(1,31)],MONTH_LADDER=["*","JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"],DOW_LADDER=["*","MON-FRI","SAT,SUN","MON","TUE","WED","THU","FRI","SAT","SUN"],DOW_CODES=["MON","TUE","WED","THU","FRI","SAT","SUN"];function range(from,to){let out=[];for(let n2=from;n2<=to;n2++)out.push(String(n2));return out}var LADDERS={minute:MINUTE_LADDER,hour:HOUR_LADDER,dayOfMonth:DOM_LADDER,month:MONTH_LADDER,dayOfWeek:DOW_LADDER};function stepSegment(segment,current,delta){let ladder=LADDERS[segment],index=ladder.indexOf(current.trim().toUpperCase());if(index<0)return(delta>0?ladder[0]:ladder[ladder.length-1])??current;let next=(index+delta+ladder.length)%ladder.length;return ladder[next]??current}function moveSegmentCursor(cursor,delta){return Math.min(Math.max(cursor+delta,0),CRON_SEGMENTS.length-1)}function setSegment(expression,index,value){let parts=splitCron(expression);if(index<0||index>=CRON_SEGMENTS.length)return joinCron(parts);return parts[index]=value,joinCron(parts)}function describeCron(expression){let[minute,hour,dom,month,dow]=splitCron(expression);if(month!=="*"||dom!=="*")return null;if(minute===void 0||hour===void 0||dow===void 0)return null;let timeOfDay=describeTimeOfDay(minute,hour);if(!timeOfDay)return null;let{at,bare}=timeOfDay;if(dow==="*")return bare?at:t("automations.schedule.everyDay",{at});if(dow==="MON-FRI")return t("automations.schedule.weekdays",{at});if(dow==="SAT,SUN")return t("automations.schedule.weekends",{at});let code=DOW_CODES.find((candidate)=>candidate===dow.toUpperCase());if(code)return t("automations.schedule.onWeekday",{weekday:t(`automations.schedule.dow.${code}`),at});return null}function describeTimeOfDay(minute,hour){if(hour==="*"){if(minute==="*")return{at:t("automations.schedule.everyMinute"),bare:!0};if(minute.startsWith("*/"))return{at:t("automations.schedule.everyMinutes",{n:minute.slice(2)}),bare:!0};if(/^\d+$/.test(minute))return{at:t("automations.schedule.hourlyAt",{minute:minute.padStart(2,"0")}),bare:!1};return null}if(hour.startsWith("*/")&&minute==="0")return{at:t("automations.schedule.everyHours",{n:hour.slice(2)}),bare:!0};if(/^\d+$/.test(hour)&&/^\d+$/.test(minute)){let time=`${hour.padStart(2,"0")}:${minute.padStart(2,"0")}`;return{at:t("automations.schedule.atClock",{time}),bare:!1}}return null}function fuzzyMatch(query,haystack){if(!query)return!0;let q2=query.toLowerCase(),h2=haystack.toLowerCase(),qi=0;for(let hi=0;hi<h2.length&&qi<q2.length;hi++)if(h2.charCodeAt(hi)===q2.charCodeAt(qi))qi++;return qi===q2.length}function compareRecent(a2,b3){let byTime=taskTime(b3)-taskTime(a2);if(byTime!==0)return byTime;return String(b3.id).localeCompare(String(a2.id))}function taskTime(task){let parsed=Date.parse(task.updatedAt||task.createdAt);return Number.isFinite(parsed)?parsed:0}function repoBasename(repo){let segments=repo.split("/").filter(Boolean);return segments[segments.length-1]??repo}function sidebarProjectKey(repo){return repo.trim().replace(/[\\/]+$/,"")||repo}function sidebarProjectLabel(repo,repos){let base=repoBasename(repo);if(!repos.some((r2)=>r2!==repo&&repoBasename(r2)===base))return base;return repo.replace(/[\\/]+$/,"").split(/[\\/]+/).slice(-2).join("/")}import{TextAttributes as TextAttributes10}from"@opentui/core";function PickerList(props){let{theme}=useTheme(),t3=useT(),below=props.window.total-props.window.start-props.window.items.length;return $jsxs("box",{gap:0,paddingLeft:2,paddingBottom:props.paddingBottom,children:[props.window.start>0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("newTask.picker.moreAbove",{count:props.window.start})}):null,props.rows.map((row,i2)=>{let absoluteIndex=props.window.start+i2,isCursor=absoluteIndex===props.cursor,fg=isCursor?theme.primary:row.accent?theme.accent:theme.textMuted,attributes=isCursor?TextAttributes10.BOLD:void 0;if(!row.dim)return $jsxs("text",{fg,attributes,wrapMode:"none",onMouseUp:()=>props.onPick(absoluteIndex),children:[isCursor?"\u25B8 ":" ",row.body]},row.key);return $jsxs("box",{flexDirection:"row",onMouseUp:()=>props.onPick(absoluteIndex),children:[$jsxs("text",{fg,attributes,wrapMode:"none",flexShrink:0,children:[isCursor?"\u25B8 ":" ",row.body]}),$jsx("box",{flexGrow:1}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:1,children:` ${row.dim}`})]},row.key)}),below>0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("newTask.picker.moreBelow",{count:below})}):null,props.footer]})}function AutomationComposerView(props){let{theme}=useTheme(),dialog=useDialog(),t3=useT(),padX=useDialogPaddingX(),[draft,setDraft]=import_react40.useState(()=>({...EMPTY_DRAFT,repo:props.defaultRepo??props.repos[0]??""})),[field,setField]=import_react40.useState("name"),[repoCursor,setRepoCursor]=import_react40.useState(()=>{let at=props.repos.indexOf(props.defaultRepo??"");return at>=0?at:0}),[error,setError]=import_react40.useState(null),[segmentCursor,setSegmentCursor]=import_react40.useState(0),segmentValues=splitCron(draft.schedule),selectSegment=(index)=>{setField("schedule"),setSegmentCursor(Math.min(Math.max(index,0),CRON_SEGMENTS.length-1))},cancel=()=>{props.onCancel(),dialog.clear()},patch=(next)=>{setDraft((prev)=>({...prev,...next})),setError(null)},pickRepoAt=(index)=>{let repo=props.repos[clampCursor(index,props.repos.length)];if(!repo)return;setRepoCursor(clampCursor(index,props.repos.length)),patch({repo,target:void 0})};function commit(){if(canSubmitDraft(draft)){props.onSubmit({name:draft.name.trim(),repo:draft.repo.trim(),prompt:draft.prompt.trim(),schedule:draft.schedule.trim(),...draft.target?{target:draft.target}:{}}),dialog.clear();return}let gap=firstIncompleteField(draft);if(gap)setField(gap),setError(t3(`automations.missing.${gap}`))}let preview=previewSchedule(draft.schedule,Date.now()),repoWindow=windowAround(props.repos,repoCursor),repoRows=repoWindow.items.map((repo,index)=>({key:repo,body:sidebarProjectLabel(repo,props.repos),accent:repoWindow.start+index===repoCursor})),targets=props.tasks.filter((task)=>task.repo===draft.repo),targetCursor=draft.target?targets.findIndex((task)=>task.id===draft.target?.taskId)+1:0;function pickTarget(delta){let index=(targetCursor+delta+targets.length+1)%(targets.length+1),task=targets[index-1];patch({target:task?{kind:"existing-tab",taskId:task.id,tabId:"tab-1"}:void 0})}let targetLabel=draft.target?targets[targetCursor-1]?.title??draft.target.taskId:t3("automations.targetFresh");return useBindings(()=>({bindings:[{key:"tab",cmd:()=>setField((f2)=>nextComposerField(f2,1,Boolean(draft.target)))},{key:"shift+tab",cmd:()=>setField((f2)=>nextComposerField(f2,-1,Boolean(draft.target)))},...field==="target"?[{key:"up",cmd:()=>pickTarget(-1)},{key:"down",cmd:()=>pickTarget(1)}]:[],...field==="repo"?[{key:"up",cmd:()=>pickRepoAt(repoCursor-1)},{key:"down",cmd:()=>pickRepoAt(repoCursor+1)}]:[],...field==="schedule"?[{key:"left",cmd:()=>setSegmentCursor((c2)=>moveSegmentCursor(c2,-1))},{key:"right",cmd:()=>setSegmentCursor((c2)=>moveSegmentCursor(c2,1))},{key:"up",cmd:()=>{let seg=CRON_SEGMENTS[segmentCursor];if(!seg)return;patch({schedule:setSegment(draft.schedule,segmentCursor,stepSegment(seg,segmentValues[segmentCursor]??"*",1))})}},{key:"down",cmd:()=>{let seg=CRON_SEGMENTS[segmentCursor];if(!seg)return;patch({schedule:setSegment(draft.schedule,segmentCursor,stepSegment(seg,segmentValues[segmentCursor]??"*",-1))})}}]:[],...field==="confirm"?[{key:"return",cmd:()=>commit()}]:[]]})),$jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:1,children:[$jsx(DialogHeader,{title:t3("automations.newTitle"),onClose:()=>cancel()}),$jsx(DialogSection,{label:t3("automations.fieldName"),focused:field==="name",onPress:()=>setField("name"),children:$jsx(DialogField,{focused:field==="name",children:$jsx("input",{value:draft.name,placeholder:t3("automations.namePlaceholder"),focused:field==="name",onMouseUp:()=>setField("name"),onInput:(v3)=>patch({name:v3}),onSubmit:()=>setField(nextComposerField("name"))})})}),$jsx(DialogSection,{label:t3("automations.fieldRepo"),focused:field==="repo",hint:props.repos.length===0?void 0:"\u2191/\u2193",onPress:()=>setField("repo"),children:props.repos.length===0?$jsx("text",{fg:theme.textMuted,children:t3("automations.needRepo")}):$jsx(DialogField,{focused:field==="repo",children:$jsx(PickerList,{window:repoWindow,cursor:repoCursor,rows:repoRows,onPick:pickRepoAt})})}),$jsx(DialogSection,{label:t3("automations.fieldTarget"),focused:field==="target",hint:"\u2191/\u2193",onPress:()=>setField("target"),children:$jsx(DialogField,{focused:field==="target",children:$jsx("text",{fg:theme.text,onMouseUp:()=>{setField("target"),pickTarget(1)},children:targetLabel})})}),draft.target?$jsx(DialogSection,{label:t3("automations.fieldTargetTab"),focused:field==="targetTab",onPress:()=>setField("targetTab"),children:$jsx(DialogField,{focused:field==="targetTab",children:$jsx("input",{value:draft.target.tabId,focused:field==="targetTab",onMouseUp:()=>setField("targetTab"),onInput:(tabId)=>{if(draft.target)patch({target:{...draft.target,tabId}})},onSubmit:()=>setField("prompt")})})}):null,$jsx(DialogSection,{label:t3("automations.fieldPrompt"),focused:field==="prompt",onPress:()=>setField("prompt"),children:$jsx(DialogField,{focused:field==="prompt",children:$jsx("input",{value:draft.prompt,placeholder:t3("automations.promptPlaceholder"),focused:field==="prompt",onMouseUp:()=>setField("prompt"),onInput:(v3)=>patch({prompt:v3}),onSubmit:()=>setField(nextComposerField("prompt"))})})}),$jsx(DialogSection,{label:t3("automations.fieldSchedule"),focused:field==="schedule",hint:"\u2190/\u2192 \u2191/\u2193",onPress:()=>setField("schedule"),children:$jsxs(DialogField,{focused:field==="schedule",children:[$jsx("box",{flexDirection:"row",gap:2,children:CRON_SEGMENTS.map((segment,index)=>{let activeCell=field==="schedule"&&index===segmentCursor;return $jsxs("box",{flexDirection:"column",onMouseUp:()=>selectSegment(index),children:[$jsx("text",{fg:activeCell?theme.primary:theme.text,attributes:activeCell?TextAttributes11.BOLD|TextAttributes11.UNDERLINE:void 0,wrapMode:"none",children:segmentValues[index]??"*"}),$jsx("text",{fg:activeCell?theme.textMuted:theme.borderSubtle,wrapMode:"none",children:t3(`automations.cronField.${segment}`)})]},segment)})}),preview.kind==="ok"?$jsx("text",{fg:theme.success,wrapMode:"none",children:`${describeCron(draft.schedule)??""}${describeCron(draft.schedule)?" \xB7 ":""}${preview.relative} \xB7 ${preview.absolute}`}):$jsx("text",{fg:theme.error,wrapMode:"none",children:preview.kind==="never"?t3("automations.cronNever"):t3("automations.cronInvalid")})]})}),error?$jsxs("text",{fg:theme.error,wrapMode:"word",children:["\u203B ",error]}):null,$jsx(DialogFooter,{children:t3("automations.composerLegend")}),$jsx(DialogActions,{label:t3("common.create"),focused:field==="confirm",onPress:()=>commit()})]})}var AutomationComposer={show(dialog,opts){return showDialog(dialog,(resolve)=>$jsx(AutomationComposerView,{repos:opts.repos,tasks:opts.tasks??[],...opts.defaultRepo?{defaultRepo:opts.defaultRepo}:{},onSubmit:(draft)=>resolve(draft),onCancel:()=>resolve(void 0)}))}};function formatWhen(iso,now){if(!iso)return"\u2014";let at=Date.parse(iso);if(!Number.isFinite(at))return"\u2014";let deltaMs=at-now,ahead=deltaMs>=0,{minutes,hours}=relativeBuckets(Math.abs(deltaMs));if(minutes<1)return t(ahead?"automations.when.now":"automations.when.justNow");if(minutes<60)return t(ahead?"automations.when.inMinutes":"automations.when.minutesAgo",{n:minutes});if(hours<24)return t(ahead?"automations.when.inHours":"automations.when.hoursAgo",{n:hours});return new Date(at).toLocaleDateString(intlLocale())}function formatRunStatus(status,translate){let key=`automations.runStatus.${status}`,label=translate(key);return label===key?status:label}import{TextAttributes as TextAttributes12}from"@opentui/core";var RUN_TONE={dispatched:"success",revived:"success",deferred:"warning",skipped_precheck:"muted",skipped_cancelled:"muted",skipped_missed:"warning",skipped_unavailable:"warning",dispatch_failed:"error"};function runToneColor(status,theme){let tone=RUN_TONE[status]??"muted";if(tone==="success")return theme.success;if(tone==="warning")return theme.warning;if(tone==="error")return theme.error;return theme.textMuted}function runGlyph(status){let tone=RUN_TONE[status]??"muted";if(tone==="success")return"\u2713";if(tone==="error")return"\u2020";if(tone==="warning")return"!";return"\xB7"}function triggerGlyph(trigger){return trigger==="manual"?"\u25B8":"\xB7"}function outputTail(text,limit=10){let lines=text.replace(/\s+$/,"").split(`
20
+ `))count++;return count}function parseNumstat(raw){return parseNumstatRows(raw).map((r2)=>({path:r2.path,added:r2.added,deleted:r2.deleted}))}function parseStatusEntries(raw){let out=[];for(let row of parsePorcelainRows(raw)){let status;if(row.x==="?"&&row.y==="?")status="?";else{let candidate=row.y!==" "?row.y:row.x;if(candidate==="M"||candidate==="A"||candidate==="D"||candidate==="R"||candidate==="C"||candidate==="U"||candidate==="T")status=candidate;else continue}let path=row.path;if(path.length===0)continue;if(path.endsWith("/")&&status!=="?")continue;out.push({path,status})}return out}var TAB_ORDER=["all","changes"];function tabLabelKey(tab){switch(tab){case"all":return"files.tabs.all";case"changes":return"files.tabs.changes"}}function fileTreeBindings(opts){return bindByIds({"files.nav":(_evt,slot)=>{if((slot??0)%2===0)opts.moveDown();else opts.moveUp()},"files.hierarchy":(_evt,slot)=>{if((slot??0)%2===0)opts.collapseOrParent();else opts.expandOrDescend()},"files.tab":(_evt,slot)=>{let cur=opts.currentTab(),idx=TAB_ORDER.indexOf(cur);if(idx<0)return;let delta=(slot??0)%2===0?-1:1,next=TAB_ORDER[(idx+delta+TAB_ORDER.length)%TAB_ORDER.length];if(next)opts.setTab(next)},"files.open":()=>opts.openCurrent(),"files.mention":()=>opts.mentionCurrent?.(),"files.openExternal":()=>opts.openExternal(),"files.refresh":()=>opts.refresh(),"files.scope":()=>opts.toggleScope?.(),"files.diff":()=>opts.openDiff?.(),"files.diffAll":()=>opts.openDiffAll?.()})}import{spawn as spawn3}from"child_process";import{existsSync as existsSync2}from"fs";import{platform}from"os";function openExternally(absPath){if(!absPath)return;let plat=platform();if(plat==="linux"){if(existsSync2("/proc/sys/fs/binfmt_misc/WSLInterop")||process.env.WSL_DISTRO_NAME){spawnDetachedWithFallback("wslview",[absPath],()=>{let child=spawn3("wslpath",["-w",absPath],{stdio:["ignore","pipe","ignore"]}),out="";child.stdout?.on("data",(b3)=>{out+=b3.toString()}),child.on("close",(code)=>{if(code===0)spawnDetachedWithFallback("explorer.exe",[out.trim()])})});return}spawnDetachedWithFallback("xdg-open",[absPath]);return}if(plat==="darwin"){spawnDetachedWithFallback("open",[absPath]);return}if(plat==="win32"){spawnDetachedWithFallback("cmd.exe",["/c","start","",absPath]);return}}function spawnDetachedWithFallback(cmd,args,onError){spawnDetached(cmd,args,{onError:onError?()=>onError():void 0})}import{watch}from"fs";function statusToken(s2){switch(s2){case"M":return"warning";case"A":return"success";case"D":return"error";case"?":return"textMuted";case"R":case"C":case"U":case"T":return"info"}}function summarizeGitError(raw,t3){let kind=classifyGitError(raw);if(kind)return t3(`files.error.${kind}`);let colon=raw.indexOf(": ");if(colon>=0&&raw.startsWith("git "))return raw.slice(colon+2).trim()||t3("files.error.gitFailed");return raw.trim()||t3("files.error.gitFailed")}function classifyGitError(raw){let m3=raw.toLowerCase();if(m3.includes("not a git repository"))return"notGitRepo";if(m3.includes("does not exist")||m3.includes("enoent"))return"pathMissing";if(m3.includes("permission denied")||m3.includes("eacces"))return"permissionDenied";if(m3.includes("git: not found")||m3.includes("command not found"))return"gitNotInstalled";return null}function gitErrorIsRetryable(raw){let kind=classifyGitError(raw);return kind!=="notGitRepo"&&kind!=="gitNotInstalled"}function computeStatWidths(rows){let added=0,deleted=0;for(let row of rows){if(row.kind!=="status")continue;if(row.added!=null)added=Math.max(added,String(row.added).length+1);if(row.deleted!=null)deleted=Math.max(deleted,String(row.deleted).length+1)}return{added,deleted}}function computePathBudget(paneWidth,w3){let stats=(w3.added>0?w3.added+1:0)+(w3.deleted>0?w3.deleted+1:0);return Math.max(8,paneWidth-6-stats)}function statCell(value,width,sign){let glyph=sign==="-"?"\u2212":sign;return value==null?" ".repeat(width):`${glyph}${value}`.padStart(width)}function toggleDir(expanded,path){let next=new Set(expanded);if(next.has(path))next.delete(path);else next.add(path);return next}function expandOrDescendAction(rows,cursorIndex){let row=rows[cursorIndex];if(!row)return null;if(row.kind==="status"){if(row.fileCount==null)return null;if(!row.expanded)return{type:"expand",path:row.path};return cursorIndex+1<rows.length?{type:"cursor",index:cursorIndex+1}:null}if(row.kind!=="dir")return null;if(!row.expanded&&row.hasChildren)return{type:"expand",path:row.path};if(row.expanded&&cursorIndex+1<rows.length)return{type:"cursor",index:cursorIndex+1};return null}function collapseOrParentAction(rows,cursorIndex){let row=rows[cursorIndex];if(!row)return null;if(row.kind==="dir"&&row.expanded)return{type:"collapse",path:row.path};if(row.kind==="status")return row.fileCount!=null&&row.expanded?{type:"collapse",path:row.path}:null;if(row.kind!=="dir"&&row.kind!=="file")return null;let targetDepth=row.depth-1;if(targetDepth<0)return null;for(let j2=cursorIndex-1;j2>=0;j2--){let candidate=rows[j2];if(!candidate)continue;if(candidate.kind==="dir"&&candidate.depth===targetDepth)return{type:"cursor",index:j2}}return null}function followScrollTop(scrollTop,viewportHeight,cursorIndex){if(viewportHeight<=0)return null;if(cursorIndex<scrollTop)return cursorIndex;if(cursorIndex>=scrollTop+viewportHeight)return cursorIndex-viewportHeight+1;return null}function watchEventRelevant(filename){if(filename===".git"||filename.startsWith(".git/")||filename.startsWith(".git\\"))return!1;if(filename.startsWith("node_modules/")||filename.startsWith("node_modules\\"))return!1;return!0}function watchWorktree(path,onChange,debounceMs=500){let debounceTimer=null,watcher=null;try{watcher=watch(path,{recursive:!0},(_event,filename)=>{if(filename==null)return;if(!watchEventRelevant(filename.toString()))return;if(debounceTimer!=null)clearTimeout(debounceTimer);debounceTimer=setTimeout(()=>{debounceTimer=null,onChange()},debounceMs)}),watcher.on("error",()=>{})}catch{}return()=>{if(debounceTimer!=null)clearTimeout(debounceTimer);if(watcher!=null)watcher.close()}}function reconcileStableRows(prev,next,keyOf,equals,opts={}){if(prev.length===0)return next;let prevByKey=new Map;for(let row of prev)prevByKey.set(keyOf(row),row);let allReused=prev.length===next.length,out=Array(next.length);for(let i2=0;i2<next.length;i2++){let fresh=next[i2],old=prevByKey.get(keyOf(fresh));if(old&&equals(old,fresh)&&(!opts.samePosition||prev[i2]===old)){if(out[i2]=old,allReused&&prev[i2]!==old)allReused=!1}else out[i2]=fresh,allReused=!1}return allReused?prev:out}function flattenTree(node,expanded,depth,out){for(let child of node.children)if(child.isDir){let isOpen=expanded.has(child.path);if(out.push({kind:"dir",path:child.path,name:child.name,depth,expanded:isOpen,hasChildren:child.children.length>0}),isOpen)flattenTree(child,expanded,depth+1,out)}else out.push({kind:"file",path:child.path,name:child.name,depth})}function truncatePathTail(path,maxCells){return truncateStartCells(path,maxCells,charWidth)}var NO_EXPANSION=new Set;function statusRows(entries,expanded=NO_EXPANSION){let out=[];for(let e2 of entries){if(e2.children==null){out.push({kind:"status",path:e2.path,status:e2.status,added:e2.added,deleted:e2.deleted});continue}let isOpen=expanded.has(e2.path);if(out.push({kind:"status",path:e2.path,status:e2.status,added:e2.added,deleted:e2.deleted,fileCount:e2.children.length,expanded:isOpen}),isOpen)for(let c2 of e2.children)out.push({kind:"status",path:c2.path,status:c2.status,added:c2.added,deleted:c2.deleted,child:!0})}return out}function rowKey(row){return`${row.kind}\x00${row.path}`}function rowEquals(a2,b3){if(a2.kind!==b3.kind||a2.path!==b3.path)return!1;switch(a2.kind){case"file":{let o2=b3;return a2.name===o2.name&&a2.depth===o2.depth}case"dir":{let o2=b3;return a2.name===o2.name&&a2.depth===o2.depth&&a2.expanded===o2.expanded&&a2.hasChildren===o2.hasChildren}case"status":{let o2=b3;return a2.status===o2.status&&a2.added===o2.added&&a2.deleted===o2.deleted&&a2.fileCount===o2.fileCount&&a2.expanded===o2.expanded&&a2.child===o2.child}}}function reconcileRows(prev,next){return reconcileStableRows(prev,next,rowKey,rowEquals)}function sameFileList(a2,b3){if(a2===b3)return!0;if(a2==null||b3==null)return!1;if(a2.length!==b3.length)return!1;for(let i2=0;i2<a2.length;i2++)if(a2[i2]!==b3[i2])return!1;return!0}function sameStatusEntries(a2,b3){if(a2===b3)return!0;if(a2==null||b3==null)return!1;if(a2.length!==b3.length)return!1;for(let i2=0;i2<a2.length;i2++){let x2=a2[i2],y3=b3[i2];if(x2.path!==y3.path||x2.status!==y3.status||x2.added!==y3.added||x2.deleted!==y3.deleted)return!1;let xc=x2.children,yc=y3.children;if(xc==null!==(yc==null))return!1;if(xc&&yc){if(xc.length!==yc.length)return!1;for(let j2=0;j2<xc.length;j2++){let cx=xc[j2],cy=yc[j2];if(cx.path!==cy.path||cx.status!==cy.status||cx.added!==cy.added||cx.deleted!==cy.deleted)return!1}}}return!0}function buildTree(paths){let root={name:"",path:"",isDir:!0,children:[]},indexes=new Map;for(let p3 of paths){if(!p3)continue;let segs=p3.split("/").filter((s2)=>s2.length>0);if(segs.length===0)continue;let cur=root;for(let i2=0;i2<segs.length;i2++){let seg=segs[i2],isDir=i2!==segs.length-1,index=indexes.get(cur);if(!index)index=new Map,indexes.set(cur,index);let key=`${isDir?"d":"f"}:${seg}`,child=index.get(key);if(!child)child={name:seg,path:segs.slice(0,i2+1).join("/"),isDir,children:[]},cur.children.push(child),index.set(key,child);cur=child}}return sortTree(root),root}function sortTree(node){node.children.sort((a2,b3)=>{if(a2.isDir!==b3.isDir)return a2.isDir?-1:1;return a2.name.localeCompare(b3.name)});for(let c2 of node.children)sortTree(c2)}var import_react29=__toESM(require_react_production(),1);var import_react28=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes7}from"@opentui/core";function displayCap(cap){return cap.split(" + ").map((part)=>formatChord(part)).join(" + ")}function sectionTitle(section,t3){if(section.kind==="here")return t3("help.here",{surface:tKeys("category",scopeCategory(section.scope))});if(section.kind==="direct")return t3("help.direct");if(section.kind==="prefix")return t3("help.afterPrefix");return t3("help.otherPane",{surface:tKeys("category",scopeCategory(section.scope))})}function HelpDialog(props){let dialog=useDialog(),{theme}=useTheme(),t3=useT(),padX=useDialogPaddingX(),keymapVersion2=useKeymapVersion(),pureTuiPrefix=currentPrefixConfiguration(),sections=import_react28.useMemo(()=>grammarHelpSections(KobeKeymap,props.currentScope??null,pureTuiPrefix.key,props.reachability),[keymapVersion2,props.currentScope,props.reachability,pureTuiPrefix.key]),close=()=>props.onClose?props.onClose():dialog.clear(),scrollRef=import_react28.useRef(null),scrollBy=(lines)=>{let scroll=scrollRef.current;if(!scroll)return;scroll.scrollTo({x:0,y:Math.max(0,scroll.scrollTop+lines)})},scrollToEdge=(edge)=>{let scroll=scrollRef.current;if(!scroll)return;scroll.scrollTo({x:0,y:edge==="top"?0:Number.MAX_SAFE_INTEGER})};return useBindings(()=>({bindings:[{key:"?",cmd:close},{key:"up",cmd:()=>scrollBy(-1)},{key:"down",cmd:()=>scrollBy(1)},{key:"pageup",cmd:()=>scrollBy(-(scrollRef.current?.viewport.height??10))},{key:"pagedown",cmd:()=>scrollBy(scrollRef.current?.viewport.height??10)},{key:"home",cmd:()=>scrollToEdge("top")},{key:"end",cmd:()=>scrollToEdge("bottom")}]})),$jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:1,flexShrink:1,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",flexShrink:0,children:[$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{attributes:TextAttributes7.BOLD,fg:theme.text,children:t3("help.title")}),$jsx("text",{fg:theme.textMuted,children:props.currentScope?t3("help.focused",{surface:tKeys("category",scopeCategory(props.currentScope))}):t3("help.allBindings")}),$jsx("text",{fg:theme.textMuted,children:t3("help.grammar",{prefix:pureTuiPrefix.key?formatChord(pureTuiPrefix.key):t3("help.disabled")})})]}),$jsxs("box",{flexDirection:"row",gap:2,flexShrink:0,children:[$jsx("text",{fg:theme.textMuted,attributes:TextAttributes7.DIM,children:t3("help.scrollKeys")}),$jsx("text",{fg:theme.textMuted,onMouseUp:close,children:t3("help.esc")})]})]}),$jsx("scrollbox",{ref:(r2)=>{scrollRef.current=r2},flexShrink:1,flexGrow:1,stickyScroll:!1,verticalScrollbarOptions:{trackOptions:{backgroundColor:theme.backgroundDialog,foregroundColor:theme.borderActive}},children:$jsx("box",{paddingBottom:1,gap:1,paddingRight:1,children:sections.map((section,sectionIndex)=>$jsxs("box",{gap:0,children:[$jsx("text",{fg:theme.accent,attributes:TextAttributes7.BOLD,children:sectionTitle(section,t3)}),section.rows.map((row)=>{return $jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,children:[$jsx("box",{width:18,children:$jsx("text",{fg:theme.primary,children:displayCap(row.primary)})}),$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.text,children:tKeys("desc",row.binding.id)})}),row.aliases.length>0?$jsx("box",{children:$jsx("text",{fg:theme.textMuted,children:`(${row.aliases.map(displayCap).join(", ")})`})}):null]},`${section.kind}-${row.binding.id}`)})]},`${section.kind}-${section.scope??sectionIndex}`))})})]})}HelpDialog.show=(dialog,currentScope)=>{let reachability=currentBindingReachability(),inputScope=reachability.inputPassthrough?"terminal":currentScope;dialog.replace(()=>$jsx(HelpDialog,{currentScope:inputScope,reachability}))};function useStatusKeyHintItems(opts){let t3=useT(),kv=useOptionalKV(),focus=useOptionalFocus(),dialog=useOptionalDialog(),keymapVersion2=useKeymapVersion(),stackVersion=useBindingStackVersion(),hintsEnabled=keyHintsEnabled(kv?.get(KEY_HINTS_ENABLED_KEY,!0)),[snapshot,setSnapshot]=import_react29.useState({tokens:[],modal:!1});import_react29.useEffect(()=>{let enabled=hintsEnabled,nextModal=modalActive()||(dialog?.stack.length??0)>0,fresh=enabled&&!nextModal?statusHintTokens(currentBindingReachability(),currentPrefixConfiguration().key):null;setSnapshot((prev)=>{let nextTokens=fresh??(enabled?prev.tokens:[]);return prev.modal===nextModal&&prev.tokens.length===nextTokens.length&&prev.tokens.every((tok,i2)=>tok.chord===nextTokens[i2]?.chord&&tok.msg===nextTokens[i2]?.msg)?prev:{tokens:nextTokens,modal:nextModal}})},[keymapVersion2,stackVersion,focus?.focused,dialog?.stack.length,hintsEnabled]);let actions=snapshot.modal?{commands:void 0,sidebar:void 0,help:void 0}:{commands:()=>void armPrefixFromCurrentStack(),sidebar:focus?()=>focus.setFocused("sidebar"):void 0,help:dialog?()=>HelpDialog.show(dialog,focus?.focused??"sidebar"):void 0},items=snapshot.tokens.map((tok)=>({text:opts?.compact?formatChord(tok.chord):t3(`hints.status.${tok.msg}`,{key:formatChord(tok.chord)}),onPress:actions[tok.msg]}));if(opts?.onOpenSettings&&!opts.compact&&hintsEnabled)items.push({text:`[${t3("hints.status.settings")}]`,bindingId:"settings.open",onPress:snapshot.modal?void 0:opts.onOpenSettings});return items}function StatusKeyHintBar(props){let{theme}=useTheme(),items=useStatusKeyHintItems({onOpenSettings:props.onOpenSettings,compact:props.compact});if(items.length===0)return null;return $jsx("box",{flexDirection:"row",flexShrink:0,children:items.flatMap((item,index)=>[index>0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:" \xB7 "},`sep-${item.text}`):null,$jsxs("box",{position:"relative",onMouseUp:item.onPress,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:item.text}),item.bindingId?$jsx(ShortcutRevealBadge,{bindingId:item.bindingId,cover:!0}):null]},item.text)])})}function usePaneHintMark(pane){let kv=useOptionalKV();return import_react29.useCallback(()=>{if(!kv)return;if(kv.get(PANE_HINT_USED_KEYS[pane],!1)!==!0)kv.set(PANE_HINT_USED_KEYS[pane],!0)},[kv,pane])}function PaneKeyHint(props){let t3=useT(),{theme}=useTheme(),kv=useOptionalKV();useKeymapVersion();let enabledRaw=kv?.get(KEY_HINTS_ENABLED_KEY,!0),usedRaw=kv?.get(PANE_HINT_USED_KEYS[props.pane],!1);if(!keyHintsEnabled(enabledRaw))return null;let tokens=paneHintTokens(props.pane,paneHintVisible(enabledRaw,usedRaw)?"firstUse":"always");if(tokens.length===0)return null;return $jsx("text",{fg:theme.textMuted,wrapMode:"none",children:tokens.map((tok)=>`${formatChord(tok.cap)} ${t3(`hints.pane.${tok.msg}`)}`).join(" \xB7 ")})}var import_react33=__toESM(require_react_production(),1);var import_react30=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes8}from"@opentui/core";var FileTreeRowView=import_react30.memo(function(props){let{theme}=useTheme(),selection=resolveRowSelectionChrome(theme,{cursor:props.cursor}),bar=$jsx("text",{fg:selection.markerColor,wrapMode:"none",children:selection.marker}),rowBg=selection.backgroundColor,row=props.row;if(row.kind==="dir"){let indent2=" ".repeat(row.depth);return $jsxs("box",{flexDirection:"row",gap:0,backgroundColor:rowBg,onMouseUp:()=>props.onActivate(props.row,props.index),children:[bar,$jsx("box",{flexGrow:1,paddingRight:1,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes8.BOLD,wrapMode:"none",children:`${indent2}${row.expanded?"\u25BE":"\u25B8"} ${row.name}/`})})]})}if(row.kind==="file"){let indent2=" ".repeat(row.depth);return $jsxs("box",{flexDirection:"row",gap:0,backgroundColor:rowBg,onMouseUp:()=>props.onActivate(props.row,props.index),children:[bar,$jsx("box",{flexGrow:1,paddingRight:1,children:$jsx("text",{fg:theme.text,wrapMode:"none",children:`${indent2} ${row.name}`})})]})}let isUntrackedDir2=row.fileCount!==void 0,marker=isUntrackedDir2?row.expanded?"\u25BE ":"\u25B8 ":"",countSuffix=isUntrackedDir2?` (${row.fileCount})`:"",indent=row.child?" ":"",pathBudget=props.pathBudget-displayWidth(marker)-displayWidth(countSuffix)-displayWidth(indent),tone=statusToken(row.status),statusColor=tone==="success"?theme.success:tone==="warning"?theme.warning:tone==="error"?theme.error:tone==="info"?theme.info:theme.textMuted;return $jsxs("box",{flexDirection:"row",gap:0,backgroundColor:rowBg,onMouseUp:()=>props.onActivate(props.row,props.index),children:[bar,$jsxs("box",{flexDirection:"row",flexGrow:1,gap:1,paddingRight:1,children:[$jsx("text",{fg:statusColor,wrapMode:"none",children:row.status}),$jsx("text",{fg:isUntrackedDir2?theme.textMuted:theme.text,wrapMode:"none",flexGrow:1,children:`${indent}${marker}${truncatePathTail(row.path,pathBudget)}${countSuffix}`}),props.statWidths.added>0?$jsx("text",{fg:theme.success,wrapMode:"none",children:statCell(row.added,props.statWidths.added,"+")}):null,props.statWidths.deleted>0?$jsx("text",{fg:theme.error,wrapMode:"none",children:statCell(row.deleted,props.statWidths.deleted,"-")}):null]})]})});var import_react32=__toESM(require_react_production(),1);function rowWindowRange(top,height,rowCount){if(rowCount<=0)return{start:0,end:0};if(height<=0)return{start:0,end:Math.min(rowCount,64)};let end=Math.min(rowCount,Math.ceil(top+height)+16);return{start:Math.max(0,Math.min(Math.floor(top)-16,end-1)),end}}function useRowWindow(opts){let{scrollEl,rowCount}=opts,renderer=useRenderer(),[view,setView]=import_react32.useState({top:0,height:0}),sample=import_react32.useCallback(()=>{if(!scrollEl||scrollEl.isDestroyed)return;let top=scrollEl.scrollTop,height=scrollEl.viewport.height;setView((cur)=>cur.top===top&&cur.height===height?cur:{top,height})},[scrollEl]);import_react32.useEffect(()=>{if(!renderer)return;return sample(),renderer.on("frame",sample),()=>{renderer.off("frame",sample)}},[renderer,sample]);let{start,end}=rowWindowRange(view.top,view.height,rowCount);return{start,end,sample}}function FileTreeBodyView(props){let{theme}=useTheme(),t3=useT(),{rows,cursorIndex}=props,[scrollEl,setScrollEl]=import_react33.useState(null),rowWindow=useRowWindow({scrollEl,rowCount:rows.length}),rowCount=rows.length,sample=rowWindow.sample;return import_react33.useEffect(()=>{if(!scrollEl||rowCount===0)return;let y3=followScrollTop(scrollEl.scrollTop,scrollEl.viewport.height,cursorIndex);if(y3!=null)scrollEl.scrollTo({x:0,y:y3});sample()},[cursorIndex,rowCount,scrollEl,sample]),$jsx("scrollbox",{ref:setScrollEl,flexGrow:1,verticalScrollbarOptions:{trackOptions:{foregroundColor:"transparent"}},children:props.worktreePath==null?$jsx("box",{paddingTop:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:t3("files.empty.noTask")})}):props.error!=null?$jsxs("box",{paddingTop:1,paddingLeft:1,flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.error,wrapMode:"word",children:summarizeGitError(props.error,t3)}),gitErrorIsRetryable(props.error)?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("files.error.retryHint")}):null]}):rows.length===0&&props.loaded?$jsx("box",{paddingTop:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:props.tab==="all"?t3("files.empty.noFiles"):t3("files.empty.noChanges")})}):rows.length>0?$jsxs("box",{flexShrink:0,gap:0,paddingRight:1,children:[rowWindow.start>0?$jsx("box",{flexShrink:0,height:rowWindow.start}):null,rows.slice(rowWindow.start,rowWindow.end).map((row,offset)=>{let index=rowWindow.start+offset;return $jsx(FileTreeRowView,{row,index,cursor:index===cursorIndex,statWidths:props.statWidths,pathBudget:props.pathBudget,onActivate:props.onActivate},`${row.kind}:${row.path}`)}),rows.length>rowWindow.end?$jsx("box",{flexShrink:0,height:rows.length-rowWindow.end}):null]}):null})}import{TextAttributes as TextAttributes9}from"@opentui/core";function FileTreeHeaderView(props){let{theme}=useTheme(),t3=useT(),prefixKey=currentPrefixConfiguration().key,createPRChord=prefixKey?`[${formatChord(prefixKey)} P]`:null,zenStroke=findBinding("workspace.zenToggle")?.prefixKeys?.[0],zenChord=prefixKey&&zenStroke?`[${formatChord(prefixKey)} ${zenStroke.toUpperCase()}]`:null;return $jsxs($Fragment,{children:[props.onZenToggle||props.onCreatePR?$jsxs("box",{flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-end",columnGap:2,paddingBottom:1,flexShrink:0,children:[props.onZenToggle?$jsxs("box",{position:"relative",flexDirection:"row",gap:1,flexShrink:0,onMouseUp:(e2)=>{e2.stopPropagation(),props.onZenToggle?.()},children:[zenChord?$jsx("text",{fg:theme.accent,attributes:TextAttributes9.BOLD,wrapMode:"none",children:zenChord}):null,$jsx("text",{fg:theme.text,wrapMode:"none",children:t3("files.actions.zen")}),$jsx(ShortcutRevealBadge,{bindingId:"workspace.zenToggle"})]}):null,props.onCreatePR?$jsxs("box",{flexDirection:"row",gap:1,flexShrink:0,onMouseUp:(e2)=>{e2.stopPropagation(),props.onCreatePR?.()},children:[createPRChord?$jsxs("box",{position:"relative",children:[$jsx("text",{fg:theme.accent,attributes:TextAttributes9.BOLD,wrapMode:"none",children:createPRChord}),$jsx(ShortcutRevealBadge,{bindingId:"files.createPR",cover:!0})]}):null,$jsx("text",{fg:theme.text,wrapMode:"none",children:t3("files.actions.createPR")})]}):null]}):null,$jsx("box",{flexDirection:"row",paddingBottom:0,flexShrink:0,gap:2,children:TAB_ORDER.map((tabId)=>{let isActive=props.tab===tabId;return $jsx("text",{fg:isActive?theme.primary:theme.textMuted,attributes:isActive?TextAttributes9.BOLD:void 0,wrapMode:"none",onMouseUp:()=>props.onSelectTab(tabId),children:t3(tabLabelKey(tabId))},tabId)})}),props.tab==="changes"?$jsxs("box",{flexDirection:"column",paddingBottom:1,flexShrink:0,gap:0,children:[$jsxs("text",{fg:theme.textMuted,wrapMode:"word",children:[props.scope==="branch"&&props.base!=null?t3("files.scope.branch",{base:props.base}):t3("files.scope.working"),props.base!=null?` ${t3("files.scope.toggleHint")}`:` ${t3("files.scope.noBase")}`]}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("files.legend.changes")}),props.onDiffAll?$jsx("text",{fg:theme.accent,wrapMode:"none",onMouseUp:(e2)=>{e2.stopPropagation(),props.onDiffAll?.()},children:t3("files.actions.diffAll")}):null]}):$jsx("box",{flexDirection:"row",paddingBottom:1,flexShrink:0})]})}function FileTree(props){let{theme}=useTheme(),t3=useT(),dims=useTerminalDimensions(),[tab,setTab]=import_react35.useState("all"),[scope,setScope]=import_react35.useState("working"),[scopeManual,setScopeManual]=import_react35.useState(!1),[base,setBase]=import_react35.useState(null),[cursorIndex,setCursorIndex]=import_react35.useState(0),[refreshTick,setRefreshTick]=import_react35.useState(0),[allFiles,setAllFiles]=import_react35.useState(null),[changes,setChanges]=import_react35.useState(null),[error,setError]=import_react35.useState(null),[expandedDirs,setExpandedDirs]=import_react35.useState(()=>new Set),pathRef=useLatest(props.worktreePath),tabRef=useLatest(tab),allFilesRef=useLatest(allFiles),changesRef=useLatest(changes),scopeRef=useLatest(scope),baseRef=useLatest(base),scopeManualRef=useLatest(scopeManual),onOpenFileRef=useLatest(props.onOpenFile),fetchSeq=import_react35.useRef(0),refetch=import_react35.useCallback(async(currentTab,path,signal)=>{let seq=++fetchSeq.current;if(path==null){setAllFiles(null),setChanges(null),setError(null);return}setError(null);try{if(currentTab==="all"){let files=await listFiles(path,signal);if(signal?.aborted||seq!==fetchSeq.current||pathRef.current!==path)return;setAllFiles((prev)=>sameFileList(prev,files)?prev:files)}else if(currentTab==="changes"){let wantBranch=scopeRef.current==="branch"&&baseRef.current!=null,entries=wantBranch?await statusFilesBranch(path,baseRef.current,signal):await statusFiles(path,signal);if(signal?.aborted||seq!==fetchSeq.current||pathRef.current!==path)return;if(!wantBranch&&entries.length===0&&!scopeManualRef.current&&baseRef.current!=null){setScope("branch");return}setChanges((prev)=>sameStatusEntries(prev,entries)?prev:entries)}}catch(err){if(signal?.aborted)return;let message=errorMessage(err);if(seq===fetchSeq.current&&pathRef.current===path)setError(message)}},[]);import_react35.useEffect(()=>{setAllFiles(null),setChanges(null),setError(null),setCursorIndex(0),setExpandedDirs(new Set),setScope("working"),setScopeManual(!1);let controller=new AbortController;return refetch(tabRef.current,props.worktreePath,controller.signal),()=>controller.abort()},[props.worktreePath,refetch]),import_react35.useEffect(()=>{let path=props.worktreePath;if(path==null){setBase(null);return}let disposed=!1,controller=new AbortController;return resolveBase(path,props.prBaseRef,controller.signal).then((b3)=>{if(!disposed)setBase(b3)}).catch(()=>{if(!disposed)setBase(null)}),()=>{disposed=!0,controller.abort()}},[props.worktreePath,props.prBaseRef]),import_react35.useEffect(()=>{if(tabRef.current!=="changes")return;let path=pathRef.current;if(path==null)return;let controller=new AbortController;return refetch("changes",path,controller.signal),()=>controller.abort()},[scope,base,refetch]),import_react35.useEffect(()=>{let path=props.worktreePath;if(path==null)return;if(readRoveEnv("FILETREE_WATCH")==="0")return;return watchWorktree(path,()=>setRefreshTick((n2)=>n2+1))},[props.worktreePath]),import_react35.useEffect(()=>{setCursorIndex(0);let path=pathRef.current;if(path==null)return;let controller=new AbortController;if(tab==="all"){if(allFilesRef.current==null)refetch("all",path,controller.signal)}else if(tab==="changes"){if(changesRef.current==null)refetch("changes",path,controller.signal)}return()=>controller.abort()},[tab,refetch]),import_react35.useEffect(()=>{if(refreshTick===0)return;let path=pathRef.current;if(path==null)return;let controller=new AbortController;return refetch(tabRef.current,path,controller.signal),()=>controller.abort()},[refreshTick,refetch]);let tree=import_react35.useMemo(()=>allFiles==null?null:buildTree(allFiles),[allFiles]),prevRows=import_react35.useRef([]),rows=import_react35.useMemo(()=>{let next=[];if(tab==="all"){if(tree!=null)flattenTree(tree,expandedDirs,0,next)}else if(tab==="changes"){if(changes!=null)next.push(...statusRows(changes,expandedDirs))}let reconciled=reconcileRows(prevRows.current,next);return prevRows.current=reconciled,reconciled},[tab,tree,expandedDirs,changes]);import_react35.useEffect(()=>{if(rows.length===0)return;setCursorIndex((i2)=>i2>rows.length-1?rows.length-1:i2)},[rows]);let statWidths=import_react35.useMemo(()=>computeStatWidths(rows),[rows]),paneWidth=props.paneWidth??dims.width,pathBudget=import_react35.useMemo(()=>computePathBudget(paneWidth,statWidths),[paneWidth,statWidths]);function applyNav(action){if(!action)return;if(action.type==="cursor")setCursorIndex(action.index);else if(action.type==="expand")setExpandedDirs((prev)=>new Set(prev).add(action.path));else setExpandedDirs((prev)=>toggleDir(prev,action.path))}let activateRow=import_react35.useCallback((row)=>{if(row.kind==="dir"||row.path.endsWith("/"))setExpandedDirs((prev)=>toggleDir(prev,row.path));else onOpenFileRef.current(row.path)},[]),handleRowActivate=import_react35.useCallback((row,index)=>{setCursorIndex(index),activateRow(row)},[activateRow]),markKeysUsed=usePaneHintMark("files");useBindings(()=>({enabled:props.focused??!0,bindings:fileTreeBindings({moveDown:()=>{if(markKeysUsed(),rows.length===0)return;setCursorIndex((i2)=>Math.min(i2+1,rows.length-1))},moveUp:()=>{if(markKeysUsed(),rows.length===0)return;setCursorIndex((i2)=>Math.max(i2-1,0))},setTab,currentTab:()=>tab,openCurrent:()=>{markKeysUsed();let row=rows[cursorIndex];if(row)activateRow(row)},mentionCurrent:()=>{let row=rows[cursorIndex];if(!row||row.kind==="dir"||row.path.endsWith("/"))return;props.onMention?.(row.path)},openExternal:()=>{let row=rows[cursorIndex];if(!row||row.kind==="dir"||row.path.endsWith("/"))return;if(!props.worktreePath)return;openExternally(`${props.worktreePath}/${row.path}`)},refresh:()=>{setRefreshTick((n2)=>n2+1)},toggleScope:()=>{if(tab!=="changes")return;if(base==null)return;setScopeManual(!0),setScope((s2)=>s2==="working"?"branch":"working")},openDiff:()=>{let row=rows[cursorIndex];if(!row)return;let spec=row.kind==="dir"||row.path.endsWith("/")?`${row.path.replace(/\/+$/,"")}/`:row.path;props.onOpenDiff?.(spec,scope==="branch"&&base!=null?base:void 0)},openDiffAll:()=>{props.onOpenDiff?.(".",scope==="branch"&&base!=null?base:void 0)},expandOrDescend:()=>applyNav(expandOrDescendAction(rows,cursorIndex)),collapseOrParent:()=>applyNav(collapseOrParentAction(rows,cursorIndex))})}));let loaded=tab==="all"&&allFiles!=null||tab==="changes"&&changes!=null;return $jsxs("box",{flexDirection:"column",flexGrow:1,paddingLeft:0,paddingRight:0,children:[$jsx(FileTreeHeaderView,{tab,scope,base,onSelectTab:setTab,onZenToggle:props.onZenToggle,onCreatePR:props.onCreatePR,onDiffAll:props.onOpenDiff?()=>props.onOpenDiff?.(".",scope==="branch"&&base!=null?base:void 0):void 0}),$jsx(FileTreeBodyView,{rows,cursorIndex,statWidths,pathBudget,onActivate:handleRowActivate,worktreePath:props.worktreePath,error,loaded,tab}),props.worktreePath!=null?$jsx("box",{flexDirection:"row",justifyContent:"flex-end",paddingTop:1,flexShrink:0,children:$jsx(PaneKeyHint,{pane:"files"})}):null]})}var WORKTREE_TOOLS_MIN_WIDTH=22,WORKTREE_TOOLS_MAX_WIDTH=34;function HostFilesPane(props){let{theme}=useTheme(),focus=useFocus(),dims=useTerminalDimensions(),inactiveBorder=theme.borderActive,available=Math.max(WORKTREE_TOOLS_MIN_WIDTH,dims.width-sidebarWidthFor(dims.width)),width=Math.max(WORKTREE_TOOLS_MIN_WIDTH,Math.min(WORKTREE_TOOLS_MAX_WIDTH,Math.floor(available/3)));return $jsx("box",{width,flexShrink:0,borderStyle:"rounded",borderColor:focus.focused==="files"?theme.focusAccent:inactiveBorder,onMouseUp:()=>focus.setFocused("files"),children:$jsx(FileTree,{worktreePath:props.worktree,paneWidth:width-2,prBaseRef:props.prBaseRef,focused:props.focused,onOpenFile:props.onOpenFile,onOpenDiff:props.onOpenDiff,onMention:props.onMention,onZenToggle:props.onZenToggle,onCreatePR:props.taskKind==="main"?void 0:props.onCreatePR})})}var EIGHTHS=["","\u258F","\u258E","\u258D","\u258C","\u258B","\u258A","\u2589"];function ratioBar(ratio,width=8){let cells=Math.min(1,Math.max(0,ratio))*width,full=Math.floor(cells),eighth=Math.round((cells-full)*8);if(eighth===8)full+=1,eighth=0;let partial=full<width?EIGHTHS[eighth]??"":"";return`${"\u2588".repeat(full)}${partial}`.padEnd(width,"\u2591")}var USAGE_BAR_WIDTH=10,toneOf=(percent)=>percent>=95?"crit":percent>=75?"warn":"ok",pad2=(n2)=>String(n2).padStart(2,"0");function formatReset(resetsAt,nowMs){if(resetsAt==null||resetsAt<=nowMs)return"";let d2=new Date(resetsAt),clock=`${pad2(d2.getHours())}:${pad2(d2.getMinutes())}`;if(resetsAt-nowMs<86400000)return`\u2192 ${clock}`;return`\u2192 ${d2.getMonth()+1}/${d2.getDate()} ${clock}`}function usageChips(usage,nowMs){return usage.windows.map((w3)=>({label:w3.label,percentText:`${w3.percent}%`,resetText:formatReset(w3.resetsAt,nowMs),tone:toneOf(w3.percent)}))}function narrowUsageChip(usage,nowMs){let w3=usage.windows.find((win)=>win.kind==="session")??usage.windows[0];if(!w3)return null;return{label:w3.label,percentText:`${w3.percent}%`,resetText:formatReset(w3.resetsAt,nowMs),tone:toneOf(w3.percent)}}function fullChipCells(chip,index){let label=index===0?chip.label:`\xB7 ${chip.label}`,parts=[displayWidth(label),displayWidth(chip.percentText)];if(chip.resetText)parts.push(displayWidth(chip.resetText));return parts.reduce((a2,b3)=>a2+b3,0)+(parts.length-1)}function fullVendorCells(vendor){return displayWidth(vendor.vendor)+vendor.chips.reduce((sum,chip,i2)=>sum+fullChipCells(chip,i2),0)+vendor.chips.length}function usageChipsBudget(opts){return Math.max(0,opts.terminalWidth-4-opts.hintCells)}function buildFooterChips(opts){let entries=[...opts.usage.entries()].map(([id,snapshot])=>({vendor:opts.vendorLabel(id).toUpperCase(),snapshot,chips:usageChips(snapshot,opts.nowMs)})).filter((entry)=>entry.chips.length>0);if(entries.length===0)return null;if(!opts.forceCompact){let fulls=entries.map((entry)=>({vendor:entry.vendor,chips:entry.chips}));if(fulls.reduce((sum,v3)=>sum+fullVendorCells(v3),0)+(fulls.length-1)*2<=opts.budget)return{form:"full",vendors:fulls}}let vendors=[],remaining=opts.budget;for(let entry of entries){let chip=narrowUsageChip(entry.snapshot,opts.nowMs);if(!chip)continue;let gap=vendors.length>0?2:0,need=displayWidth(entry.vendor)+1+displayWidth(chip.percentText);if(need+gap<=remaining){vendors.push({vendor:entry.vendor,percentText:chip.percentText,tone:chip.tone}),remaining-=need+gap;continue}let nameBudget=remaining-gap-1-displayWidth(chip.percentText);if(nameBudget>=3)vendors.push({vendor:truncateEndCells(entry.vendor,nameBudget,approxCharCells),percentText:chip.percentText,tone:chip.tone});break}return{form:"compact",vendors}}function contextChip(usage){if(!usage)return null;let window=usage.contextWindowTokens;if(window===void 0||window<=0)return null;let percent=Math.min(100,Math.max(0,Math.round(usage.contextTokens/window*100)));return{label:"ctx",percentText:`${percent}%${usage.approximate?"~":""}`,resetText:"",tone:toneOf(percent)}}function tokenTotalChip(usage){if(!usage)return null;if(usage.inputTokens===void 0&&usage.outputTokens===void 0)return null;return{label:"\u03A3",text:humanTokens((usage.inputTokens??0)+(usage.outputTokens??0))}}function humanTokens(total){if(total<1000)return String(total);if(total<1e6)return`${Math.floor(total/1000)}k`;return`${(Math.floor(total/1e5)/10).toFixed(1)}M`}function usageRows(usage,nowMs){let labelWidth=Math.min(8,usage.windows.reduce((w3,win)=>Math.max(w3,win.label.length),2));return usage.windows.map((w3)=>({label:(w3.label.length>labelWidth?w3.label.slice(0,labelWidth):w3.label).padEnd(labelWidth),bar:ratioBar(w3.percent/100,USAGE_BAR_WIDTH),percentText:`${String(w3.percent).padStart(3)}%`,resetText:formatReset(w3.resetsAt,nowMs),tone:toneOf(w3.percent)}))}function ContextChip(props){let{theme}=useTheme(),chip=props.chip;if(!chip)return null;let toneColor2={ok:theme.success,warn:theme.warning,crit:theme.error};return $jsxs("box",{flexDirection:"row",gap:1,flexShrink:0,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:chip.label}),$jsx("text",{fg:toneColor2[chip.tone],wrapMode:"none",children:chip.percentText})]})}function TokenChip(props){let{theme}=useTheme(),chip=props.chip;if(!chip)return null;return $jsxs("box",{flexDirection:"row",gap:1,flexShrink:0,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:chip.label}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:chip.text})]})}function UsageChips(props){let{theme}=useTheme(),usage=useAccessor(props.orchestrator.usageSnapshotSignal()),toneColor2={ok:theme.success,warn:theme.warning,crit:theme.error},now=Date.now(),view=usage&&usage.size>0?buildFooterChips({usage,budget:props.budget,nowMs:now,vendorLabel:engineDisplayName,forceCompact:props.narrow}):null;if(!view)return null;if(view.form==="full")return $jsx("box",{flexDirection:"row",gap:2,children:view.vendors.map((vendor)=>$jsxs("box",{flexDirection:"row",gap:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:vendor.vendor}),vendor.chips.map((chip,i2)=>$jsxs("box",{flexDirection:"row",gap:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:i2===0?chip.label:`\xB7 ${chip.label}`}),$jsx("text",{fg:toneColor2[chip.tone],wrapMode:"none",children:chip.percentText}),chip.resetText?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:chip.resetText}):null]},chip.label))]},vendor.vendor))});return $jsx("box",{flexDirection:"row",gap:2,children:view.vendors.map((vendor,index)=>$jsxs("box",{flexDirection:"row",gap:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:vendor.vendor}),$jsx("text",{fg:toneColor2[vendor.tone],wrapMode:"none",children:vendor.percentText})]},`${vendor.vendor}-${index}`))})}function WorkspaceFrame(props){let{theme}=useTheme(),dims=useTerminalDimensions(),narrow=isNarrowWidth(dims.width),usage=useAccessor(props.orchestrator.usageSnapshotSignal()),context=useAccessor(props.orchestrator.contextUsageSignal()),usageEntry=props.activeTaskId&&props.activeTabId?context?.get(`${props.activeTaskId}::${props.activeTabId}`):void 0,ctxChip=contextChip(usageEntry),tokChip=tokenTotalChip(usageEntry),hintItems=useStatusKeyHintItems({onOpenSettings:narrow?void 0:props.onOpenSettings,compact:narrow}),footerVisible=usage!=null&&usage.size>0||ctxChip!==null||tokChip!==null||hintItems.length>0,hintCells=hintItems.reduce((sum,item,index)=>sum+displayWidth(item.text)+(index>0?3:0),0),contextCells=11,tokenCells=tokChip?10:0,chipsBudget=Math.max(0,usageChipsBudget({terminalWidth:dims.width,hintCells})-11-tokenCells);return $jsx(ShortcutRevealProvider,{children:$jsxs("box",{flexDirection:"column",flexGrow:1,backgroundColor:theme.background,children:[props.banner,$jsx("box",{flexDirection:"row",flexGrow:1,children:props.children}),footerVisible?$jsxs("box",{flexDirection:"row",flexShrink:0,height:1,paddingLeft:1,paddingRight:1,gap:2,children:[$jsxs("box",{flexGrow:1,flexShrink:1,flexDirection:"row",gap:2,overflow:"hidden",children:[$jsx(ContextChip,{chip:ctxChip}),$jsx(TokenChip,{chip:tokChip}),$jsx(UsageChips,{orchestrator:props.orchestrator,narrow,budget:chipsBudget})]}),$jsx(StatusKeyHintBar,{onOpenSettings:narrow?void 0:props.onOpenSettings,compact:narrow})]}):null]})})}function workspacePagesClosed(s2){return!s2.dialogOpen&&!s2.settingsOpen&&!s2.worktreesOpen&&!s2.updateOpen}function settingsCloseKeysEnabled(s2){return s2.settingsOpen&&!s2.dialogOpen}var PANE_CYCLE=["sidebar","workspace","files"];function nextFocusedPane(current,delta,opts){let reachable=PANE_CYCLE.filter((pane)=>pane!=="files"||opts.filesVisible),idx=reachable.indexOf(current);if(idx<0)return(delta>0?reachable[reachable.length-1]:reachable[0])??null;let next=Math.min(Math.max(idx+delta,0),reachable.length-1);return next===idx?null:reachable[next]??null}function firePluginBinding(binding){let verb=binding.kind==="pane"?["plugin","pane","open",binding.target]:["plugin","action","invoke",binding.target],[cmd,...rest]=[...roveCliInvocation(),...verb];spawnDetached(cmd,rest,{onError:(err)=>console.warn(`[rove/plugins] ${binding.target}: ${String(err)}`)})}function usePluginKeybindings(enabled){useBindings(()=>({enabled,bindings:pluginKeybindings().map((binding)=>({key:binding.chord,cmd:()=>firePluginBinding(binding)}))}))}function useWorkspaceKeybindings(deps){let{focus,dialog}=deps,t3=useT(),renderer=useRenderer();function exitApp(){try{renderer?.destroy()}catch(err){console.error("Rove: renderer.destroy() failed during quit:",err)}process.exit(0)}async function quit(){if(await DialogConfirm.show(dialog,t3("workspace.quit.confirmTitle"),t3("workspace.quit.confirmBody"),t3("common.cancel"),t3("workspace.quit.confirmLabel")))exitApp()}function cyclePane(delta){let next=nextFocusedPane(focus.focused,delta,{filesVisible:deps.filesPaneVisible!==!1});if(next)focus.setFocused(next)}let pages={dialogOpen:deps.dialog.stack.length>0,settingsOpen:deps.pages.settingsOpen,worktreesOpen:deps.pages.worktreesOpen,updateOpen:deps.pages.updateOpen,kanbanOpen:deps.pages.kanbanOpen,automationsOpen:deps.pages.automationsOpen,workItemsOpen:deps.pages.workItemsOpen},pagesClosed=workspacePagesClosed(pages);useBindings(()=>({enabled:pagesClosed,bindings:[...bindByIds({"help.open":()=>HelpDialog.show(dialog,focus.focused),"focus.previous":prefixAction(()=>cyclePane(-1)),"focus.next":prefixAction(()=>cyclePane(1)),"workspace.zenToggle":prefixAction(()=>deps.toggleZen()),"view.redraw":prefixAction(()=>{if(renderer)redrawScreen(renderer)}),"attention.next":()=>deps.jumpToNextAttention(),"inbox.show":prefixAction(()=>deps.openInbox()),"kanban.open":prefixAction(()=>deps.pages.openKanban()),"automations.open":prefixAction(()=>deps.pages.openAutomations()),"workItems.open":prefixAction(()=>deps.pages.openWorkItems()),"task.moveMode":prefixAction(()=>deps.enterMoveMode()),"settings.open":prefixAction(()=>deps.pages.openSettings()),"files.createPR":prefixAction(()=>{let row=focus.focused==="sidebar"?deps.cursorTaskId():null;if(row!==null&&row!==deps.selectedId)deps.createPRFor(row);else deps.createPR()}),"files.fixChecks":prefixAction(()=>{let id=(focus.focused==="sidebar"?deps.cursorTaskId():null)??deps.selectedId;if(id)deps.fixChecksFor(id)}),"files.syncBase":prefixAction(()=>{let id=(focus.focused==="sidebar"?deps.cursorTaskId():null)??deps.selectedId;if(id)deps.syncBaseFor(id)}),"task.openEditor":prefixAction(()=>{let id=(focus.focused==="sidebar"?deps.cursorTaskId():null)??deps.selectedId;if(id)deps.openTaskWorktree(id)})})]})),useBindings(()=>({enabled:!pages.dialogOpen&&!pages.settingsOpen&&!deps.searchActive,bindings:bindByIds({"task.new.global":()=>deps.createTask()})})),useBindings(()=>({enabled:pagesClosed&&focus.focused!=="sidebar",bindings:bindByIds({"focus.sidebar":()=>focus.setFocused("sidebar")})})),useBindings(()=>({enabled:pagesClosed&&focus.focused==="sidebar"&&!deps.searchActive,bindings:bindByIds({"app.quit":(_evt,slot)=>{if(slot===1){exitApp();return}quit()},"settings.open.sidebar":()=>deps.pages.openSettings(),"worktrees.open.sidebar":()=>deps.pages.openWorktrees(),"tasks.update":()=>deps.pages.openUpdate()})})),useBindings(()=>({enabled:pagesClosed&&focus.focused==="sidebar"&&!deps.searchActive,bindings:bindByIds({"task.new":()=>deps.createTask(),"tasks.openWorktree":()=>{let id=deps.cursorTaskId();if(id)deps.openTaskWorktree(id)},"tasks.renameBranch":()=>{let id=deps.cursorTaskId();if(id)deps.renameBranch(id)},"tasks.cycleEngine":()=>{let id=deps.cursorTaskId();if(id)deps.cycleVendor(id)},"tasks.focusEngine":()=>focus.setFocused("workspace"),"sidebar.sort":()=>deps.toggleSortMode()})})),useBindings(()=>({enabled:settingsCloseKeysEnabled(pages),bindings:pageCloseBindings(deps.pages.closeSettings)})),usePluginKeybindings(pagesClosed)}var import_react60=__toESM(require_react_production(),1);var SIDEBAR_NAV_ITEMS=[{nav:"kanban",labelKey:"tasks.nav.kanban",bindingId:"kanban.open"},{nav:"automations",labelKey:"tasks.nav.automations",bindingId:"automations.open"},{nav:"issues",labelKey:"tasks.nav.issues",bindingId:"workItems.open"}];function focusPaneForNav(nav){return nav==="terminal"?"sidebar":"workspace"}import{TextAttributes as TextAttributes13}from"@opentui/core";var import_react42=__toESM(require_react_production(),1);function dividerRule(terminalWidth){return"\u2500".repeat(Math.max(1,terminalWidth))}var import_react39=__toESM(require_react_production(),1);function useCursorFollow(cursor){let scrolls=import_react39.useRef(new Set),rows=import_react39.useRef(new Map);return import_react39.useEffect(()=>{let el=rows.current.get(cursor);if(!el)return;for(let scroll of scrolls.current)if(scroll.viewport.height>0)scroll.scrollChildIntoView(el.id)},[cursor]),{scrollRef:(r2)=>{if(!r2)return;return scrolls.current.add(r2),()=>{scrolls.current.delete(r2)}},rowRef:(key)=>(r2)=>{if(!r2)return;return rows.current.set(key,r2),()=>{if(rows.current.get(key)===r2)rows.current.delete(key)}}}}var import_react40=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes11}from"@opentui/core";function relativeBuckets(absMs){let minutes=Math.floor(absMs/60000),hours=Math.floor(minutes/60);return{minutes,hours,days:Math.floor(hours/24)}}function relativeCountdown(deadlineMs,nowMs=Date.now()){return relativeAge(nowMs,deadlineMs)}function relativeAge(ms,nowMs=Date.now()){let delta=Math.max(0,nowMs-ms),secs=Math.floor(delta/1000);if(secs<60)return`${secs}s`;let{minutes,hours,days}=relativeBuckets(delta);if(minutes<60)return`${minutes}m`;if(hours<24)return`${hours}h`;return`${days}d`}var COMPOSER_FIELDS=["name","repo","target","targetTab","prompt","schedule","confirm"];function nextComposerField(field,delta=1,bound=!1){let fields=bound?COMPOSER_FIELDS:COMPOSER_FIELDS.filter((f2)=>f2!=="targetTab"),index=fields.indexOf(field);if(index<0)return"name";let next=(index+delta+fields.length)%fields.length;return fields[next]??"name"}var EMPTY_DRAFT={name:"",repo:"",prompt:"",schedule:"0 9 * * MON-FRI"};function canSubmitDraft(draft){return draft.name.trim().length>0&&draft.repo.trim().length>0&&draft.prompt.trim().length>0&&(!draft.target||draft.target.taskId.trim().length>0&&/^tab-[\w-]+$/.test(draft.target.tabId))&&isValidCron(draft.schedule.trim())}function firstIncompleteField(draft){if(draft.name.trim().length===0)return"name";if(draft.repo.trim().length===0)return"repo";if(draft.target&&!draft.target.taskId.trim())return"target";if(draft.target&&!/^tab-[\w-]+$/.test(draft.target.tabId))return"targetTab";if(draft.prompt.trim().length===0)return"prompt";if(!isValidCron(draft.schedule.trim()))return"schedule";return null}function previewSchedule(expression,nowMs){let trimmed=expression.trim();if(!isValidCron(trimmed))return{kind:"invalid"};let nextRunMs;try{nextRunMs=nextCronAfter(trimmed,nowMs)}catch{return{kind:"never"}}return{kind:"ok",nextRunMs,relative:formatRelative(nextRunMs-nowMs),absolute:formatAbsolute(nextRunMs,nowMs)}}function formatRelative(deltaMs){let{minutes,hours,days}=relativeBuckets(deltaMs);if(minutes<60)return t("automations.when.inMinutes",{n:Math.max(1,minutes)});if(hours<24)return t("automations.when.inHours",{n:hours});return t("automations.when.inDays",{n:days})}function formatAbsolute(atMs,nowMs){let at=new Date(atMs),time=`${String(at.getHours()).padStart(2,"0")}:${String(at.getMinutes()).padStart(2,"0")}`,now=new Date(nowMs);if(at.getFullYear()===now.getFullYear()&&at.getMonth()===now.getMonth()&&at.getDate()===now.getDate())return time;let withinWeek=atMs-nowMs<518400000,date=at.toLocaleDateString(intlLocale(),withinWeek?{weekday:"short"}:{weekday:"short",month:"short",day:"numeric"});return withinWeek?`${date} ${time}`:t("automations.when.dateTime",{date,time})}var CRON_SEGMENTS=["minute","hour","dayOfMonth","month","dayOfWeek"];function splitCron(expression){let parts=expression.trim().split(/\s+/).filter(Boolean);return CRON_SEGMENTS.map((_3,index)=>parts[index]??"*")}function joinCron(parts){return CRON_SEGMENTS.map((_3,index)=>parts[index]??"*").join(" ")}var MINUTE_LADDER=["*","*/5","*/10","*/15","*/30",...range(0,59)],HOUR_LADDER=["*","*/2","*/3","*/4","*/6","*/12",...range(0,23)],DOM_LADDER=["*",...range(1,31)],MONTH_LADDER=["*","JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"],DOW_LADDER=["*","MON-FRI","SAT,SUN","MON","TUE","WED","THU","FRI","SAT","SUN"],DOW_CODES=["MON","TUE","WED","THU","FRI","SAT","SUN"];function range(from,to){let out=[];for(let n2=from;n2<=to;n2++)out.push(String(n2));return out}var LADDERS={minute:MINUTE_LADDER,hour:HOUR_LADDER,dayOfMonth:DOM_LADDER,month:MONTH_LADDER,dayOfWeek:DOW_LADDER};function stepSegment(segment,current,delta){let ladder=LADDERS[segment],index=ladder.indexOf(current.trim().toUpperCase());if(index<0)return(delta>0?ladder[0]:ladder[ladder.length-1])??current;let next=(index+delta+ladder.length)%ladder.length;return ladder[next]??current}function moveSegmentCursor(cursor,delta){return Math.min(Math.max(cursor+delta,0),CRON_SEGMENTS.length-1)}function setSegment(expression,index,value){let parts=splitCron(expression);if(index<0||index>=CRON_SEGMENTS.length)return joinCron(parts);return parts[index]=value,joinCron(parts)}function describeCron(expression){let[minute,hour,dom,month,dow]=splitCron(expression);if(month!=="*"||dom!=="*")return null;if(minute===void 0||hour===void 0||dow===void 0)return null;let timeOfDay=describeTimeOfDay(minute,hour);if(!timeOfDay)return null;let{at,bare}=timeOfDay;if(dow==="*")return bare?at:t("automations.schedule.everyDay",{at});if(dow==="MON-FRI")return t("automations.schedule.weekdays",{at});if(dow==="SAT,SUN")return t("automations.schedule.weekends",{at});let code=DOW_CODES.find((candidate)=>candidate===dow.toUpperCase());if(code)return t("automations.schedule.onWeekday",{weekday:t(`automations.schedule.dow.${code}`),at});return null}function describeTimeOfDay(minute,hour){if(hour==="*"){if(minute==="*")return{at:t("automations.schedule.everyMinute"),bare:!0};if(minute.startsWith("*/"))return{at:t("automations.schedule.everyMinutes",{n:minute.slice(2)}),bare:!0};if(/^\d+$/.test(minute))return{at:t("automations.schedule.hourlyAt",{minute:minute.padStart(2,"0")}),bare:!1};return null}if(hour.startsWith("*/")&&minute==="0")return{at:t("automations.schedule.everyHours",{n:hour.slice(2)}),bare:!0};if(/^\d+$/.test(hour)&&/^\d+$/.test(minute)){let time=`${hour.padStart(2,"0")}:${minute.padStart(2,"0")}`;return{at:t("automations.schedule.atClock",{time}),bare:!1}}return null}function fuzzyMatch(query,haystack){if(!query)return!0;let q2=query.toLowerCase(),h2=haystack.toLowerCase(),qi=0;for(let hi=0;hi<h2.length&&qi<q2.length;hi++)if(h2.charCodeAt(hi)===q2.charCodeAt(qi))qi++;return qi===q2.length}function compareRecent(a2,b3){let byTime=taskTime(b3)-taskTime(a2);if(byTime!==0)return byTime;return String(b3.id).localeCompare(String(a2.id))}function taskTime(task){let parsed=Date.parse(task.updatedAt||task.createdAt);return Number.isFinite(parsed)?parsed:0}function repoBasename(repo){let segments=repo.split("/").filter(Boolean);return segments[segments.length-1]??repo}function sidebarProjectKey(repo){return repo.trim().replace(/[\\/]+$/,"")||repo}function sidebarProjectLabel(repo,repos){let base=repoBasename(repo);if(!repos.some((r2)=>r2!==repo&&repoBasename(r2)===base))return base;return repo.replace(/[\\/]+$/,"").split(/[\\/]+/).slice(-2).join("/")}import{TextAttributes as TextAttributes10}from"@opentui/core";function PickerList(props){let{theme}=useTheme(),t3=useT(),below=props.window.total-props.window.start-props.window.items.length;return $jsxs("box",{gap:0,paddingLeft:2,paddingBottom:props.paddingBottom,children:[props.window.start>0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("newTask.picker.moreAbove",{count:props.window.start})}):null,props.rows.map((row,i2)=>{let absoluteIndex=props.window.start+i2,isCursor=absoluteIndex===props.cursor,fg=isCursor?theme.primary:row.accent?theme.accent:theme.textMuted,attributes=isCursor?TextAttributes10.BOLD:void 0;if(!row.dim)return $jsxs("text",{fg,attributes,wrapMode:"none",onMouseUp:()=>props.onPick(absoluteIndex),children:[isCursor?"\u25B8 ":" ",row.body]},row.key);return $jsxs("box",{flexDirection:"row",onMouseUp:()=>props.onPick(absoluteIndex),children:[$jsxs("text",{fg,attributes,wrapMode:"none",flexShrink:0,children:[isCursor?"\u25B8 ":" ",row.body]}),$jsx("box",{flexGrow:1}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:1,children:` ${row.dim}`})]},row.key)}),below>0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("newTask.picker.moreBelow",{count:below})}):null,props.footer]})}function AutomationComposerView(props){let{theme}=useTheme(),dialog=useDialog(),t3=useT(),padX=useDialogPaddingX(),[draft,setDraft]=import_react40.useState(()=>({...EMPTY_DRAFT,repo:props.defaultRepo??props.repos[0]??""})),[field,setField]=import_react40.useState("name"),[repoCursor,setRepoCursor]=import_react40.useState(()=>{let at=props.repos.indexOf(props.defaultRepo??"");return at>=0?at:0}),[error,setError]=import_react40.useState(null),[segmentCursor,setSegmentCursor]=import_react40.useState(0),segmentValues=splitCron(draft.schedule),selectSegment=(index)=>{setField("schedule"),setSegmentCursor(Math.min(Math.max(index,0),CRON_SEGMENTS.length-1))},cancel=()=>{props.onCancel(),dialog.clear()},patch=(next)=>{setDraft((prev)=>({...prev,...next})),setError(null)},pickRepoAt=(index)=>{let repo=props.repos[clampCursor(index,props.repos.length)];if(!repo)return;setRepoCursor(clampCursor(index,props.repos.length)),patch({repo,target:void 0})};function commit(){if(canSubmitDraft(draft)){props.onSubmit({name:draft.name.trim(),repo:draft.repo.trim(),prompt:draft.prompt.trim(),schedule:draft.schedule.trim(),...draft.target?{target:draft.target}:{}}),dialog.clear();return}let gap=firstIncompleteField(draft);if(gap)setField(gap),setError(t3(`automations.missing.${gap}`))}let preview=previewSchedule(draft.schedule,Date.now()),repoWindow=windowAround(props.repos,repoCursor),repoRows=repoWindow.items.map((repo,index)=>({key:repo,body:sidebarProjectLabel(repo,props.repos),accent:repoWindow.start+index===repoCursor})),targets=props.tasks.filter((task)=>task.repo===draft.repo),targetCursor=draft.target?targets.findIndex((task)=>task.id===draft.target?.taskId)+1:0;function pickTarget(delta){let index=(targetCursor+delta+targets.length+1)%(targets.length+1),task=targets[index-1];patch({target:task?{kind:"existing-tab",taskId:task.id,tabId:"tab-1"}:void 0})}let targetLabel=draft.target?targets[targetCursor-1]?.title??draft.target.taskId:t3("automations.targetFresh");return useBindings(()=>({bindings:[{key:"tab",cmd:()=>setField((f2)=>nextComposerField(f2,1,Boolean(draft.target)))},{key:"shift+tab",cmd:()=>setField((f2)=>nextComposerField(f2,-1,Boolean(draft.target)))},...field==="target"?[{key:"up",cmd:()=>pickTarget(-1)},{key:"down",cmd:()=>pickTarget(1)}]:[],...field==="repo"?[{key:"up",cmd:()=>pickRepoAt(repoCursor-1)},{key:"down",cmd:()=>pickRepoAt(repoCursor+1)}]:[],...field==="schedule"?[{key:"left",cmd:()=>setSegmentCursor((c2)=>moveSegmentCursor(c2,-1))},{key:"right",cmd:()=>setSegmentCursor((c2)=>moveSegmentCursor(c2,1))},{key:"up",cmd:()=>{let seg=CRON_SEGMENTS[segmentCursor];if(!seg)return;patch({schedule:setSegment(draft.schedule,segmentCursor,stepSegment(seg,segmentValues[segmentCursor]??"*",1))})}},{key:"down",cmd:()=>{let seg=CRON_SEGMENTS[segmentCursor];if(!seg)return;patch({schedule:setSegment(draft.schedule,segmentCursor,stepSegment(seg,segmentValues[segmentCursor]??"*",-1))})}}]:[],...field==="confirm"?[{key:"return",cmd:()=>commit()}]:[]]})),$jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:1,children:[$jsx(DialogHeader,{title:t3("automations.newTitle"),onClose:()=>cancel()}),$jsx(DialogSection,{label:t3("automations.fieldName"),focused:field==="name",onPress:()=>setField("name"),children:$jsx(DialogField,{focused:field==="name",children:$jsx("input",{value:draft.name,placeholder:t3("automations.namePlaceholder"),focused:field==="name",onMouseUp:()=>setField("name"),onInput:(v3)=>patch({name:v3}),onSubmit:()=>setField(nextComposerField("name"))})})}),$jsx(DialogSection,{label:t3("automations.fieldRepo"),focused:field==="repo",hint:props.repos.length===0?void 0:"\u2191/\u2193",onPress:()=>setField("repo"),children:props.repos.length===0?$jsx("text",{fg:theme.textMuted,children:t3("automations.needRepo")}):$jsx(DialogField,{focused:field==="repo",children:$jsx(PickerList,{window:repoWindow,cursor:repoCursor,rows:repoRows,onPick:pickRepoAt})})}),$jsx(DialogSection,{label:t3("automations.fieldTarget"),focused:field==="target",hint:"\u2191/\u2193",onPress:()=>setField("target"),children:$jsx(DialogField,{focused:field==="target",children:$jsx("text",{fg:theme.text,onMouseUp:()=>{setField("target"),pickTarget(1)},children:targetLabel})})}),draft.target?$jsx(DialogSection,{label:t3("automations.fieldTargetTab"),focused:field==="targetTab",onPress:()=>setField("targetTab"),children:$jsx(DialogField,{focused:field==="targetTab",children:$jsx("input",{value:draft.target.tabId,focused:field==="targetTab",onMouseUp:()=>setField("targetTab"),onInput:(tabId)=>{if(draft.target)patch({target:{...draft.target,tabId}})},onSubmit:()=>setField("prompt")})})}):null,$jsx(DialogSection,{label:t3("automations.fieldPrompt"),focused:field==="prompt",onPress:()=>setField("prompt"),children:$jsx(DialogField,{focused:field==="prompt",children:$jsx("input",{value:draft.prompt,placeholder:t3("automations.promptPlaceholder"),focused:field==="prompt",onMouseUp:()=>setField("prompt"),onInput:(v3)=>patch({prompt:v3}),onSubmit:()=>setField(nextComposerField("prompt"))})})}),$jsx(DialogSection,{label:t3("automations.fieldSchedule"),focused:field==="schedule",hint:"\u2190/\u2192 \u2191/\u2193",onPress:()=>setField("schedule"),children:$jsxs(DialogField,{focused:field==="schedule",children:[$jsx("box",{flexDirection:"row",gap:2,children:CRON_SEGMENTS.map((segment,index)=>{let activeCell=field==="schedule"&&index===segmentCursor;return $jsxs("box",{flexDirection:"column",onMouseUp:()=>selectSegment(index),children:[$jsx("text",{fg:activeCell?theme.primary:theme.text,attributes:activeCell?TextAttributes11.BOLD|TextAttributes11.UNDERLINE:void 0,wrapMode:"none",children:segmentValues[index]??"*"}),$jsx("text",{fg:activeCell?theme.textMuted:theme.borderSubtle,wrapMode:"none",children:t3(`automations.cronField.${segment}`)})]},segment)})}),preview.kind==="ok"?$jsx("text",{fg:theme.success,wrapMode:"none",children:`${describeCron(draft.schedule)??""}${describeCron(draft.schedule)?" \xB7 ":""}${preview.relative} \xB7 ${preview.absolute}`}):$jsx("text",{fg:theme.error,wrapMode:"none",children:preview.kind==="never"?t3("automations.cronNever"):t3("automations.cronInvalid")})]})}),error?$jsxs("text",{fg:theme.error,wrapMode:"word",children:["\u203B ",error]}):null,$jsx(DialogFooter,{children:t3("automations.composerLegend")}),$jsx(DialogActions,{label:t3("common.create"),focused:field==="confirm",onPress:()=>commit()})]})}var AutomationComposer={show(dialog,opts){return showDialog(dialog,(resolve)=>$jsx(AutomationComposerView,{repos:opts.repos,tasks:opts.tasks??[],...opts.defaultRepo?{defaultRepo:opts.defaultRepo}:{},onSubmit:(draft)=>resolve(draft),onCancel:()=>resolve(void 0)}))}};function formatWhen(iso,now){if(!iso)return"\u2014";let at=Date.parse(iso);if(!Number.isFinite(at))return"\u2014";let deltaMs=at-now,ahead=deltaMs>=0,{minutes,hours}=relativeBuckets(Math.abs(deltaMs));if(minutes<1)return t(ahead?"automations.when.now":"automations.when.justNow");if(minutes<60)return t(ahead?"automations.when.inMinutes":"automations.when.minutesAgo",{n:minutes});if(hours<24)return t(ahead?"automations.when.inHours":"automations.when.hoursAgo",{n:hours});return new Date(at).toLocaleDateString(intlLocale())}function formatRunStatus(status,translate){let key=`automations.runStatus.${status}`,label=translate(key);return label===key?status:label}import{TextAttributes as TextAttributes12}from"@opentui/core";var RUN_TONE={dispatched:"success",revived:"success",deferred:"warning",skipped_precheck:"muted",skipped_cancelled:"muted",skipped_missed:"warning",skipped_unavailable:"warning",dispatch_failed:"error"};function runToneColor(status,theme){let tone=RUN_TONE[status]??"muted";if(tone==="success")return theme.success;if(tone==="warning")return theme.warning;if(tone==="error")return theme.error;return theme.textMuted}function runGlyph(status){let tone=RUN_TONE[status]??"muted";if(tone==="success")return"\u2713";if(tone==="error")return"\u2020";if(tone==="warning")return"!";return"\xB7"}function triggerGlyph(trigger){return trigger==="manual"?"\u25B8":"\xB7"}function outputTail(text,limit=10){let lines=text.replace(/\s+$/,"").split(`
21
21
  `);return lines.length>limit?lines.slice(-limit):lines}function PrecheckDetail(props){let{theme}=useTheme(),t3=useT(),result=props.run?.precheckResult;if(!result)return null;let exit=result.timedOut?t3("automations.precheckTimedOut"):t3("automations.precheckExited",{code:String(result.exitCode??"?")}),streams=[{label:t3("automations.precheckStdout"),text:result.stdout},{label:t3("automations.precheckStderr"),text:result.stderr}].filter((stream)=>stream.text.trim().length>0);return $jsxs("box",{flexDirection:"column",marginTop:1,flexShrink:0,children:[$jsx("text",{attributes:TextAttributes12.BOLD,fg:theme.textMuted,children:t3("automations.precheckDetail",{exit,duration:String(result.durationMs)})}),streams.length===0?$jsx("text",{fg:theme.textMuted,children:t3("automations.precheckNoOutput")}):streams.map((stream)=>$jsxs("box",{flexDirection:"row",gap:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:`${stream.label}:`}),$jsx("text",{fg:theme.text,flexShrink:1,children:outputTail(stream.text).join(`
22
22
  `)})]},stream.label))]})}function RunHistory(props){let{theme}=useTheme(),t3=useT(),runs=props.runs;return $jsxs($Fragment,{children:[$jsx("text",{attributes:TextAttributes12.BOLD,fg:theme.text,children:t3("automations.recentRuns")}),runs.length===0?$jsx("text",{fg:theme.textMuted,children:t3("automations.noRuns")}):runs.slice(0,5).map((run)=>{return $jsx("text",{fg:runToneColor(run.status,theme),children:`${triggerGlyph(run.trigger)} #${run.runNumber} ${formatRunStatus(run.status,t3)}${run.tabId?` \xB7 ${run.tabId}`:""}${run.deferredId?` \xB7 ${t3("automations.queuedReceipt",{id:run.deferredId})}`:""}${run.error?` \u2014 ${run.error}`:""} ${formatWhen(run.at,props.now)}`},run.id)}),$jsx(PrecheckDetail,{run:runs[0]})]})}var POLL_MS=5000;function repoLabel(repo){return repo.split("/").filter(Boolean).pop()??repo}function AutomationsPage(props){let{theme}=useTheme(),dialog=useDialog(),t3=useT(),dims=useTerminalDimensions(),notif=useNotifications();function notifyError(message){notif.notify({kind:"error",taskId:"",tabId:"",title:message})}let[automations,setAutomations]=import_react42.useState(null),[keepsDaemonAlive,setKeepsDaemonAlive]=import_react42.useState(!1),[lastRunStatus,setLastRunStatus]=import_react42.useState({}),[runs,setRuns]=import_react42.useState([]),[reloadTick,setReloadTick]=import_react42.useState(0),[busyId,setBusyId]=import_react42.useState(null),[notice,setNotice]=import_react42.useState(null),refetch=()=>setReloadTick((tick)=>tick+1);import_react42.useEffect(()=>{let disposed=!1,orch=props.orchestrator;if(!orch){setAutomations([]);return}let load=()=>{orch.listAutomations().then((result)=>{if(disposed)return;setAutomations(result.automations),setKeepsDaemonAlive(result.keepsDaemonAlive),setLastRunStatus(result.lastRunStatus??{})}).catch(()=>{if(!disposed)setAutomations((prev)=>prev??[])})};load();let timer=setInterval(load,POLL_MS);return()=>{disposed=!0,clearInterval(timer)}},[props.orchestrator,reloadTick]);let rows=automations??[],needAttention=rows.filter((a2)=>{let status=lastRunStatus[a2.id];return status!==void 0&&automationRunNeedsAttention(status)}).length,[cursor,setCursor]=import_react42.useState(0);import_react42.useEffect(()=>{setCursor((c2)=>clampCursor(c2,rows.length))},[rows.length]);let selected=rows[cursor],follow=useCursorFollow(cursor);import_react42.useEffect(()=>{let disposed=!1,orch=props.orchestrator;if(!orch||!selected){setRuns([]);return}return orch.automationRuns(selected.id).then((result)=>{if(!disposed)setRuns(result.runs)}).catch(()=>{if(!disposed)setRuns([])}),()=>{disposed=!0}},[props.orchestrator,selected,reloadTick]),import_react42.useEffect(()=>{setNotice(null)},[selected?.id]);async function toggleEnabled(){let orch=props.orchestrator;if(!orch||!selected||busyId)return;setBusyId(selected.id);try{await orch.setAutomationEnabled(selected.id,!selected.enabled),refetch()}catch(err){console.error("[rove automations] toggle failed:",err),notifyError(t3(selected.enabled?"automations.disableFailed":"automations.enableFailed",{name:selected.name,error:errorMessage(err)}))}finally{setBusyId(null)}}async function runNow(){let orch=props.orchestrator;if(!orch||!selected||busyId)return;setBusyId(selected.id),setNotice(t3("automations.running",{name:selected.name}));try{let result=await orch.runAutomationNow(selected.id);setNotice(t3("automations.ranWith",{name:selected.name,status:result.status})),refetch()}catch(err){console.error("[rove automations] run now failed:",err),notifyError(t3("automations.runFailed",{name:selected.name,error:errorMessage(err)}))}finally{setBusyId(null)}}async function createAutomation(){let orch=props.orchestrator;if(!orch||busyId)return;let repos=[...new Set([...getSavedRepos(),...orch.listTasks().map((task)=>task.repo)])].filter(Boolean);if(repos.length===0){setNotice(t3("automations.needRepo"));return}let draft=await AutomationComposer.show(dialog,{repos,tasks:orch.listTasks().filter((task)=>!task.deletion),...props.focusRepo?{defaultRepo:props.focusRepo}:{}});if(!draft)return;setBusyId("new");try{await orch.createAutomation(draft),refetch()}catch(err){console.error("[rove automations] create failed:",err),notifyError(t3("automations.createFailed",{error:errorMessage(err)}))}finally{setBusyId(null)}}async function requestDelete(){let orch=props.orchestrator;if(!orch||!selected||busyId)return;if(await DialogConfirm.show(dialog,t3("automations.deleteTitle"),t3("automations.deleteBody",{name:selected.name}),t3("common.cancel"),t3("automations.deleteButton"),{danger:!0})!==!0)return;setBusyId(selected.id);try{await orch.deleteAutomation(selected.id),refetch()}catch(err){console.error("[rove automations] delete failed:",err),notifyError(t3("automations.deleteFailed",{name:selected.name,error:errorMessage(err)}))}finally{setBusyId(null)}}useBindings(()=>({enabled:props.focused!==!1,bindings:[...pageCloseBindings(props.onClose),{key:"j",cmd:()=>setCursor((c2)=>clampCursor(c2+1,rows.length))},{key:"down",cmd:()=>setCursor((c2)=>clampCursor(c2+1,rows.length))},{key:"k",cmd:()=>setCursor((c2)=>clampCursor(c2-1,rows.length))},{key:"up",cmd:()=>setCursor((c2)=>clampCursor(c2-1,rows.length))},{key:"n",cmd:()=>void createAutomation()},{key:"r",cmd:()=>refetch()},{key:"e",cmd:()=>void toggleEnabled()},{key:"s",cmd:()=>void runNow()},{key:"d",cmd:()=>void requestDelete()},{key:"return",cmd:()=>{let taskId=runs[0]?.taskId;if(taskId)props.onOpenTask?.(taskId);else if(runs.length>0)setNotice(t3("automations.latestRunNoTask"))}}]}));let now=Date.now();return $jsxs("box",{flexDirection:"column",flexGrow:1,paddingTop:1,paddingLeft:2,paddingRight:2,children:[$jsxs("box",{flexDirection:"row",gap:1,flexShrink:0,children:[$jsx("text",{attributes:TextAttributes13.BOLD,fg:theme.text,wrapMode:"none",flexShrink:0,children:t3("automations.title")}),$jsx("text",{fg:theme.borderSubtle,wrapMode:"none",flexBasis:0,flexGrow:1,flexShrink:1,children:dividerRule(dims.width)}),needAttention>0?$jsx("text",{fg:theme.error,wrapMode:"none",flexShrink:0,children:t3("automations.needAttention",{count:String(needAttention),total:String(rows.length)})}):null,$jsx("text",{fg:keepsDaemonAlive?theme.success:theme.textMuted,wrapMode:"none",flexShrink:0,children:keepsDaemonAlive?t3("automations.holdingDaemon"):t3("automations.notHolding")})]}),automations===null?$jsx("box",{paddingTop:1,children:$jsx("text",{fg:theme.textMuted,children:t3("common.loading")})}):rows.length===0?$jsxs("box",{flexDirection:"column",paddingTop:1,gap:1,children:[$jsx("text",{fg:theme.textMuted,children:t3("automations.empty")}),$jsx("text",{fg:theme.text,children:t3("automations.emptyHint")})]}):$jsx("scrollbox",{ref:follow.scrollRef,flexGrow:1,flexShrink:1,flexBasis:0,marginTop:1,verticalScrollbarOptions:{trackOptions:{foregroundColor:"transparent"}},children:rows.map((automation,index)=>{let isCursor=index===cursor,lastRun=lastRunStatus[automation.id];return $jsxs("box",{ref:follow.rowRef(index),flexDirection:"row",flexShrink:0,...FRAME,borderColor:isCursor?theme.borderActive:theme.borderSubtle,paddingLeft:1,paddingRight:1,gap:1,...isCursor?{backgroundColor:theme.backgroundElement}:{},children:[$jsx("text",{fg:automation.enabled?theme.text:theme.textMuted,attributes:isCursor?TextAttributes13.BOLD:void 0,wrapMode:"none",flexShrink:1,children:automation.name}),$jsx("text",{fg:theme.borderSubtle,wrapMode:"none",flexBasis:0,flexGrow:1,flexShrink:1,children:dividerRule(dims.width)}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:1,children:`${repoLabel(automation.repo)} \xB7 ${automation.schedule}`}),automation.enabled?null:$jsx("text",{fg:theme.warning,wrapMode:"none",flexShrink:0,children:`${t3("automations.paused")} \xB7`}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:formatWhen(automation.nextRunAt,now)}),$jsx("text",{fg:lastRun?runToneColor(lastRun,theme):theme.textMuted,wrapMode:"none",flexShrink:0,width:1,children:lastRun?runGlyph(lastRun):" "})]},automation.id)})}),$jsx("box",{flexDirection:"column",marginTop:1,...FRAME,borderColor:theme.border,padding:1,flexShrink:0,children:selected?$jsxs($Fragment,{children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",gap:2,children:[$jsx("text",{fg:theme.text,wrapMode:"none",flexShrink:1,flexGrow:1,children:selected.prompt}),$jsx("text",{fg:busyId===selected.id?theme.textMuted:theme.primary,attributes:TextAttributes13.BOLD,wrapMode:"none",flexShrink:0,onMouseUp:()=>void runNow(),children:t3("automations.runNow")})]}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:selected.target?t3("automations.targetExisting",{task:props.orchestrator?.listTasks().find((task)=>task.id===selected.target?.taskId)?.title??selected.target.taskId,tab:selected.target.tabId}):t3(selected.persistentSession?"automations.targetStanding":"automations.targetFresh")}),selected.precheck?$jsx("text",{fg:theme.textMuted,children:t3("automations.precheck",{command:selected.precheck.command})}):null,$jsx(RunHistory,{runs,now})]}):$jsx("text",{fg:theme.textMuted,children:t3("automations.noSelection")})}),notice?$jsx("text",{fg:theme.textMuted,children:notice}):null]})}import{TextAttributes as TextAttributes17}from"@opentui/core";var import_react49=__toESM(require_react_production(),1);var DISPOSITIONS={backlog:"active",in_progress:"active",in_review:"parked",error:"parked",done:"terminal",canceled:"terminal",open:"active",doing:"active",hold:"parked"};function statusDisposition(status){return DISPOSITIONS[status]??"parked"}var BOARD_COLUMN_ORDER=["backlog","in_progress","parked","done"],COLUMN_CAP=20;function moveBoardSelection(columns,currentId,dir){let firstVisible=columns.find((column)=>column.issues.length>0)?.issues[0]?.id??null;if(currentId==null)return firstVisible;let col=-1,row=-1;for(let[c2,column]of columns.entries()){let r2=column.issues.findIndex((issue)=>issue.id===currentId);if(r2!==-1){col=c2,row=r2;break}}if(col===-1)return firstVisible;if(dir==="up"||dir==="down"){let column=columns[col]?.issues??[],next=dir==="up"?row-1:row+1;return column[Math.max(0,Math.min(next,column.length-1))]?.id??currentId}let step=dir==="left"?-1:1;for(let c2=col+step;c2>=0&&c2<columns.length;c2+=step){let column=columns[c2]?.issues??[];if(column.length===0)continue;return column[Math.min(row,column.length-1)]?.id??currentId}return currentId}function issueColumnKey(issue,taskExists){let disposition=statusDisposition(issue.status);if(disposition==="terminal")return"done";if(disposition==="parked")return"parked";if(issue.taskId!==void 0&&issue.taskId!==""&&(taskExists?.(issue.taskId)??!0))return"in_progress";if(issue.status==="doing")return"in_progress";return"backlog"}var BOARD_ATTENTION_STATES=["permission_needed","rate_limited","error","dead"];function isBoardAttentionState(state){return state!==void 0&&BOARD_ATTENTION_STATES.includes(state)}function applyBoardAttention(columns,stateOf){let attentionCount=0;return{columns:columns.map((col)=>{if(col.key!=="in_progress")return col;let attention=[],rest=[];for(let issue of col.issues)if(issue.taskId!==void 0&&issue.taskId!==""&&isBoardAttentionState(stateOf(issue.taskId)))attention.push(issue);else rest.push(issue);return attentionCount=attention.length,attention.length===0?col:{...col,issues:[...attention,...rest]}}),attentionCount}}function compareIssues(a2,b3){if(a2.created!==b3.created)return a2.created<b3.created?1:-1;return b3.id-a2.id}function buildIssueBoard(issues,taskExists){let buckets={backlog:[],in_progress:[],parked:[],done:[]};for(let issue of issues)buckets[issueColumnKey(issue,taskExists)].push(issue);return BOARD_COLUMN_ORDER.map((key)=>{let capped=key==="done"||key==="parked",sorted=buckets[key].sort(compareIssues);if(!capped||sorted.length<=COLUMN_CAP)return{key,issues:sorted,hiddenCount:0};return{key,issues:sorted.slice(0,COLUMN_CAP),hiddenCount:sorted.length-COLUMN_CAP}})}var import_react43=__toESM(require_react_production(),1);function planRound(attempts,title){let n2=Math.max(1,Math.trunc(attempts));if(n2===1)return[title?{title}:{}];let groupId=ulid();return Array.from({length:n2},(_3,i2)=>({groupId,...title?{title:`${title} #${i2+1}/${n2}`}:{}}))}var realDeliver=async(rpc,taskId,prompt)=>(await startTaskSessionWithPromptAdapter(rpc,taskId,prompt)).started;async function runQuickForkRound(orch,repo,input,deliver=realDeliver){setRepoLastActiveVendor(repo,input.vendor),addSavedRepo(repo);let plan=planRound(input.attempts),created=[],failures=[];for(let sibling of plan)try{let task=await orch.createTask({repo,baseRef:input.baseRef,vendor:input.vendor,...sibling});created.push(task.id)}catch(err){failures.push(`create: ${errorMessage(err)}`);break}let settled=await Promise.allSettled(created.map((id)=>deliver(orch.rpc,id,input.prompt))),started2=[];return settled.forEach((result,i2)=>{let id=created[i2]??"";if(result.status==="fulfilled"&&result.value){started2.push(id);return}failures.push(result.status==="rejected"?`${id}: ${errorMessage(result.reason)}`:`${id}: prompt not delivered`)}),await Promise.all(created.map((id)=>orch.setPrompt(id,input.prompt).catch(()=>{return}))),{started:started2,failures,created}}function quickForkComposerOptions(repo,engines,defaultVendor,branchFrom=repo){return{repoLabel:repoBasename(repo),engines,defaultVendor,defaultBaseRef:getCurrentBranch(branchFrom)??getCurrentBranch(repo)??DEFAULT_BASE_REF,engineLabel:engineDisplayName}}function quickForkDefaultVendor(repo,detected){let pref=resolvePreferredVendor(repo);if(detected.length===0||detected.includes(pref))return pref;return detected[0]??pref}async function createQuickForkTask(orch,repo,baseRef,vendor){return setRepoLastActiveVendor(repo,vendor),addSavedRepo(repo),orch.createTask({repo,baseRef,vendor})}async function runQuickFork(orch,repo,result,hooks){try{let task=await createQuickForkTask(orch,repo,result.baseRef,result.vendor);return hooks.selectTask(task.id),await hooks.enterTask(task.id),task.id}catch(err){console.error("[rove workspace] quick-fork task.create failed:",err),hooks.notifyError(t("tasks.toast.forkFailed",{error:userFacingErrorMessage(err)}));return}}async function runAgainTask(orch,task,hooks){let prompt=task.prompt;if(prompt===void 0)return;let baseRef=task.baseRef??getCurrentBranch(task.worktreePath||task.repo)??DEFAULT_BASE_REF,vendor=task.vendor??DEFAULT_TASK_VENDOR,taskId=await runQuickFork(orch,task.repo,{baseRef,vendor},hooks);if(taskId===void 0)return;return await orch.setPrompt(taskId,prompt).catch(()=>{return}),taskId}function useQuickFork(orch,hooks){let[pending,setPending]=import_react43.useState(null);async function onQuickFork(repo,result){let prompt=appendAttachmentRefs(result.prompt,result.attachments);if(result.attempts>1){let outcome=await runQuickForkRound(orch,repo,{...result,prompt,attempts:result.attempts});if(outcome.failures.length>0){hooks.notifyError(`${hooks.t("quickTask.roundPartial",{ok:outcome.started.length,count:result.attempts,failed:outcome.failures.length})}: ${outcome.failures.join("; ")}`);return}hooks.notify(hooks.t("quickTask.startedRound",{count:outcome.started.length}));return}let taskId=await runQuickFork(orch,repo,result,hooks);if(taskId)setPending({taskId,prompt})}async function onRunAgain(task){let taskId=await runAgainTask(orch,task,hooks);if(taskId&&task.prompt!==void 0)setPending({taskId,prompt:task.prompt})}function initialPromptFor(taskId){return taskId&&pending?.taskId===taskId?pending.prompt:void 0}return{onQuickFork:(repo,result)=>void onQuickFork(repo,result),initialPromptFor,runAgain:(task)=>void onRunAgain(task)}}import{TextAttributes as TextAttributes14}from"@opentui/core";var import_react46=__toESM(require_react_production(),1);function promptHeader(issue){let lines=[`Work on user story #${issue.id}: ${issue.title}`,""],body=issue.body.trim();if(body)lines.push(body,"");return lines}function issueWorktreePrompt(issue,api,product){return[...promptHeader(issue),`Treat this as the story's dedicated ${product} task session: work only in this task worktree, and preserve any repo init instructions already delivered to the session.`,"Before finishing, verify the acceptance criteria implied by the story and summarize what changed plus any verification still needed.","Then merge the task branch back into the current project's main branch after the worktree is clean and checks pass.",`When the work lands, run: ${api} issue-set-status --repo . --id ${issue.id} --status done`].join(`
23
23
  `)}function issueProjectPrompt(issue,api){return[...promptHeader(issue),"You are working directly in the project checkout \u2014 no dedicated worktree or branch was created. Keep changes reviewable and do not switch branches unless asked.","Before finishing, verify the acceptance criteria implied by the story and summarize what changed plus any verification still needed.",`When the work lands, run: ${api} issue-set-status --repo . --id ${issue.id} --status done`].join(`