@sma1lboy/rove 0.9.277-next.2 → 0.9.277-next.4

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 (53) hide show
  1. package/dist/cli/{chunk-671ak750.js → chunk-0t6j1skp.js} +1 -1
  2. package/dist/cli/{chunk-n94vzkbe.js → chunk-1cyeyw6g.js} +1 -1
  3. package/dist/cli/{chunk-vwpf55cr.js → chunk-2569f2kc.js} +2 -2
  4. package/dist/cli/{chunk-j1qy79fd.js → chunk-2drde6sc.js} +1 -1
  5. package/dist/cli/{chunk-vpsarakj.js → chunk-4xr4pv54.js} +1 -1
  6. package/dist/cli/{chunk-z3qz6enf.js → chunk-6cfs0nqe.js} +1 -1
  7. package/dist/cli/{chunk-d552cvb2.js → chunk-73zg0mrb.js} +1 -1
  8. package/dist/cli/{chunk-rmsdybs3.js → chunk-7ks7rrnr.js} +2 -2
  9. package/dist/cli/{chunk-ys6v36ph.js → chunk-8j3b5m5h.js} +1 -1
  10. package/dist/cli/{chunk-fgtc1xq9.js → chunk-8jn2axtz.js} +1 -1
  11. package/dist/cli/{chunk-mxx0y791.js → chunk-9s7q3432.js} +1 -1
  12. package/dist/cli/{chunk-gbd5j3dv.js → chunk-aefvcbng.js} +1 -1
  13. package/dist/cli/{chunk-3y0z478f.js → chunk-am5cpb9n.js} +1 -1
  14. package/dist/cli/{chunk-37fas9aj.js → chunk-byh66pd6.js} +1 -1
  15. package/dist/cli/{chunk-pqr6td4z.js → chunk-cgmqnhjn.js} +1 -1
  16. package/dist/cli/{chunk-9x2xd1rz.js → chunk-ck9jdarp.js} +1 -1
  17. package/dist/cli/{chunk-tw9tfs1d.js → chunk-d6j2d6fk.js} +1 -1
  18. package/dist/cli/{chunk-0rvydb9q.js → chunk-e04pp8f5.js} +1 -1
  19. package/dist/cli/{chunk-3dhv5n19.js → chunk-exp78r1c.js} +1 -1
  20. package/dist/cli/{chunk-cf3vpsm5.js → chunk-f7egph8g.js} +1 -1
  21. package/dist/cli/{chunk-jejmt4k0.js → chunk-hdzsswee.js} +3 -3
  22. package/dist/cli/{chunk-kag7cfbr.js → chunk-hzvb6xsd.js} +1 -1
  23. package/dist/cli/{chunk-j9tsdn1d.js → chunk-j30488hn.js} +1 -1
  24. package/dist/cli/{chunk-rztqccs3.js → chunk-jgkdxj5f.js} +1 -1
  25. package/dist/cli/{chunk-748656h7.js → chunk-k2j2tjvd.js} +2 -2
  26. package/dist/cli/{chunk-ta1p2nwa.js → chunk-k9jhy3yx.js} +1 -1
  27. package/dist/cli/{chunk-zpwvjt14.js → chunk-kgpj4k4z.js} +1 -1
  28. package/dist/cli/chunk-m98jd1fz.js +3 -0
  29. package/dist/cli/{chunk-shtm72c0.js → chunk-mcxvazp4.js} +1 -1
  30. package/dist/cli/{chunk-vkv1v3xn.js → chunk-nhd4y1dw.js} +2 -2
  31. package/dist/cli/{chunk-yzdrhytj.js → chunk-np398f2a.js} +1 -1
  32. package/dist/cli/{chunk-mjyhy152.js → chunk-nqwza8b0.js} +1 -1
  33. package/dist/cli/{chunk-ca4x8s96.js → chunk-nv6dz5wy.js} +2 -2
  34. package/dist/cli/{chunk-2vph030z.js → chunk-nvcq93bp.js} +1 -1
  35. package/dist/cli/{chunk-36eyrv4r.js → chunk-p7v3w8ys.js} +1 -1
  36. package/dist/cli/{chunk-6wfhq8xd.js → chunk-qwwt4ch2.js} +1 -1
  37. package/dist/cli/{chunk-g9xknhjq.js → chunk-sh37tm44.js} +1 -1
  38. package/dist/cli/{chunk-nw092jak.js → chunk-t2p22ww7.js} +1 -1
  39. package/dist/cli/{chunk-9fdy8vne.js → chunk-t99295wq.js} +1 -1
  40. package/dist/cli/{chunk-5yh5trgy.js → chunk-v4bax7cf.js} +1 -1
  41. package/dist/cli/{chunk-wzss4pzh.js → chunk-ve76p2mx.js} +1 -1
  42. package/dist/cli/{chunk-bykqhbvy.js → chunk-vwmwmycs.js} +1 -1
  43. package/dist/cli/{chunk-zrf93zrx.js → chunk-w2tcb3rn.js} +1 -1
  44. package/dist/cli/{chunk-rjy900p4.js → chunk-wac6eaxn.js} +1 -1
  45. package/dist/cli/{chunk-5apxck3d.js → chunk-was6vqxt.js} +7 -7
  46. package/dist/cli/{chunk-z3wrbtcq.js → chunk-ym0zghjh.js} +2 -2
  47. package/dist/cli/{chunk-tnatqcy7.js → chunk-z1y9gys2.js} +1 -1
  48. package/dist/cli/index.js +2 -2
  49. package/dist/web/assets/{index-BakEtMcK.js → index-BK-95nwh.js} +29 -29
  50. package/dist/web/assets/{index-BVQbpUea.css → index-DoaQz96N.css} +1 -1
  51. package/dist/web/index.html +2 -2
  52. package/package.json +1 -1
  53. package/dist/cli/chunk-m4z6kepz.js +0 -3
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{APPEARANCE_SETTINGS,COLORBLIND_KEY,DEFAULT_BASE_REF,DEFAULT_COLORBLIND,DEFAULT_GLYPHS,DEFAULT_GLYPH_SET,DEFAULT_RUNNING_TITLE,DEFAULT_SCROLLBACK_ROWS,DEFAULT_TASK_COLORS,DEFAULT_WORKING_BORDER,EVENT_FEED_LIMIT,GLYPH_SETS,GLYPH_SET_KEY,ISSUE_CHAT_PLACEMENTS,PREFIX_TAP_PRESENTATIONS,PREFIX_TAP_PRESENTATION_KEY,RUNNING_TITLE_KEY,SCROLLBACK_ROWS_KEY,SECTIONS,SECTIONS_SIDEBAR_WIDTH,SPLIT_STYLE_KEY,TAB_STRIP_HIDE_SINGLE_KEY,TAB_STRIP_MODES,TAB_STRIP_MODE_KEY,TASK_COLORS_KEY,WORKING_BORDER_KEY,appearanceChoices,appendAttachmentRefs,applyAppearanceChoice,asAttachmentPaths,attachmentLabel,autoRoutingRows,buildDiffReview,buildPRPrompt,captureClipboardAttachment,cloneRepo,commentAtRow,commentRange,compareName,compareNewest,compareRecent,computeReviewPaint,conversationTitleOf,createBackgroundPoller,createKeybindingsFile,currentAppearanceChoice,deriveFolderName,detectWorktreeOpener,devRows,displayEndpoint,displaySettingValue,engineIntegrations,enginesNeedingHookInstall,enginesWithHooksInstalled,eventRows,findAvailableFolderName,findFileHandler,fuzzyMatch,gatherPRPromptState,generalLabelLayout,generalRows,getCurrentBranch,isBooleanOn,isNoProjectTask,issueChatTaskTitle,issueProjectPrompt,issueWorktreePrompt,keybindingRows,languageRowId,listLocalBranches,nextEnumValue,normalizeColorblind,normalizeGlyphSet,normalizeNumberInput,normalizePrefixTapPresentation,normalizeRunningTitle,normalizeScrollbackRows,normalizeSplitStyle,normalizeTaskColors,normalizeWorkingBorder,openExternally,openWorktree,persistedScrollbackRows,pluginPageErrorState,prefixTapPresentationRowId,readPluginRows,reconcileStableRows,relativeAge,relativeBuckets,repoBasename,resolveCloneTarget,resolveTabStripMode,rowAt,rowIndex,rowLiveBranchPath,sectionRows,setPluginEnabled,setPluginSetting,sidebarPrChip,sidebarProjectKeyOfTask,sidebarProjectKeyResolver,sidebarProjectLabel,sidebarRepoLabel,spawnDetached,subscribeBackgroundPolls,tabStripVisible,taskColor,toggledBooleanValue,truncateEnd,truncateEndCells,truncateStartCells,unifiedDiffRows,unsentComments,validateCloneTarget,validateGitUrl,validateRepoPath,withImagePlaceholders,worktreeRowLabel}from"./chunk-vkv1v3xn.js";import{machineOfTask,useMachineRows,useMergedTasks}from"./chunk-stng29vp.js";import{trackWelcomeWrite}from"./chunk-mxx0y791.js";import{installSkillNow,skillMissing}from"./chunk-676f3tva.js";import{fetchMarketplace}from"./chunk-grr2fn38.js";import"./chunk-c25vea1q.js";import{failureHint}from"./chunk-nw092jak.js";import{preparePluginInstall}from"./chunk-se00fc8v.js";import{formatBytes}from"./chunk-my20q579.js";import"./chunk-x89zw7br.js";import{humanOnlyFix,noEngineFix}from"./chunk-3y0z478f.js";import{embeddedTerminalEnv}from"./chunk-7bgbansg.js";import{deriveTitleFromSessionId,startTaskSessionWithPromptAdapter}from"./chunk-n94vzkbe.js";import{buildCIPromptForWorktree}from"./chunk-vkz6kkmm.js";import{canonPath,checkResolutionNotify}from"./chunk-1wwqf6kx.js";import{readLastActiveTaskId}from"./chunk-c1dz3qg3.js";import{isValidCron,nextCronAfter}from"./chunk-a4hsqj1b.js";import{tabStatus,taskStatus}from"./chunk-6hcyvg0m.js";import{installSkillErrors,skillTargets}from"./chunk-5vrg6h71.js";import{DIRECT_GUIDE_PREFIX_ACTION_ID,MarkdownText,PaneErrorBoundary,ReleaseNotesBody,RenderProfiler,armPrefixFromCurrentStack,bindByIds,bootPaneHost,currentBindingReachability,currentPaletteActions,defaultChordsOf,findBinding,formatChord,hostTargetFps,imeAnchorController,invokeArmedPrefixActionFromCurrentStack,isNarrowWidth,keymapVersion,modalActive,narrowSurface,pageCloseBindings,pluginKeybindings,redrawScreen,reloadUserKeybindings,runShellUpdater,shortcutCaption,showDialog,subscribeBindingStack,subscribeKeymapVersion,useAccessor,useBindingStackVersion,useBindings,useDialog,useDialogPaddingX,useFocus,useKV,useLatest,useNotifications,useOptionalDialog,useOptionalFocus,useOptionalKV,useOptionalNotifications,useT,useTerminalSize,useTheme,userKeybindingsReport}from"./chunk-rmsdybs3.js";import{DEFAULT_SOUND_VOLUME,FINISHED_ALERTS_KEY,FIXED_BINDING_IDS,PREFIX_GUIDE_DELAY_MS,PREFIX_HUD_TTL_MS,RAIL_FOLD_STYLE_KEY,RoveKeymap,SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,SOUND_VOLUME_KEY,ZEN_ACTIVE_KEY,ZEN_DEFAULT,attentionEdges,attentionKindFor,chipAttentionKind,currentPrefixConfiguration,isKittyModifierKeyEvent,nextSoundVolume,normalizeSoundVolume,prefixAction,prefixHudClock,prefixHudState}from"./chunk-x85rcep5.js";import{$Fragment,$jsx,$jsxs,flushSync,usePaste,useRenderer}from"./chunk-29kvfqeh.js";import{require_react_production}from"./chunk-2wd4744g.js";import{RemoteOrchestrator,absorbTab,adoptTabs,liveRowTokens}from"./chunk-v6v272b3.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-6xr1prk6.js";import"./chunk-764bsyb0.js";import{UPDATE_CHANNEL_KEY,normalizeReleaseChannel,preferredReleaseChannel,rememberReleaseChannel,tryOutChannel}from"./chunk-m4z6kepz.js";import"./chunk-xte4phd1.js";import{AUTO_ROUTING_TIERS,autoRoutingKey,classifyScreen,contentFirstLine,deriveTaskGroup,describeTierBlock,filetypeOf,isCombinedPathspec,isImagePath,listFiles,liveSourceProtocol,loadPreviewData,patchFirstLine,planChatContinuation,planWorktreeHandoff,readAutoRoutingTable,readClassifierConfig,resolveBase,searchTasks,secretStatus,statusFiles,statusFilesBranch,taskGroupRank,tierBlock,unifiedDiffFiles,worktreeFilePath,writeSecret}from"./chunk-zpwvjt14.js";import{reloadPluginEngines}from"./chunk-kdnk8m5j.js";import{listPaneLaunches}from"./chunk-rjfdzjhj.js";import{detectEngineStatus,detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-r2bb8b11.js";import{DEFAULT_EDITOR_KIND,EDITOR_CUSTOM_KEY,EDITOR_KINDS,EDITOR_KIND_KEY,normalizeEditorKind,resolveEditorLaunch}from"./chunk-agvtzads.js";import{SHELL_TASK_TITLE,deriveTitleFromPrompt}from"./chunk-2xsxcdp6.js";import"./chunk-17e2tgyg.js";import{FORK_UNSUPPORTED_CODE,PROJECT_SIBLING_BASE,TASK_DELETING_CODE,TaskDeletingError,WORKTREE_BASE_CUSTOM_KEY,dirtyRefusalReason,worktreeBaseKindOf}from"./chunk-1vxtd8rh.js";import{ISSUE_STATUSES}from"./chunk-4hestsjp.js";import"./chunk-qgrg9a5n.js";import"./chunk-2bgmby1d.js";import{loadPluginRegistry,readPluginManifest}from"./chunk-n0rdn2fn.js";import"./chunk-5mhvjytn.js";import"./chunk-atn06ncf.js";import{submitFeedback}from"./chunk-tt58819p.js";import{forwardVerb,requireMachine}from"./chunk-ta1p2nwa.js";import"./chunk-vytrhm50.js";import"./chunk-vp29jgbt.js";import{PROJECT_DIR_TOKEN,WORKTREE_BASE_KEY,hasProjectDirToken,normalizeWorktreeBase}from"./chunk-gq36nzg8.js";import"./chunk-sq6zj3fb.js";import{ulid}from"./chunk-qkehg2c1.js";import{approxCellWidth,approxCharCells,charWidth,displayWidth,padEndCells}from"./chunk-dvcb6mk4.js";import{hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp}from"./chunk-j1qy79fd.js";import{ensurePtyHostReachable}from"./chunk-z43e08kw.js";import"./chunk-w77s2df8.js";import{DEFAULT_TERMINAL_COLORS,formatDefaultColorReply,parseTerminalDefaultColors}from"./chunk-mqfvzdpr.js";import{LOCALE_KEY,breathColor,breathGlyph,diffInks,mixInk,turnHue}from"./chunk-cf3vpsm5.js";import"./chunk-rxqdw6s5.js";import"./chunk-kxp04jnp.js";import{addTab,closeActiveTab,closeTab,collapseSplit,conversationTitle,cycleLeaf,cycleTab,engineTabSpawnFor,expandHome,filterSubdirs,findEditorTab,gotoTab,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,tabCwdFor,tabExitAction,tabPtyKey,tabPtyKeyFor,tabTitle,tabTitleStable,visibleNativeStatus}from"./chunk-tw9tfs1d.js";import{AUTO_STATUS_KEY,DISPATCHER_KEY,repoEnv}from"./chunk-61cn88e7.js";import{ENGINE_PROTOCOLS,applyTabOps,defaultEngineCommand,diffTabs,engineCommandKey,engineDisplayName,engineLaunchArgv,engineNameKey,engineProtocolKey,engineRenamedFrom,humanizeSlug,interactiveEngineCommand,pickUnclaimedSessionId,protocolEntry,roveApiInvocation,withPinnedSessionId}from"./chunk-atg13xab.js";import"./chunk-r5j8fycq.js";import{isBuiltinModInstalled,setBuiltinModInstalled}from"./chunk-xfgqae9t.js";import{builtinModsPath}from"./chunk-j1z9kgyd.js";import{aliasedKeys,isUnderKey,teardownScope}from"./chunk-g9ba25q5.js";import"./chunk-ggnq2vvk.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import{terminalTabsKey}from"./chunk-mdc7b01e.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{execHostForWorktreePath,remoteKeyForRepo}from"./chunk-895yqjjz.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import{connectOrStartDaemon}from"./chunk-e58kj4gm.js";import"./chunk-0a65j1zj.js";import"./chunk-bcyex84w.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-vvqwgcge.js";import{createEngineHookAdapter,engineEntry,engineSessionIdFromTitle,engineTitleTurnHint,getCapabilities,stripEngineStatusPrefix}from"./chunk-x83xbzjd.js";import{spawnCapture}from"./chunk-2tfnscxk.js";import{availableEngineIds,installedEngineIds}from"./chunk-hzz020xx.js";import"./chunk-w7zv47mp.js";import"./chunk-etfh8f4z.js";import{getGlobalDefaultVendor,resolvePreferredVendor,setGlobalDefaultVendor,setRepoLastActiveVendor}from"./chunk-9rj2fx6v.js";import{addSavedRepo,getSavedRepos,isGitRepo,isRemoteRepoKey,resolveMainRepoRoot}from"./chunk-rfp0ayra.js";import{parsePorcelain,sameWorktreeChanges}from"./chunk-0r1jf8m9.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import{recordSpawn}from"./chunk-40dgv828.js";import"./chunk-kg9kmwt9.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{processCwd}from"./chunk-3n0y9vpj.js";import{matchPathGlob}from"./chunk-kg11c1py.js";import{CURRENT_VERSION,channelOf,checkLatestVersion,fetchReleaseNotesRange,releasePageUrl,updateCommandFor}from"./chunk-9ckvdy0j.js";import"./chunk-zsfyj36g.js";import{tildify}from"./chunk-2r1fgng9.js";import{errorMessage,userFacingErrorMessage}from"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import{currentLang,intlLocale,registerMessages,setLocaleLang,t,tKeys}from"./chunk-mjyhy152.js";import{LOCALES}from"./chunk-wzss4pzh.js";import{createStateCell,profileSpan,profileTick}from"./chunk-cmp64q4j.js";import{CHANNEL_NAMES,RoveDaemonClient,attentionInboxItemKey,automationRunNeedsAttention,isRoutineInboxState,routineRunResponseState}from"./chunk-qzzmd63x.js";import"./chunk-96kvwzj8.js";import"./chunk-7bakcyes.js";import{roveCliInvocation}from"./chunk-8qkyd589.js";import"./chunk-7kysxgbq.js";import"./chunk-hz1x3hak.js";import{MULTI_REPO_CAP,childrenOf,isSharedChild,rollupPr,taskCwd,taskRepos,workspaceCapabilities}from"./chunk-x1jxxmtc.js";import{DEFAULT_TASK_VENDOR,TASK_STATUSES}from"./chunk-xy8be792.js";import{ALL_VENDORS,isBuiltinVendor,nextVendorWithin,prevVendorWithin}from"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import{isDev,roveStateDir}from"./chunk-z1nj22va.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{logClientError}from"./chunk-0g4wc808.js";import{pathIdentity,pathSyntax,pathWithin,samePath}from"./chunk-pn5ygqn6.js";import{defaultDaemonSocketPath}from"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import{readRoveEnv}from"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import{__commonJS,__require,__toESM}from"./chunk-91sykzqq.js";var require_xterm_headless=__commonJS((exports)=>{(()=>{var e2={5639:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.CircularList=void 0;let i3=s3(7150),r7=s3(802);class n3 extends i3.Disposable{constructor(e4){super(),this._maxLength=e4,this.onDeleteEmitter=this._register(new r7.Emitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new r7.Emitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new r7.Emitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e4){if(this._maxLength===e4)return;let t5=Array(e4);for(let s4=0;s4<Math.min(e4,this.length);s4++)t5[s4]=this._array[this._getCyclicIndex(s4)];this._array=t5,this._maxLength=e4,this._startIndex=0}get length(){return this._length}set length(e4){if(e4>this._length)for(let t5=this._length;t5<e4;t5++)this._array[t5]=void 0;this._length=e4}get(e4){return this._array[this._getCyclicIndex(e4)]}set(e4,t5){this._array[this._getCyclicIndex(e4)]=t5}push(e4){this._array[this._getCyclicIndex(this._length)]=e4,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e4,t5,...s4){if(t5){for(let s5=e4;s5<this._length-t5;s5++)this._array[this._getCyclicIndex(s5)]=this._array[this._getCyclicIndex(s5+t5)];this._length-=t5,this.onDeleteEmitter.fire({index:e4,amount:t5})}for(let t6=this._length-1;t6>=e4;t6--)this._array[this._getCyclicIndex(t6+s4.length)]=this._array[this._getCyclicIndex(t6)];for(let t6=0;t6<s4.length;t6++)this._array[this._getCyclicIndex(e4+t6)]=s4[t6];if(s4.length&&this.onInsertEmitter.fire({index:e4,amount:s4.length}),this._length+s4.length>this._maxLength){let e5=this._length+s4.length-this._maxLength;this._startIndex+=e5,this._length=this._maxLength,this.onTrimEmitter.fire(e5)}else this._length+=s4.length}trimStart(e4){e4>this._length&&(e4=this._length),this._startIndex+=e4,this._length-=e4,this.onTrimEmitter.fire(e4)}shiftElements(e4,t5,s4){if(!(t5<=0)){if(e4<0||e4>=this._length)throw Error("start argument out of range");if(e4+s4<0)throw Error("Cannot shift elements in list beyond index 0");if(s4>0){for(let i5=t5-1;i5>=0;i5--)this.set(e4+i5+s4,this.get(e4+i5));let i4=e4+t5+s4-this._length;if(i4>0)for(this._length+=i4;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let i4=0;i4<t5;i4++)this.set(e4+i4+s4,this.get(e4+i4))}}_getCyclicIndex(e4){return(this._startIndex+e4)%this._maxLength}}t4.CircularList=n3},7453:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.clone=function e4(t5,s3=5){if(typeof t5!="object")return t5;let i3=Array.isArray(t5)?[]:{};for(let r7 in t5)i3[r7]=s3<=1?t5[r7]:t5[r7]&&e4(t5[r7],s3-1);return i3}},5777:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.CoreTerminal=void 0;let i3=s3(6501),r7=s3(6025),n3=s3(7276),o2=s3(9640),a2=s3(56),h2=s3(4071),c2=s3(7792),l2=s3(6415),u2=s3(5746),d2=s3(5882),f2=s3(2486),_4=s3(3562),p3=s3(8811),g3=s3(802),v3=s3(7150),m3=!1;class b3 extends v3.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new g3.Emitter),this._onScroll.event((e4)=>{this._onScrollApi?.fire(e4.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e4){for(let t5 in e4)this.optionsService.options[t5]=e4[t5]}constructor(e4){super(),this._windowsWrappingHeuristics=this._register(new v3.MutableDisposable),this._onBinary=this._register(new g3.Emitter),this.onBinary=this._onBinary.event,this._onData=this._register(new g3.Emitter),this.onData=this._onData.event,this._onLineFeed=this._register(new g3.Emitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new g3.Emitter),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new g3.Emitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new g3.Emitter),this._instantiationService=new r7.InstantiationService,this.optionsService=this._register(new a2.OptionsService(e4)),this._instantiationService.setService(i3.IOptionsService,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(o2.BufferService)),this._instantiationService.setService(i3.IBufferService,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(n3.LogService)),this._instantiationService.setService(i3.ILogService,this._logService),this.coreService=this._register(this._instantiationService.createInstance(h2.CoreService)),this._instantiationService.setService(i3.ICoreService,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(c2.CoreMouseService)),this._instantiationService.setService(i3.ICoreMouseService,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(l2.UnicodeService)),this._instantiationService.setService(i3.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(u2.CharsetService),this._instantiationService.setService(i3.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(p3.OscLinkService),this._instantiationService.setService(i3.IOscLinkService,this._oscLinkService),this._inputHandler=this._register(new f2.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(g3.Event.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(g3.Event.forward(this._bufferService.onResize,this._onResize)),this._register(g3.Event.forward(this.coreService.onData,this._onData)),this._register(g3.Event.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new _4.WriteBuffer((e5,t5)=>this._inputHandler.parse(e5,t5))),this._register(g3.Event.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(e4,t5){this._writeBuffer.write(e4,t5)}writeSync(e4,t5){this._logService.logLevel<=i3.LogLevelEnum.WARN&&!m3&&(this._logService.warn("writeSync is unreliable and will be removed soon."),m3=!0),this._writeBuffer.writeSync(e4,t5)}input(e4,t5=!0){this.coreService.triggerDataEvent(e4,t5)}resize(e4,t5){isNaN(e4)||isNaN(t5)||(e4=Math.max(e4,o2.MINIMUM_COLS),t5=Math.max(t5,o2.MINIMUM_ROWS),this._bufferService.resize(e4,t5))}scroll(e4,t5=!1){this._bufferService.scroll(e4,t5)}scrollLines(e4,t5){this._bufferService.scrollLines(e4,t5)}scrollPages(e4){this.scrollLines(e4*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e4){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e4){let t5=e4-this._bufferService.buffer.ydisp;t5!==0&&this.scrollLines(t5)}registerEscHandler(e4,t5){return this._inputHandler.registerEscHandler(e4,t5)}registerDcsHandler(e4,t5){return this._inputHandler.registerDcsHandler(e4,t5)}registerCsiHandler(e4,t5){return this._inputHandler.registerCsiHandler(e4,t5)}registerOscHandler(e4,t5){return this._inputHandler.registerOscHandler(e4,t5)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e4=!1,t5=this.optionsService.rawOptions.windowsPty;t5&&t5.buildNumber!==void 0&&t5.buildNumber!==void 0?e4=t5.backend==="conpty"&&t5.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e4=!0),e4?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e4=[];e4.push(this.onLineFeed(d2.updateWindowsModeWrappedState.bind(null,this._bufferService))),e4.push(this.registerCsiHandler({final:"H"},()=>((0,d2.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,v3.toDisposable)(()=>{for(let t5 of e4)t5.dispose()})}}}t4.CoreTerminal=b3},2486:function(e3,t4,s3){var i3=this&&this.__decorate||function(e4,t5,s4,i4){var r8,n4=arguments.length,o3=n4<3?t5:i4===null?i4=Object.getOwnPropertyDescriptor(t5,s4):i4;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o3=Reflect.decorate(e4,t5,s4,i4);else for(var a3=e4.length-1;a3>=0;a3--)(r8=e4[a3])&&(o3=(n4<3?r8(o3):n4>3?r8(t5,s4,o3):r8(t5,s4))||o3);return n4>3&&o3&&Object.defineProperty(t5,s4,o3),o3},r7=this&&this.__param||function(e4,t5){return function(s4,i4){t5(s4,i4,e4)}};Object.defineProperty(t4,"__esModule",{value:!0}),t4.InputHandler=t4.WindowsOptionsReportType=void 0,t4.isValidColorIndex=k3;let n3=s3(3534),o2=s3(6760),a2=s3(6717),h2=s3(7150),c2=s3(726),l2=s3(6107),u2=s3(8938),d2=s3(3055),f2=s3(5451),_4=s3(6501),p3=s3(6415),g3=s3(1346),v3=s3(9823),m3=s3(8693),b3=s3(802),S3={"(":0,")":1,"*":2,"+":3,"-":1,".":2},y3=131072;function C3(e4,t5){if(e4>24)return t5.setWinLines||!1;switch(e4){case 1:return!!t5.restoreWin;case 2:return!!t5.minimizeWin;case 3:return!!t5.setWinPosition;case 4:return!!t5.setWinSizePixels;case 5:return!!t5.raiseWin;case 6:return!!t5.lowerWin;case 7:return!!t5.refreshWin;case 8:return!!t5.setWinSizeChars;case 9:return!!t5.maximizeWin;case 10:return!!t5.fullscreenWin;case 11:return!!t5.getWinState;case 13:return!!t5.getWinPosition;case 14:return!!t5.getWinSizePixels;case 15:return!!t5.getScreenSizePixels;case 16:return!!t5.getCellSizePixels;case 18:return!!t5.getWinSizeChars;case 19:return!!t5.getScreenSizeChars;case 20:return!!t5.getIconTitle;case 21:return!!t5.getWinTitle;case 22:return!!t5.pushTitle;case 23:return!!t5.popTitle;case 24:return!!t5.setWinLines}return!1}var w4;(function(e4){e4[e4.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",e4[e4.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(w4||(t4.WindowsOptionsReportType=w4={}));let E3=0;class A4 extends h2.Disposable{getAttrData(){return this._curAttrData}constructor(e4,t5,s4,i4,r8,h3,u3,d3,f3=new a2.EscapeSequenceParser){super(),this._bufferService=e4,this._charsetService=t5,this._coreService=s4,this._logService=i4,this._optionsService=r8,this._oscLinkService=h3,this._coreMouseService=u3,this._unicodeService=d3,this._parser=f3,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new c2.StringToUtf32,this._utf8Decoder=new c2.Utf8ToUtf32,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=l2.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=l2.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this._register(new b3.Emitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new b3.Emitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new b3.Emitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new b3.Emitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new b3.Emitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new b3.Emitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new b3.Emitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new b3.Emitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new b3.Emitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new b3.Emitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new b3.Emitter),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new b3.Emitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new b3.Emitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new L2(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate((e5)=>this._activeBuffer=e5.activeBuffer)),this._parser.setCsiHandlerFallback((e5,t6)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(e5),params:t6.toArray()})}),this._parser.setEscHandlerFallback((e5)=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(e5)})}),this._parser.setExecuteHandlerFallback((e5)=>{this._logService.debug("Unknown EXECUTE code: ",{code:e5})}),this._parser.setOscHandlerFallback((e5,t6,s5)=>{this._logService.debug("Unknown OSC code: ",{identifier:e5,action:t6,data:s5})}),this._parser.setDcsHandlerFallback((e5,t6,s5)=>{t6==="HOOK"&&(s5=s5.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(e5),action:t6,payload:s5})}),this._parser.setPrintHandler((e5,t6,s5)=>this.print(e5,t6,s5)),this._parser.registerCsiHandler({final:"@"},(e5)=>this.insertChars(e5)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(e5)=>this.scrollLeft(e5)),this._parser.registerCsiHandler({final:"A"},(e5)=>this.cursorUp(e5)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(e5)=>this.scrollRight(e5)),this._parser.registerCsiHandler({final:"B"},(e5)=>this.cursorDown(e5)),this._parser.registerCsiHandler({final:"C"},(e5)=>this.cursorForward(e5)),this._parser.registerCsiHandler({final:"D"},(e5)=>this.cursorBackward(e5)),this._parser.registerCsiHandler({final:"E"},(e5)=>this.cursorNextLine(e5)),this._parser.registerCsiHandler({final:"F"},(e5)=>this.cursorPrecedingLine(e5)),this._parser.registerCsiHandler({final:"G"},(e5)=>this.cursorCharAbsolute(e5)),this._parser.registerCsiHandler({final:"H"},(e5)=>this.cursorPosition(e5)),this._parser.registerCsiHandler({final:"I"},(e5)=>this.cursorForwardTab(e5)),this._parser.registerCsiHandler({final:"J"},(e5)=>this.eraseInDisplay(e5,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},(e5)=>this.eraseInDisplay(e5,!0)),this._parser.registerCsiHandler({final:"K"},(e5)=>this.eraseInLine(e5,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},(e5)=>this.eraseInLine(e5,!0)),this._parser.registerCsiHandler({final:"L"},(e5)=>this.insertLines(e5)),this._parser.registerCsiHandler({final:"M"},(e5)=>this.deleteLines(e5)),this._parser.registerCsiHandler({final:"P"},(e5)=>this.deleteChars(e5)),this._parser.registerCsiHandler({final:"S"},(e5)=>this.scrollUp(e5)),this._parser.registerCsiHandler({final:"T"},(e5)=>this.scrollDown(e5)),this._parser.registerCsiHandler({final:"X"},(e5)=>this.eraseChars(e5)),this._parser.registerCsiHandler({final:"Z"},(e5)=>this.cursorBackwardTab(e5)),this._parser.registerCsiHandler({final:"`"},(e5)=>this.charPosAbsolute(e5)),this._parser.registerCsiHandler({final:"a"},(e5)=>this.hPositionRelative(e5)),this._parser.registerCsiHandler({final:"b"},(e5)=>this.repeatPrecedingCharacter(e5)),this._parser.registerCsiHandler({final:"c"},(e5)=>this.sendDeviceAttributesPrimary(e5)),this._parser.registerCsiHandler({prefix:">",final:"c"},(e5)=>this.sendDeviceAttributesSecondary(e5)),this._parser.registerCsiHandler({final:"d"},(e5)=>this.linePosAbsolute(e5)),this._parser.registerCsiHandler({final:"e"},(e5)=>this.vPositionRelative(e5)),this._parser.registerCsiHandler({final:"f"},(e5)=>this.hVPosition(e5)),this._parser.registerCsiHandler({final:"g"},(e5)=>this.tabClear(e5)),this._parser.registerCsiHandler({final:"h"},(e5)=>this.setMode(e5)),this._parser.registerCsiHandler({prefix:"?",final:"h"},(e5)=>this.setModePrivate(e5)),this._parser.registerCsiHandler({final:"l"},(e5)=>this.resetMode(e5)),this._parser.registerCsiHandler({prefix:"?",final:"l"},(e5)=>this.resetModePrivate(e5)),this._parser.registerCsiHandler({final:"m"},(e5)=>this.charAttributes(e5)),this._parser.registerCsiHandler({final:"n"},(e5)=>this.deviceStatus(e5)),this._parser.registerCsiHandler({prefix:"?",final:"n"},(e5)=>this.deviceStatusPrivate(e5)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(e5)=>this.softReset(e5)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(e5)=>this.setCursorStyle(e5)),this._parser.registerCsiHandler({final:"r"},(e5)=>this.setScrollRegion(e5)),this._parser.registerCsiHandler({final:"s"},(e5)=>this.saveCursor(e5)),this._parser.registerCsiHandler({final:"t"},(e5)=>this.windowOptions(e5)),this._parser.registerCsiHandler({final:"u"},(e5)=>this.restoreCursor(e5)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(e5)=>this.insertColumns(e5)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(e5)=>this.deleteColumns(e5)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(e5)=>this.selectProtected(e5)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(e5)=>this.requestMode(e5,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(e5)=>this.requestMode(e5,!1)),this._parser.setExecuteHandler(n3.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(n3.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(n3.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(n3.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(n3.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(n3.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(n3.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(n3.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(n3.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(n3.C1.IND,()=>this.index()),this._parser.setExecuteHandler(n3.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(n3.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new g3.OscHandler((e5)=>(this.setTitle(e5),this.setIconName(e5),!0))),this._parser.registerOscHandler(1,new g3.OscHandler((e5)=>this.setIconName(e5))),this._parser.registerOscHandler(2,new g3.OscHandler((e5)=>this.setTitle(e5))),this._parser.registerOscHandler(4,new g3.OscHandler((e5)=>this.setOrReportIndexedColor(e5))),this._parser.registerOscHandler(8,new g3.OscHandler((e5)=>this.setHyperlink(e5))),this._parser.registerOscHandler(10,new g3.OscHandler((e5)=>this.setOrReportFgColor(e5))),this._parser.registerOscHandler(11,new g3.OscHandler((e5)=>this.setOrReportBgColor(e5))),this._parser.registerOscHandler(12,new g3.OscHandler((e5)=>this.setOrReportCursorColor(e5))),this._parser.registerOscHandler(104,new g3.OscHandler((e5)=>this.restoreIndexedColor(e5))),this._parser.registerOscHandler(110,new g3.OscHandler((e5)=>this.restoreFgColor(e5))),this._parser.registerOscHandler(111,new g3.OscHandler((e5)=>this.restoreBgColor(e5))),this._parser.registerOscHandler(112,new g3.OscHandler((e5)=>this.restoreCursorColor(e5))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let e5 in o2.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:e5},()=>this.selectCharset("("+e5)),this._parser.registerEscHandler({intermediates:")",final:e5},()=>this.selectCharset(")"+e5)),this._parser.registerEscHandler({intermediates:"*",final:e5},()=>this.selectCharset("*"+e5)),this._parser.registerEscHandler({intermediates:"+",final:e5},()=>this.selectCharset("+"+e5)),this._parser.registerEscHandler({intermediates:"-",final:e5},()=>this.selectCharset("-"+e5)),this._parser.registerEscHandler({intermediates:".",final:e5},()=>this.selectCharset("."+e5)),this._parser.registerEscHandler({intermediates:"/",final:e5},()=>this.selectCharset("/"+e5));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler((e5)=>(this._logService.error("Parsing error: ",e5),e5)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new v3.DcsHandler((e5,t6)=>this.requestStatusString(e5,t6)))}_preserveStack(e4,t5,s4,i4){this._parseStack.paused=!0,this._parseStack.cursorStartX=e4,this._parseStack.cursorStartY=t5,this._parseStack.decodedLength=s4,this._parseStack.position=i4}_logSlowResolvingAsync(e4){this._logService.logLevel<=_4.LogLevelEnum.WARN&&Promise.race([e4,new Promise((e5,t5)=>setTimeout(()=>t5("#SLOW_TIMEOUT"),5000))]).catch((e5)=>{if(e5!=="#SLOW_TIMEOUT")throw e5;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e4,t5){let s4,i4=this._activeBuffer.x,r8=this._activeBuffer.y,n4=0,o3=this._parseStack.paused;if(o3){if(s4=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t5))return this._logSlowResolvingAsync(s4),s4;i4=this._parseStack.cursorStartX,r8=this._parseStack.cursorStartY,this._parseStack.paused=!1,e4.length>y3&&(n4=this._parseStack.position+y3)}if(this._logService.logLevel<=_4.LogLevelEnum.DEBUG&&this._logService.debug("parsing data "+(typeof e4=="string"?` "${e4}"`:` "${Array.prototype.map.call(e4,(e5)=>String.fromCharCode(e5)).join("")}"`)),this._logService.logLevel===_4.LogLevelEnum.TRACE&&this._logService.trace("parsing data (codes)",typeof e4=="string"?e4.split("").map((e5)=>e5.charCodeAt(0)):e4),this._parseBuffer.length<e4.length&&this._parseBuffer.length<y3&&(this._parseBuffer=new Uint32Array(Math.min(e4.length,y3))),o3||this._dirtyRowTracker.clearRange(),e4.length>y3)for(let t6=n4;t6<e4.length;t6+=y3){let n5=t6+y3<e4.length?t6+y3:e4.length,o4=typeof e4=="string"?this._stringDecoder.decode(e4.substring(t6,n5),this._parseBuffer):this._utf8Decoder.decode(e4.subarray(t6,n5),this._parseBuffer);if(s4=this._parser.parse(this._parseBuffer,o4))return this._preserveStack(i4,r8,o4,t6),this._logSlowResolvingAsync(s4),s4}else if(!o3){let t6=typeof e4=="string"?this._stringDecoder.decode(e4,this._parseBuffer):this._utf8Decoder.decode(e4,this._parseBuffer);if(s4=this._parser.parse(this._parseBuffer,t6))return this._preserveStack(i4,r8,t6,0),this._logSlowResolvingAsync(s4),s4}this._activeBuffer.x===i4&&this._activeBuffer.y===r8||this._onCursorMove.fire();let a3=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),h3=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);h3<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(h3,this._bufferService.rows-1),end:Math.min(a3,this._bufferService.rows-1)})}print(e4,t5,s4){let i4,r8,n4=this._charsetService.charset,o3=this._optionsService.rawOptions.screenReaderMode,a3=this._bufferService.cols,h3=this._coreService.decPrivateModes.wraparound,d3=this._coreService.modes.insertMode,f3=this._curAttrData,_5=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&s4-t5>0&&_5.getWidth(this._activeBuffer.x-1)===2&&_5.setCellFromCodepoint(this._activeBuffer.x-1,0,1,f3);let g4=this._parser.precedingJoinState;for(let v4=t5;v4<s4;++v4){if(i4=e4[v4],i4<127&&n4){let e5=n4[String.fromCharCode(i4)];e5&&(i4=e5.charCodeAt(0))}let t6=this._unicodeService.charProperties(i4,g4);r8=p3.UnicodeService.extractWidth(t6);let s5=p3.UnicodeService.extractShouldJoin(t6),m4=s5?p3.UnicodeService.extractWidth(g4):0;if(g4=t6,o3&&this._onA11yChar.fire((0,c2.stringFromCodePoint)(i4)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+r8-m4>a3){if(h3){let e5=_5,t7=this._activeBuffer.x-m4;for(this._activeBuffer.x=m4,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),_5=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m4>0&&_5 instanceof l2.BufferLine&&_5.copyCellsFrom(e5,t7,0,m4,!1);t7<a3;)e5.setCellFromCodepoint(t7++,0,1,f3)}else if(this._activeBuffer.x=a3-1,r8===2)continue}if(s5&&this._activeBuffer.x){let e5=_5.getWidth(this._activeBuffer.x-1)?1:2;_5.addCodepointToCell(this._activeBuffer.x-e5,i4,r8);for(let e6=r8-m4;--e6>=0;)_5.setCellFromCodepoint(this._activeBuffer.x++,0,0,f3)}else if(d3&&(_5.insertCells(this._activeBuffer.x,r8-m4,this._activeBuffer.getNullCell(f3)),_5.getWidth(a3-1)===2&&_5.setCellFromCodepoint(a3-1,u2.NULL_CELL_CODE,u2.NULL_CELL_WIDTH,f3)),_5.setCellFromCodepoint(this._activeBuffer.x++,i4,r8,f3),r8>0)for(;--r8;)_5.setCellFromCodepoint(this._activeBuffer.x++,0,0,f3)}this._parser.precedingJoinState=g4,this._activeBuffer.x<a3&&s4-t5>0&&_5.getWidth(this._activeBuffer.x)===0&&!_5.hasContent(this._activeBuffer.x)&&_5.setCellFromCodepoint(this._activeBuffer.x,0,1,f3),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e4,t5){return e4.final!=="t"||e4.prefix||e4.intermediates?this._parser.registerCsiHandler(e4,t5):this._parser.registerCsiHandler(e4,(e5)=>!C3(e5.params[0],this._optionsService.rawOptions.windowOptions)||t5(e5))}registerDcsHandler(e4,t5){return this._parser.registerDcsHandler(e4,new v3.DcsHandler(t5))}registerEscHandler(e4,t5){return this._parser.registerEscHandler(e4,t5)}registerOscHandler(e4,t5){return this._parser.registerOscHandler(e4,new g3.OscHandler(t5))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e4=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e4.hasWidth(this._activeBuffer.x)&&!e4.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e4=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e4),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e4=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e4,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e4,t5){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e4,this._activeBuffer.y=this._activeBuffer.scrollTop+t5):(this._activeBuffer.x=e4,this._activeBuffer.y=t5),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e4,t5){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e4,this._activeBuffer.y+t5)}cursorUp(e4){let t5=this._activeBuffer.y-this._activeBuffer.scrollTop;return t5>=0?this._moveCursor(0,-Math.min(t5,e4.params[0]||1)):this._moveCursor(0,-(e4.params[0]||1)),!0}cursorDown(e4){let t5=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t5>=0?this._moveCursor(0,Math.min(t5,e4.params[0]||1)):this._moveCursor(0,e4.params[0]||1),!0}cursorForward(e4){return this._moveCursor(e4.params[0]||1,0),!0}cursorBackward(e4){return this._moveCursor(-(e4.params[0]||1),0),!0}cursorNextLine(e4){return this.cursorDown(e4),this._activeBuffer.x=0,!0}cursorPrecedingLine(e4){return this.cursorUp(e4),this._activeBuffer.x=0,!0}cursorCharAbsolute(e4){return this._setCursor((e4.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e4){return this._setCursor(e4.length>=2?(e4.params[1]||1)-1:0,(e4.params[0]||1)-1),!0}charPosAbsolute(e4){return this._setCursor((e4.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e4){return this._moveCursor(e4.params[0]||1,0),!0}linePosAbsolute(e4){return this._setCursor(this._activeBuffer.x,(e4.params[0]||1)-1),!0}vPositionRelative(e4){return this._moveCursor(0,e4.params[0]||1),!0}hVPosition(e4){return this.cursorPosition(e4),!0}tabClear(e4){let t5=e4.params[0];return t5===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t5===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e4){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t5=e4.params[0]||1;for(;t5--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e4){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t5=e4.params[0]||1;for(;t5--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e4){let t5=e4.params[0];return t5===1&&(this._curAttrData.bg|=536870912),t5!==2&&t5!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e4,t5,s4,i4=!1,r8=!1){let n4=this._activeBuffer.lines.get(this._activeBuffer.ybase+e4);n4.replaceCells(t5,s4,this._activeBuffer.getNullCell(this._eraseAttrData()),r8),i4&&(n4.isWrapped=!1)}_resetBufferLine(e4,t5=!1){let s4=this._activeBuffer.lines.get(this._activeBuffer.ybase+e4);s4&&(s4.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t5),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e4),s4.isWrapped=!1)}eraseInDisplay(e4,t5=!1){let s4;switch(this._restrictCursor(this._bufferService.cols),e4.params[0]){case 0:for(s4=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s4),this._eraseInBufferLine(s4++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t5);s4<this._bufferService.rows;s4++)this._resetBufferLine(s4,t5);this._dirtyRowTracker.markDirty(s4);break;case 1:for(s4=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s4),this._eraseInBufferLine(s4,0,this._activeBuffer.x+1,!0,t5),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(s4+1).isWrapped=!1);s4--;)this._resetBufferLine(s4,t5);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(s4=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,s4-1);s4--;)if(this._activeBuffer.lines.get(this._activeBuffer.ybase+s4)?.getTrimmedLength())break;for(;s4>=0;s4--)this._bufferService.scroll(this._eraseAttrData())}else{for(s4=this._bufferService.rows,this._dirtyRowTracker.markDirty(s4-1);s4--;)this._resetBufferLine(s4,t5);this._dirtyRowTracker.markDirty(0)}break;case 3:let e5=this._activeBuffer.lines.length-this._bufferService.rows;e5>0&&(this._activeBuffer.lines.trimStart(e5),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e5,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e5,0),this._onScroll.fire(0))}return!0}eraseInLine(e4,t5=!1){switch(this._restrictCursor(this._bufferService.cols),e4.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t5);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t5);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t5)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e4){this._restrictCursor();let t5=e4.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let s4=this._activeBuffer.ybase+this._activeBuffer.y,i4=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r8=this._bufferService.rows-1+this._activeBuffer.ybase-i4+1;for(;t5--;)this._activeBuffer.lines.splice(r8-1,1),this._activeBuffer.lines.splice(s4,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e4){this._restrictCursor();let t5=e4.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let s4=this._activeBuffer.ybase+this._activeBuffer.y,i4;for(i4=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i4=this._bufferService.rows-1+this._activeBuffer.ybase-i4;t5--;)this._activeBuffer.lines.splice(s4,1),this._activeBuffer.lines.splice(i4,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e4){this._restrictCursor();let t5=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t5&&(t5.insertCells(this._activeBuffer.x,e4.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e4){this._restrictCursor();let t5=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t5&&(t5.deleteCells(this._activeBuffer.x,e4.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e4){let t5=e4.params[0]||1;for(;t5--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e4){let t5=e4.params[0]||1;for(;t5--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(l2.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e4){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t5=e4.params[0]||1;for(let e5=this._activeBuffer.scrollTop;e5<=this._activeBuffer.scrollBottom;++e5){let s4=this._activeBuffer.lines.get(this._activeBuffer.ybase+e5);s4.deleteCells(0,t5,this._activeBuffer.getNullCell(this._eraseAttrData())),s4.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e4){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t5=e4.params[0]||1;for(let e5=this._activeBuffer.scrollTop;e5<=this._activeBuffer.scrollBottom;++e5){let s4=this._activeBuffer.lines.get(this._activeBuffer.ybase+e5);s4.insertCells(0,t5,this._activeBuffer.getNullCell(this._eraseAttrData())),s4.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e4){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t5=e4.params[0]||1;for(let e5=this._activeBuffer.scrollTop;e5<=this._activeBuffer.scrollBottom;++e5){let s4=this._activeBuffer.lines.get(this._activeBuffer.ybase+e5);s4.insertCells(this._activeBuffer.x,t5,this._activeBuffer.getNullCell(this._eraseAttrData())),s4.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e4){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t5=e4.params[0]||1;for(let e5=this._activeBuffer.scrollTop;e5<=this._activeBuffer.scrollBottom;++e5){let s4=this._activeBuffer.lines.get(this._activeBuffer.ybase+e5);s4.deleteCells(this._activeBuffer.x,t5,this._activeBuffer.getNullCell(this._eraseAttrData())),s4.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e4){this._restrictCursor();let t5=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t5&&(t5.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e4.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e4){let t5=this._parser.precedingJoinState;if(!t5)return!0;let s4=e4.params[0]||1,i4=p3.UnicodeService.extractWidth(t5),r8=this._activeBuffer.x-i4,n4=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(r8),o3=new Uint32Array(n4.length*s4),a3=0;for(let e5=0;e5<n4.length;){let t6=n4.codePointAt(e5)||0;o3[a3++]=t6,e5+=t6>65535?2:1}let h3=a3;for(let e5=1;e5<s4;++e5)o3.copyWithin(h3,0,a3),h3+=a3;return this.print(o3,0,h3),!0}sendDeviceAttributesPrimary(e4){return e4.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(n3.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(n3.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e4){return e4.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(n3.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(n3.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e4.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(n3.C0.ESC+"[>83;40003;0c")),!0}_is(e4){return(this._optionsService.rawOptions.termName+"").indexOf(e4)===0}setMode(e4){for(let t5=0;t5<e4.length;t5++)switch(e4.params[t5]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e4){for(let t5=0;t5<e4.length;t5++)switch(e4.params[t5]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,o2.DEFAULT_CHARSET),this._charsetService.setgCharset(1,o2.DEFAULT_CHARSET),this._charsetService.setgCharset(2,o2.DEFAULT_CHARSET),this._charsetService.setgCharset(3,o2.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1000:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e4){for(let t5=0;t5<e4.length;t5++)switch(e4.params[t5]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e4){for(let t5=0;t5<e4.length;t5++)switch(e4.params[t5]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1000:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e4.params[t5]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e4,t5){let s4=this._coreService.decPrivateModes,{activeProtocol:i4,activeEncoding:r8}=this._coreMouseService,o3=this._coreService,{buffers:a3,cols:h3}=this._bufferService,{active:c3,alt:l3}=a3,u3=this._optionsService.rawOptions,d3=(e5)=>e5?1:2,f3=e4.params[0];return _5=f3,p4=t5?f3===2?4:f3===4?d3(o3.modes.insertMode):f3===12?3:f3===20?d3(u3.convertEol):0:f3===1?d3(s4.applicationCursorKeys):f3===3?u3.windowOptions.setWinLines?h3===80?2:h3===132?1:0:0:f3===6?d3(s4.origin):f3===7?d3(s4.wraparound):f3===8?3:f3===9?d3(i4==="X10"):f3===12?d3(u3.cursorBlink):f3===25?d3(!o3.isCursorHidden):f3===45?d3(s4.reverseWraparound):f3===66?d3(s4.applicationKeypad):f3===67?4:f3===1000?d3(i4==="VT200"):f3===1002?d3(i4==="DRAG"):f3===1003?d3(i4==="ANY"):f3===1004?d3(s4.sendFocus):f3===1005?4:f3===1006?d3(r8==="SGR"):f3===1015?4:f3===1016?d3(r8==="SGR_PIXELS"):f3===1048?1:f3===47||f3===1047||f3===1049?d3(c3===l3):f3===2004?d3(s4.bracketedPasteMode):f3===2026?d3(s4.synchronizedOutput):0,o3.triggerDataEvent(`${n3.C0.ESC}[${t5?"":"?"}${_5};${p4}$y`),!0;var _5,p4}_updateAttrColor(e4,t5,s4,i4,r8){return t5===2?(e4|=50331648,e4&=-16777216,e4|=f2.AttributeData.fromColorRGB([s4,i4,r8])):t5===5&&(e4&=-50331904,e4|=33554432|255&s4),e4}_extractColor(e4,t5,s4){let i4=[0,0,-1,0,0,0],r8=0,n4=0;do{if(i4[n4+r8]=e4.params[t5+n4],e4.hasSubParams(t5+n4)){let s5=e4.getSubParams(t5+n4),o3=0;do i4[1]===5&&(r8=1),i4[n4+o3+1+r8]=s5[o3];while(++o3<s5.length&&o3+n4+1+r8<i4.length);break}if(i4[1]===5&&n4+r8>=2||i4[1]===2&&n4+r8>=5)break;i4[1]&&(r8=1)}while(++n4+t5<e4.length&&n4+r8<i4.length);for(let e5=2;e5<i4.length;++e5)i4[e5]===-1&&(i4[e5]=0);switch(i4[0]){case 38:s4.fg=this._updateAttrColor(s4.fg,i4[1],i4[3],i4[4],i4[5]);break;case 48:s4.bg=this._updateAttrColor(s4.bg,i4[1],i4[3],i4[4],i4[5]);break;case 58:s4.extended=s4.extended.clone(),s4.extended.underlineColor=this._updateAttrColor(s4.extended.underlineColor,i4[1],i4[3],i4[4],i4[5])}return n4}_processUnderline(e4,t5){t5.extended=t5.extended.clone(),(!~e4||e4>5)&&(e4=1),t5.extended.underlineStyle=e4,t5.fg|=268435456,e4===0&&(t5.fg&=-268435457),t5.updateExtended()}_processSGR0(e4){e4.fg=l2.DEFAULT_ATTR_DATA.fg,e4.bg=l2.DEFAULT_ATTR_DATA.bg,e4.extended=e4.extended.clone(),e4.extended.underlineStyle=0,e4.extended.underlineColor&=-67108864,e4.updateExtended()}charAttributes(e4){if(e4.length===1&&e4.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t5=e4.length,s4,i4=this._curAttrData;for(let r8=0;r8<t5;r8++)s4=e4.params[r8],s4>=30&&s4<=37?(i4.fg&=-50331904,i4.fg|=16777216|s4-30):s4>=40&&s4<=47?(i4.bg&=-50331904,i4.bg|=16777216|s4-40):s4>=90&&s4<=97?(i4.fg&=-50331904,i4.fg|=16777224|s4-90):s4>=100&&s4<=107?(i4.bg&=-50331904,i4.bg|=16777224|s4-100):s4===0?this._processSGR0(i4):s4===1?i4.fg|=134217728:s4===3?i4.bg|=67108864:s4===4?(i4.fg|=268435456,this._processUnderline(e4.hasSubParams(r8)?e4.getSubParams(r8)[0]:1,i4)):s4===5?i4.fg|=536870912:s4===7?i4.fg|=67108864:s4===8?i4.fg|=1073741824:s4===9?i4.fg|=2147483648:s4===2?i4.bg|=134217728:s4===21?this._processUnderline(2,i4):s4===22?(i4.fg&=-134217729,i4.bg&=-134217729):s4===23?i4.bg&=-67108865:s4===24?(i4.fg&=-268435457,this._processUnderline(0,i4)):s4===25?i4.fg&=-536870913:s4===27?i4.fg&=-67108865:s4===28?i4.fg&=-1073741825:s4===29?i4.fg&=2147483647:s4===39?(i4.fg&=-67108864,i4.fg|=16777215&l2.DEFAULT_ATTR_DATA.fg):s4===49?(i4.bg&=-67108864,i4.bg|=16777215&l2.DEFAULT_ATTR_DATA.bg):s4===38||s4===48||s4===58?r8+=this._extractColor(e4,r8,i4):s4===53?i4.bg|=1073741824:s4===55?i4.bg&=-1073741825:s4===59?(i4.extended=i4.extended.clone(),i4.extended.underlineColor=-1,i4.updateExtended()):s4===100?(i4.fg&=-67108864,i4.fg|=16777215&l2.DEFAULT_ATTR_DATA.fg,i4.bg&=-67108864,i4.bg|=16777215&l2.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",s4);return!0}deviceStatus(e4){switch(e4.params[0]){case 5:this._coreService.triggerDataEvent(`${n3.C0.ESC}[0n`);break;case 6:let e5=this._activeBuffer.y+1,t5=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n3.C0.ESC}[${e5};${t5}R`)}return!0}deviceStatusPrivate(e4){if(e4.params[0]===6){let e5=this._activeBuffer.y+1,t5=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n3.C0.ESC}[?${e5};${t5}R`)}return!0}softReset(e4){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=l2.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e4){let t5=e4.length===0?1:e4.params[0];if(t5===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t5){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar"}let e5=t5%2==1;this._coreService.decPrivateModes.cursorBlink=e5}return!0}setScrollRegion(e4){let t5=e4.params[0]||1,s4;return(e4.length<2||(s4=e4.params[1])>this._bufferService.rows||s4===0)&&(s4=this._bufferService.rows),s4>t5&&(this._activeBuffer.scrollTop=t5-1,this._activeBuffer.scrollBottom=s4-1,this._setCursor(0,0)),!0}windowOptions(e4){if(!C3(e4.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t5=e4.length>1?e4.params[1]:0;switch(e4.params[0]){case 14:t5!==2&&this._onRequestWindowsOptionsReport.fire(w4.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(w4.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${n3.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:t5!==0&&t5!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),t5!==0&&t5!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:t5!==0&&t5!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),t5!==0&&t5!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e4){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e4){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e4){return this._windowTitle=e4,this._onTitleChange.fire(e4),!0}setIconName(e4){return this._iconName=e4,!0}setOrReportIndexedColor(e4){let t5=[],s4=e4.split(";");for(;s4.length>1;){let e5=s4.shift(),i4=s4.shift();if(/^\d+$/.exec(e5)){let s5=parseInt(e5);if(k3(s5))if(i4==="?")t5.push({type:0,index:s5});else{let e6=(0,m3.parseColor)(i4);e6&&t5.push({type:1,index:s5,color:e6})}}}return t5.length&&this._onColor.fire(t5),!0}setHyperlink(e4){let t5=e4.indexOf(";");if(t5===-1)return!0;let s4=e4.slice(0,t5).trim(),i4=e4.slice(t5+1);return i4?this._createHyperlink(s4,i4):!s4.trim()&&this._finishHyperlink()}_createHyperlink(e4,t5){this._getCurrentLinkId()&&this._finishHyperlink();let s4=e4.split(":"),i4,r8=s4.findIndex((e5)=>e5.startsWith("id="));return r8!==-1&&(i4=s4[r8].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:i4,uri:t5}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e4,t5){let s4=e4.split(";");for(let e5=0;e5<s4.length&&!(t5>=this._specialColors.length);++e5,++t5)if(s4[e5]==="?")this._onColor.fire([{type:0,index:this._specialColors[t5]}]);else{let i4=(0,m3.parseColor)(s4[e5]);i4&&this._onColor.fire([{type:1,index:this._specialColors[t5],color:i4}])}return!0}setOrReportFgColor(e4){return this._setOrReportSpecialColor(e4,0)}setOrReportBgColor(e4){return this._setOrReportSpecialColor(e4,1)}setOrReportCursorColor(e4){return this._setOrReportSpecialColor(e4,2)}restoreIndexedColor(e4){if(!e4)return this._onColor.fire([{type:2}]),!0;let t5=[],s4=e4.split(";");for(let e5=0;e5<s4.length;++e5)if(/^\d+$/.exec(s4[e5])){let i4=parseInt(s4[e5]);k3(i4)&&t5.push({type:2,index:i4})}return t5.length&&this._onColor.fire(t5),!0}restoreFgColor(e4){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e4){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e4){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,o2.DEFAULT_CHARSET),!0}selectCharset(e4){return e4.length!==2?(this.selectDefaultCharset(),!0):(e4[0]==="/"||this._charsetService.setgCharset(S3[e4[0]],o2.CHARSETS[e4[1]]||o2.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e4=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e4,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=l2.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=l2.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e4){return this._charsetService.setgLevel(e4),!0}screenAlignmentPattern(){let e4=new d2.CellData;e4.content=4194373,e4.fg=this._curAttrData.fg,e4.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t5=0;t5<this._bufferService.rows;++t5){let s4=this._activeBuffer.ybase+this._activeBuffer.y+t5,i4=this._activeBuffer.lines.get(s4);i4&&(i4.fill(e4),i4.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e4,t5){let s4=this._bufferService.buffer,i4=this._optionsService.rawOptions;return((e5)=>(this._coreService.triggerDataEvent(`${n3.C0.ESC}${e5}${n3.C0.ESC}\\`),!0))(e4==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e4==='"p'?'P1$r61;1"p':e4==="r"?`P1$r${s4.scrollTop+1};${s4.scrollBottom+1}r`:e4==="m"?"P1$r0m":e4===" q"?`P1$r${{block:2,underline:4,bar:6}[i4.cursorStyle]-(i4.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e4,t5){this._dirtyRowTracker.markRangeDirty(e4,t5)}}t4.InputHandler=A4;let L2=class{constructor(e4){this._bufferService=e4,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e4){e4<this.start?this.start=e4:e4>this.end&&(this.end=e4)}markRangeDirty(e4,t5){e4>t5&&(E3=e4,e4=t5,t5=E3),e4<this.start&&(this.start=e4),t5>this.end&&(this.end=t5)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function k3(e4){return 0<=e4&&e4<256}L2=i3([r7(0,_4.IBufferService)],L2)},701:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.isChromeOS=t4.isLinux=t4.isWindows=t4.isIphone=t4.isIpad=t4.isMac=t4.isSafari=t4.isLegacyEdge=t4.isFirefox=t4.isNode=void 0,t4.getSafariVersion=function(){if(!t4.isSafari)return 0;let e4=s3.match(/Version\/(\d+)/);return e4===null||e4.length<2?0:parseInt(e4[1])},t4.isNode=typeof process<"u"&&"title"in process;let s3=t4.isNode?"node":navigator.userAgent,i3=t4.isNode?"node":navigator.platform;t4.isFirefox=s3.includes("Firefox"),t4.isLegacyEdge=s3.includes("Edge"),t4.isSafari=/^((?!chrome|android).)*safari/i.test(s3),t4.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(i3),t4.isIpad=i3==="iPad",t4.isIphone=i3==="iPhone",t4.isWindows=["Windows","Win16","Win32","WinCE"].includes(i3),t4.isLinux=i3.indexOf("Linux")>=0,t4.isChromeOS=/\bCrOS\b/.test(s3)},6168:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.DebouncedIdleTask=t4.IdleTaskQueue=t4.PriorityTaskQueue=void 0;let i3=s3(701);class r7{constructor(){this._tasks=[],this._i=0}enqueue(e4){this._tasks.push(e4),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(e4){this._idleCallback=void 0;let t5=0,s4=0,i4=e4.timeRemaining(),r8=0;for(;this._i<this._tasks.length;){if(t5=performance.now(),this._tasks[this._i]()||this._i++,t5=Math.max(1,performance.now()-t5),s4=Math.max(t5,s4),r8=e4.timeRemaining(),1.5*s4>r8)return i4-t5<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(i4-t5))}ms`),void this._start();i4=r8}this.clear()}}class n3 extends r7{_requestCallback(e4){return setTimeout(()=>e4(this._createDeadline(16)))}_cancelCallback(e4){clearTimeout(e4)}_createDeadline(e4){let t5=performance.now()+e4;return{timeRemaining:()=>Math.max(0,t5-performance.now())}}}t4.PriorityTaskQueue=n3,t4.IdleTaskQueue=!i3.isNode&&"requestIdleCallback"in window?class extends r7{_requestCallback(e4){return requestIdleCallback(e4)}_cancelCallback(e4){cancelIdleCallback(e4)}}:n3,t4.DebouncedIdleTask=class{constructor(){this._queue=new t4.IdleTaskQueue}set(e4){this._queue.clear(),this._queue.enqueue(e4)}flush(){this._queue.flush()}}},5882:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.updateWindowsModeWrappedState=function(e4){let t5=e4.buffer.lines.get(e4.buffer.ybase+e4.buffer.y-1),s4=t5?.get(e4.cols-1),r7=e4.buffer.lines.get(e4.buffer.ybase+e4.buffer.y);r7&&s4&&(r7.isWrapped=s4[i3.CHAR_DATA_CODE_INDEX]!==i3.NULL_CELL_CODE&&s4[i3.CHAR_DATA_CODE_INDEX]!==i3.WHITESPACE_CELL_CODE)};let i3=s3(8938)},5451:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.ExtendedAttrs=t4.AttributeData=void 0;class s3{constructor(){this.fg=0,this.bg=0,this.extended=new i3}static toColorRGB(e4){return[e4>>>16&255,e4>>>8&255,255&e4]}static fromColorRGB(e4){return(255&e4[0])<<16|(255&e4[1])<<8|255&e4[2]}clone(){let e4=new s3;return e4.fg=this.fg,e4.bg=this.bg,e4.extended=this.extended.clone(),e4}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}t4.AttributeData=s3;class i3{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e4){this._ext=e4}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e4){this._ext&=-469762049,this._ext|=e4<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e4){this._ext&=-67108864,this._ext|=67108863&e4}get urlId(){return this._urlId}set urlId(e4){this._urlId=e4}get underlineVariantOffset(){let e4=(3758096384&this._ext)>>29;return e4<0?4294967288^e4:e4}set underlineVariantOffset(e4){this._ext&=536870911,this._ext|=e4<<29&3758096384}constructor(e4=0,t5=0){this._ext=0,this._urlId=0,this._ext=e4,this._urlId=t5}clone(){return new i3(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}t4.ExtendedAttrs=i3},1073:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.Buffer=t4.MAX_BUFFER_SIZE=void 0;let i3=s3(5639),r7=s3(6168),n3=s3(5451),o2=s3(6107),a2=s3(732),h2=s3(3055),c2=s3(8938),l2=s3(8158),u2=s3(6760);t4.MAX_BUFFER_SIZE=4294967295,t4.Buffer=class{constructor(e4,t5,s4){this._hasScrollback=e4,this._optionsService=t5,this._bufferService=s4,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=o2.DEFAULT_ATTR_DATA.clone(),this.savedCharset=u2.DEFAULT_CHARSET,this.markers=[],this._nullCell=h2.CellData.fromCharData([0,c2.NULL_CELL_CHAR,c2.NULL_CELL_WIDTH,c2.NULL_CELL_CODE]),this._whitespaceCell=h2.CellData.fromCharData([0,c2.WHITESPACE_CELL_CHAR,c2.WHITESPACE_CELL_WIDTH,c2.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new r7.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new i3.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e4){return e4?(this._nullCell.fg=e4.fg,this._nullCell.bg=e4.bg,this._nullCell.extended=e4.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new n3.ExtendedAttrs),this._nullCell}getWhitespaceCell(e4){return e4?(this._whitespaceCell.fg=e4.fg,this._whitespaceCell.bg=e4.bg,this._whitespaceCell.extended=e4.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new n3.ExtendedAttrs),this._whitespaceCell}getBlankLine(e4,t5){return new o2.BufferLine(this._bufferService.cols,this.getNullCell(e4),t5)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e4=this.ybase+this.y-this.ydisp;return e4>=0&&e4<this._rows}_getCorrectBufferLength(e4){if(!this._hasScrollback)return e4;let s4=e4+this._optionsService.rawOptions.scrollback;return s4>t4.MAX_BUFFER_SIZE?t4.MAX_BUFFER_SIZE:s4}fillViewportRows(e4){if(this.lines.length===0){e4===void 0&&(e4=o2.DEFAULT_ATTR_DATA);let t5=this._rows;for(;t5--;)this.lines.push(this.getBlankLine(e4))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new i3.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e4,t5){let s4=this.getNullCell(o2.DEFAULT_ATTR_DATA),i4=0,r8=this._getCorrectBufferLength(t5);if(r8>this.lines.maxLength&&(this.lines.maxLength=r8),this.lines.length>0){if(this._cols<e4)for(let t6=0;t6<this.lines.length;t6++)i4+=+this.lines.get(t6).resize(e4,s4);let n4=0;if(this._rows<t5)for(let i5=this._rows;i5<t5;i5++)this.lines.length<t5+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new o2.BufferLine(e4,s4)):this.ybase>0&&this.lines.length<=this.ybase+this.y+n4+1?(this.ybase--,n4++,this.ydisp>0&&this.ydisp--):this.lines.push(new o2.BufferLine(e4,s4)));else for(let e5=this._rows;e5>t5;e5--)this.lines.length>t5+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r8<this.lines.maxLength){let e5=this.lines.length-r8;e5>0&&(this.lines.trimStart(e5),this.ybase=Math.max(this.ybase-e5,0),this.ydisp=Math.max(this.ydisp-e5,0),this.savedY=Math.max(this.savedY-e5,0)),this.lines.maxLength=r8}this.x=Math.min(this.x,e4-1),this.y=Math.min(this.y,t5-1),n4&&(this.y+=n4),this.savedX=Math.min(this.savedX,e4-1),this.scrollTop=0}if(this.scrollBottom=t5-1,this._isReflowEnabled&&(this._reflow(e4,t5),this._cols>e4))for(let t6=0;t6<this.lines.length;t6++)i4+=+this.lines.get(t6).resize(e4,s4);this._cols=e4,this._rows=t5,this._memoryCleanupQueue.clear(),i4>0.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e4=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e4=!1);let t5=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t5+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t5>100)return!0;return e4}get _isReflowEnabled(){let e4=this._optionsService.rawOptions.windowsPty;return e4&&e4.buildNumber?this._hasScrollback&&e4.backend==="conpty"&&e4.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e4,t5){this._cols!==e4&&(e4>this._cols?this._reflowLarger(e4,t5):this._reflowSmaller(e4,t5))}_reflowLarger(e4,t5){let s4=this._optionsService.rawOptions.reflowCursorLine,i4=(0,a2.reflowLargerGetLinesToRemove)(this.lines,this._cols,e4,this.ybase+this.y,this.getNullCell(o2.DEFAULT_ATTR_DATA),s4);if(i4.length>0){let s5=(0,a2.reflowLargerCreateNewLayout)(this.lines,i4);(0,a2.reflowLargerApplyNewLayout)(this.lines,s5.layout),this._reflowLargerAdjustViewport(e4,t5,s5.countRemoved)}}_reflowLargerAdjustViewport(e4,t5,s4){let i4=this.getNullCell(o2.DEFAULT_ATTR_DATA),r8=s4;for(;r8-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t5&&this.lines.push(new o2.BufferLine(e4,i4))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-s4,0)}_reflowSmaller(e4,t5){let s4=this._optionsService.rawOptions.reflowCursorLine,i4=this.getNullCell(o2.DEFAULT_ATTR_DATA),r8=[],n4=0;for(let h3=this.lines.length-1;h3>=0;h3--){let c3=this.lines.get(h3);if(!c3||!c3.isWrapped&&c3.getTrimmedLength()<=e4)continue;let l3=[c3];for(;c3.isWrapped&&h3>0;)c3=this.lines.get(--h3),l3.unshift(c3);if(!s4){let e5=this.ybase+this.y;if(e5>=h3&&e5<h3+l3.length)continue}let u3=l3[l3.length-1].getTrimmedLength(),d2=(0,a2.reflowSmallerGetNewLineLengths)(l3,this._cols,e4),f2=d2.length-l3.length,_4;_4=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+f2):Math.max(0,this.lines.length-this.lines.maxLength+f2);let p3=[];for(let e5=0;e5<f2;e5++){let e6=this.getBlankLine(o2.DEFAULT_ATTR_DATA,!0);p3.push(e6)}p3.length>0&&(r8.push({start:h3+l3.length+n4,newLines:p3}),n4+=p3.length),l3.push(...p3);let g3=d2.length-1,v3=d2[g3];v3===0&&(g3--,v3=d2[g3]);let m3=l3.length-f2-1,b3=u3;for(;m3>=0;){let e5=Math.min(b3,v3);if(l3[g3]===void 0)break;if(l3[g3].copyCellsFrom(l3[m3],b3-e5,v3-e5,e5,!0),v3-=e5,v3===0&&(g3--,v3=d2[g3]),b3-=e5,b3===0){m3--;let e6=Math.max(m3,0);b3=(0,a2.getWrappedLineTrimmedLength)(l3,e6,this._cols)}}for(let t6=0;t6<l3.length;t6++)d2[t6]<e4&&l3[t6].setCell(d2[t6],i4);let S3=f2-_4;for(;S3-- >0;)this.ybase===0?this.y<t5-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+n4)-t5&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+f2,this.ybase+t5-1)}if(r8.length>0){let e5=[],t6=[];for(let e6=0;e6<this.lines.length;e6++)t6.push(this.lines.get(e6));let s5=this.lines.length,i5=s5-1,o3=0,a3=r8[o3];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+n4);let h3=0;for(let c4=Math.min(this.lines.maxLength-1,s5+n4-1);c4>=0;c4--)if(a3&&a3.start>i5+h3){for(let e6=a3.newLines.length-1;e6>=0;e6--)this.lines.set(c4--,a3.newLines[e6]);c4++,e5.push({index:i5+1,amount:a3.newLines.length}),h3+=a3.newLines.length,a3=r8[++o3]}else this.lines.set(c4,t6[i5--]);let c3=0;for(let t7=e5.length-1;t7>=0;t7--)e5[t7].index+=c3,this.lines.onInsertEmitter.fire(e5[t7]),c3+=e5[t7].amount;let l3=Math.max(0,s5+n4-this.lines.maxLength);l3>0&&this.lines.onTrimEmitter.fire(l3)}}translateBufferLineToString(e4,t5,s4=0,i4){let r8=this.lines.get(e4);return r8?r8.translateToString(t5,s4,i4):""}getWrappedRangeForLine(e4){let t5=e4,s4=e4;for(;t5>0&&this.lines.get(t5).isWrapped;)t5--;for(;s4+1<this.lines.length&&this.lines.get(s4+1).isWrapped;)s4++;return{first:t5,last:s4}}setupTabStops(e4){for(e4!=null?this.tabs[e4]||(e4=this.prevStop(e4)):(this.tabs={},e4=0);e4<this._cols;e4+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e4]=!0}prevStop(e4){for(e4==null&&(e4=this.x);!this.tabs[--e4]&&e4>0;);return e4>=this._cols?this._cols-1:e4<0?0:e4}nextStop(e4){for(e4==null&&(e4=this.x);!this.tabs[++e4]&&e4<this._cols;);return e4>=this._cols?this._cols-1:e4<0?0:e4}clearMarkers(e4){this._isClearing=!0;for(let t5=0;t5<this.markers.length;t5++)this.markers[t5].line===e4&&(this.markers[t5].dispose(),this.markers.splice(t5--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e4=0;e4<this.markers.length;e4++)this.markers[e4].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e4){let t5=new l2.Marker(e4);return this.markers.push(t5),t5.register(this.lines.onTrim((e5)=>{t5.line-=e5,t5.line<0&&t5.dispose()})),t5.register(this.lines.onInsert((e5)=>{t5.line>=e5.index&&(t5.line+=e5.amount)})),t5.register(this.lines.onDelete((e5)=>{t5.line>=e5.index&&t5.line<e5.index+e5.amount&&t5.dispose(),t5.line>e5.index&&(t5.line-=e5.amount)})),t5.register(t5.onDispose(()=>this._removeMarker(t5))),t5}_removeMarker(e4){this._isClearing||this.markers.splice(this.markers.indexOf(e4),1)}}},6107:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.BufferLine=t4.DEFAULT_ATTR_DATA=void 0;let i3=s3(5451),r7=s3(3055),n3=s3(8938),o2=s3(726);t4.DEFAULT_ATTR_DATA=Object.freeze(new i3.AttributeData);let a2=0;class h2{constructor(e4,t5,s4=!1){this.isWrapped=s4,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e4);let i4=t5||r7.CellData.fromCharData([0,n3.NULL_CELL_CHAR,n3.NULL_CELL_WIDTH,n3.NULL_CELL_CODE]);for(let t6=0;t6<e4;++t6)this.setCell(t6,i4);this.length=e4}get(e4){let t5=this._data[3*e4+0],s4=2097151&t5;return[this._data[3*e4+1],2097152&t5?this._combined[e4]:s4?(0,o2.stringFromCodePoint)(s4):"",t5>>22,2097152&t5?this._combined[e4].charCodeAt(this._combined[e4].length-1):s4]}set(e4,t5){this._data[3*e4+1]=t5[n3.CHAR_DATA_ATTR_INDEX],t5[n3.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e4]=t5[1],this._data[3*e4+0]=2097152|e4|t5[n3.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*e4+0]=t5[n3.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t5[n3.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(e4){return this._data[3*e4+0]>>22}hasWidth(e4){return 12582912&this._data[3*e4+0]}getFg(e4){return this._data[3*e4+1]}getBg(e4){return this._data[3*e4+2]}hasContent(e4){return 4194303&this._data[3*e4+0]}getCodePoint(e4){let t5=this._data[3*e4+0];return 2097152&t5?this._combined[e4].charCodeAt(this._combined[e4].length-1):2097151&t5}isCombined(e4){return 2097152&this._data[3*e4+0]}getString(e4){let t5=this._data[3*e4+0];return 2097152&t5?this._combined[e4]:2097151&t5?(0,o2.stringFromCodePoint)(2097151&t5):""}isProtected(e4){return 536870912&this._data[3*e4+2]}loadCell(e4,t5){return a2=3*e4,t5.content=this._data[a2+0],t5.fg=this._data[a2+1],t5.bg=this._data[a2+2],2097152&t5.content&&(t5.combinedData=this._combined[e4]),268435456&t5.bg&&(t5.extended=this._extendedAttrs[e4]),t5}setCell(e4,t5){2097152&t5.content&&(this._combined[e4]=t5.combinedData),268435456&t5.bg&&(this._extendedAttrs[e4]=t5.extended),this._data[3*e4+0]=t5.content,this._data[3*e4+1]=t5.fg,this._data[3*e4+2]=t5.bg}setCellFromCodepoint(e4,t5,s4,i4){268435456&i4.bg&&(this._extendedAttrs[e4]=i4.extended),this._data[3*e4+0]=t5|s4<<22,this._data[3*e4+1]=i4.fg,this._data[3*e4+2]=i4.bg}addCodepointToCell(e4,t5,s4){let i4=this._data[3*e4+0];2097152&i4?this._combined[e4]+=(0,o2.stringFromCodePoint)(t5):2097151&i4?(this._combined[e4]=(0,o2.stringFromCodePoint)(2097151&i4)+(0,o2.stringFromCodePoint)(t5),i4&=-2097152,i4|=2097152):i4=t5|4194304,s4&&(i4&=-12582913,i4|=s4<<22),this._data[3*e4+0]=i4}insertCells(e4,t5,s4){if((e4%=this.length)&&this.getWidth(e4-1)===2&&this.setCellFromCodepoint(e4-1,0,1,s4),t5<this.length-e4){let i4=new r7.CellData;for(let s5=this.length-e4-t5-1;s5>=0;--s5)this.setCell(e4+t5+s5,this.loadCell(e4+s5,i4));for(let i5=0;i5<t5;++i5)this.setCell(e4+i5,s4)}else for(let t6=e4;t6<this.length;++t6)this.setCell(t6,s4);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,s4)}deleteCells(e4,t5,s4){if(e4%=this.length,t5<this.length-e4){let i4=new r7.CellData;for(let s5=0;s5<this.length-e4-t5;++s5)this.setCell(e4+s5,this.loadCell(e4+t5+s5,i4));for(let e5=this.length-t5;e5<this.length;++e5)this.setCell(e5,s4)}else for(let t6=e4;t6<this.length;++t6)this.setCell(t6,s4);e4&&this.getWidth(e4-1)===2&&this.setCellFromCodepoint(e4-1,0,1,s4),this.getWidth(e4)!==0||this.hasContent(e4)||this.setCellFromCodepoint(e4,0,1,s4)}replaceCells(e4,t5,s4,i4=!1){if(i4)for(e4&&this.getWidth(e4-1)===2&&!this.isProtected(e4-1)&&this.setCellFromCodepoint(e4-1,0,1,s4),t5<this.length&&this.getWidth(t5-1)===2&&!this.isProtected(t5)&&this.setCellFromCodepoint(t5,0,1,s4);e4<t5&&e4<this.length;)this.isProtected(e4)||this.setCell(e4,s4),e4++;else for(e4&&this.getWidth(e4-1)===2&&this.setCellFromCodepoint(e4-1,0,1,s4),t5<this.length&&this.getWidth(t5-1)===2&&this.setCellFromCodepoint(t5,0,1,s4);e4<t5&&e4<this.length;)this.setCell(e4++,s4)}resize(e4,t5){if(e4===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let s4=3*e4;if(e4>this.length){if(this._data.buffer.byteLength>=4*s4)this._data=new Uint32Array(this._data.buffer,0,s4);else{let e5=new Uint32Array(s4);e5.set(this._data),this._data=e5}for(let s5=this.length;s5<e4;++s5)this.setCell(s5,t5)}else{this._data=this._data.subarray(0,s4);let t6=Object.keys(this._combined);for(let s5=0;s5<t6.length;s5++){let i5=parseInt(t6[s5],10);i5>=e4&&delete this._combined[i5]}let i4=Object.keys(this._extendedAttrs);for(let t7=0;t7<i4.length;t7++){let s5=parseInt(i4[t7],10);s5>=e4&&delete this._extendedAttrs[s5]}}return this.length=e4,4*s4*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let e4=new Uint32Array(this._data.length);return e4.set(this._data),this._data=e4,1}return 0}fill(e4,t5=!1){if(t5)for(let t6=0;t6<this.length;++t6)this.isProtected(t6)||this.setCell(t6,e4);else{this._combined={},this._extendedAttrs={};for(let t6=0;t6<this.length;++t6)this.setCell(t6,e4)}}copyFrom(e4){this.length!==e4.length?this._data=new Uint32Array(e4._data):this._data.set(e4._data),this.length=e4.length,this._combined={};for(let t5 in e4._combined)this._combined[t5]=e4._combined[t5];this._extendedAttrs={};for(let t5 in e4._extendedAttrs)this._extendedAttrs[t5]=e4._extendedAttrs[t5];this.isWrapped=e4.isWrapped}clone(){let e4=new h2(0);e4._data=new Uint32Array(this._data),e4.length=this.length;for(let t5 in this._combined)e4._combined[t5]=this._combined[t5];for(let t5 in this._extendedAttrs)e4._extendedAttrs[t5]=this._extendedAttrs[t5];return e4.isWrapped=this.isWrapped,e4}getTrimmedLength(){for(let e4=this.length-1;e4>=0;--e4)if(4194303&this._data[3*e4+0])return e4+(this._data[3*e4+0]>>22);return 0}getNoBgTrimmedLength(){for(let e4=this.length-1;e4>=0;--e4)if(4194303&this._data[3*e4+0]||50331648&this._data[3*e4+2])return e4+(this._data[3*e4+0]>>22);return 0}copyCellsFrom(e4,t5,s4,i4,r8){let n4=e4._data;if(r8)for(let r9=i4-1;r9>=0;r9--){for(let e5=0;e5<3;e5++)this._data[3*(s4+r9)+e5]=n4[3*(t5+r9)+e5];268435456&n4[3*(t5+r9)+2]&&(this._extendedAttrs[s4+r9]=e4._extendedAttrs[t5+r9])}else for(let r9=0;r9<i4;r9++){for(let e5=0;e5<3;e5++)this._data[3*(s4+r9)+e5]=n4[3*(t5+r9)+e5];268435456&n4[3*(t5+r9)+2]&&(this._extendedAttrs[s4+r9]=e4._extendedAttrs[t5+r9])}let o3=Object.keys(e4._combined);for(let i5=0;i5<o3.length;i5++){let r9=parseInt(o3[i5],10);r9>=t5&&(this._combined[r9-t5+s4]=e4._combined[r9])}}translateToString(e4,t5,s4,i4){t5=t5??0,s4=s4??this.length,e4&&(s4=Math.min(s4,this.getTrimmedLength())),i4&&(i4.length=0);let r8="";for(;t5<s4;){let e5=this._data[3*t5+0],s5=2097151&e5,a3=2097152&e5?this._combined[t5]:s5?(0,o2.stringFromCodePoint)(s5):n3.WHITESPACE_CELL_CHAR;if(r8+=a3,i4)for(let e6=0;e6<a3.length;++e6)i4.push(t5);t5+=e5>>22||1}return i4&&i4.push(t5),r8}}t4.BufferLine=h2},732:(e3,t4)=>{function s3(e4,t5,s4){if(t5===e4.length-1)return e4[t5].getTrimmedLength();let i3=!e4[t5].hasContent(s4-1)&&e4[t5].getWidth(s4-1)===1,r7=e4[t5+1].getWidth(0)===2;return i3&&r7?s4-1:s4}Object.defineProperty(t4,"__esModule",{value:!0}),t4.reflowLargerGetLinesToRemove=function(e4,t5,i3,r7,n3,o2){let a2=[];for(let h2=0;h2<e4.length-1;h2++){let c2=h2,l2=e4.get(++c2);if(!l2.isWrapped)continue;let u2=[e4.get(h2)];for(;c2<e4.length&&l2.isWrapped;)u2.push(l2),l2=e4.get(++c2);if(!o2&&r7>=h2&&r7<c2){h2+=u2.length-1;continue}let d2=0,f2=s3(u2,d2,t5),_4=1,p3=0;for(;_4<u2.length;){let e5=s3(u2,_4,t5),r8=e5-p3,o3=i3-f2,a3=Math.min(r8,o3);u2[d2].copyCellsFrom(u2[_4],p3,f2,a3,!1),f2+=a3,f2===i3&&(d2++,f2=0),p3+=a3,p3===e5&&(_4++,p3=0),f2===0&&d2!==0&&u2[d2-1].getWidth(i3-1)===2&&(u2[d2].copyCellsFrom(u2[d2-1],i3-1,f2++,1,!1),u2[d2-1].setCell(i3-1,n3))}u2[d2].replaceCells(f2,i3,n3);let g3=0;for(let e5=u2.length-1;e5>0&&(e5>d2||u2[e5].getTrimmedLength()===0);e5--)g3++;g3>0&&(a2.push(h2+u2.length-g3),a2.push(g3)),h2+=u2.length-1}return a2},t4.reflowLargerCreateNewLayout=function(e4,t5){let s4=[],i3=0,r7=t5[i3],n3=0;for(let o2=0;o2<e4.length;o2++)if(r7===o2){let s5=t5[++i3];e4.onDeleteEmitter.fire({index:o2-n3,amount:s5}),o2+=s5-1,n3+=s5,r7=t5[++i3]}else s4.push(o2);return{layout:s4,countRemoved:n3}},t4.reflowLargerApplyNewLayout=function(e4,t5){let s4=[];for(let i3=0;i3<t5.length;i3++)s4.push(e4.get(t5[i3]));for(let t6=0;t6<s4.length;t6++)e4.set(t6,s4[t6]);e4.length=t5.length},t4.reflowSmallerGetNewLineLengths=function(e4,t5,i3){let r7=[],n3=e4.map((i4,r8)=>s3(e4,r8,t5)).reduce((e5,t6)=>e5+t6),o2=0,a2=0,h2=0;for(;h2<n3;){if(n3-h2<i3){r7.push(n3-h2);break}o2+=i3;let c2=s3(e4,a2,t5);o2>c2&&(o2-=c2,a2++);let l2=e4[a2].getWidth(o2-1)===2;l2&&o2--;let u2=l2?i3-1:i3;r7.push(u2),h2+=u2}return r7},t4.getWrappedLineTrimmedLength=s3},4097:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.BufferSet=void 0;let i3=s3(7150),r7=s3(1073),n3=s3(802);class o2 extends i3.Disposable{constructor(e4,t5){super(),this._optionsService=e4,this._bufferService=t5,this._onBufferActivate=this._register(new n3.Emitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new r7.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new r7.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e4){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e4),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e4,t5){this._normal.resize(e4,t5),this._alt.resize(e4,t5),this.setupTabStops(e4)}setupTabStops(e4){this._normal.setupTabStops(e4),this._alt.setupTabStops(e4)}}t4.BufferSet=o2},3055:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.CellData=void 0;let i3=s3(726),r7=s3(8938),n3=s3(5451);class o2 extends n3.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new n3.ExtendedAttrs,this.combinedData=""}static fromCharData(e4){let t5=new o2;return t5.setFromCharData(e4),t5}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,i3.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e4){this.fg=e4[r7.CHAR_DATA_ATTR_INDEX],this.bg=0;let t5=!1;if(e4[r7.CHAR_DATA_CHAR_INDEX].length>2)t5=!0;else if(e4[r7.CHAR_DATA_CHAR_INDEX].length===2){let s4=e4[r7.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=s4&&s4<=56319){let i4=e4[r7.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=i4&&i4<=57343?this.content=1024*(s4-55296)+i4-56320+65536|e4[r7.CHAR_DATA_WIDTH_INDEX]<<22:t5=!0}else t5=!0}else this.content=e4[r7.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e4[r7.CHAR_DATA_WIDTH_INDEX]<<22;t5&&(this.combinedData=e4[r7.CHAR_DATA_CHAR_INDEX],this.content=2097152|e4[r7.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t4.CellData=o2},8938:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.WHITESPACE_CELL_CODE=t4.WHITESPACE_CELL_WIDTH=t4.WHITESPACE_CELL_CHAR=t4.NULL_CELL_CODE=t4.NULL_CELL_WIDTH=t4.NULL_CELL_CHAR=t4.CHAR_DATA_CODE_INDEX=t4.CHAR_DATA_WIDTH_INDEX=t4.CHAR_DATA_CHAR_INDEX=t4.CHAR_DATA_ATTR_INDEX=t4.DEFAULT_EXT=t4.DEFAULT_ATTR=t4.DEFAULT_COLOR=void 0,t4.DEFAULT_COLOR=0,t4.DEFAULT_ATTR=t4.DEFAULT_COLOR<<9|256,t4.DEFAULT_EXT=0,t4.CHAR_DATA_ATTR_INDEX=0,t4.CHAR_DATA_CHAR_INDEX=1,t4.CHAR_DATA_WIDTH_INDEX=2,t4.CHAR_DATA_CODE_INDEX=3,t4.NULL_CELL_CHAR="",t4.NULL_CELL_WIDTH=1,t4.NULL_CELL_CODE=0,t4.WHITESPACE_CELL_CHAR=" ",t4.WHITESPACE_CELL_WIDTH=1,t4.WHITESPACE_CELL_CODE=32},8158:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.Marker=void 0;let i3=s3(802),r7=s3(7150);class n3{get id(){return this._id}constructor(e4){this.line=e4,this.isDisposed=!1,this._disposables=[],this._id=n3._nextId++,this._onDispose=this.register(new i3.Emitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,r7.dispose)(this._disposables),this._disposables.length=0)}register(e4){return this._disposables.push(e4),e4}}t4.Marker=n3,n3._nextId=1},6760:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.DEFAULT_CHARSET=t4.CHARSETS=void 0,t4.CHARSETS={},t4.DEFAULT_CHARSET=t4.CHARSETS.B,t4.CHARSETS[0]={"`":"\u25C6",a:"\u2592",b:"\u2409",c:"\u240C",d:"\u240D",e:"\u240A",f:"\xB0",g:"\xB1",h:"\u2424",i:"\u240B",j:"\u2518",k:"\u2510",l:"\u250C",m:"\u2514",n:"\u253C",o:"\u23BA",p:"\u23BB",q:"\u2500",r:"\u23BC",s:"\u23BD",t:"\u251C",u:"\u2524",v:"\u2534",w:"\u252C",x:"\u2502",y:"\u2264",z:"\u2265","{":"\u03C0","|":"\u2260","}":"\xA3","~":"\xB7"},t4.CHARSETS.A={"#":"\xA3"},t4.CHARSETS.B=void 0,t4.CHARSETS[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"},t4.CHARSETS.C=t4.CHARSETS[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"},t4.CHARSETS.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"},t4.CHARSETS.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"},t4.CHARSETS.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"},t4.CHARSETS.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"},t4.CHARSETS.E=t4.CHARSETS[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"},t4.CHARSETS.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"},t4.CHARSETS.H=t4.CHARSETS[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"},t4.CHARSETS["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"}},3534:(e3,t4)=>{var s3,i3,r7;Object.defineProperty(t4,"__esModule",{value:!0}),t4.C1_ESCAPED=t4.C1=t4.C0=void 0,function(e4){e4.NUL="\x00",e4.SOH="\x01",e4.STX="\x02",e4.ETX="\x03",e4.EOT="\x04",e4.ENQ="\x05",e4.ACK="\x06",e4.BEL="\x07",e4.BS="\b",e4.HT="\t",e4.LF=`
2
+ import{APPEARANCE_SETTINGS,COLORBLIND_KEY,DEFAULT_BASE_REF,DEFAULT_COLORBLIND,DEFAULT_GLYPHS,DEFAULT_GLYPH_SET,DEFAULT_RUNNING_TITLE,DEFAULT_SCROLLBACK_ROWS,DEFAULT_TASK_COLORS,DEFAULT_WORKING_BORDER,EVENT_FEED_LIMIT,GLYPH_SETS,GLYPH_SET_KEY,ISSUE_CHAT_PLACEMENTS,PREFIX_TAP_PRESENTATIONS,PREFIX_TAP_PRESENTATION_KEY,RUNNING_TITLE_KEY,SCROLLBACK_ROWS_KEY,SECTIONS,SECTIONS_SIDEBAR_WIDTH,SPLIT_STYLE_KEY,TAB_STRIP_HIDE_SINGLE_KEY,TAB_STRIP_MODES,TAB_STRIP_MODE_KEY,TASK_COLORS_KEY,WORKING_BORDER_KEY,appearanceChoices,appendAttachmentRefs,applyAppearanceChoice,asAttachmentPaths,attachmentLabel,autoRoutingRows,buildDiffReview,buildPRPrompt,captureClipboardAttachment,cloneRepo,commentAtRow,commentRange,compareName,compareNewest,compareRecent,computeReviewPaint,conversationTitleOf,createBackgroundPoller,createKeybindingsFile,currentAppearanceChoice,deriveFolderName,detectWorktreeOpener,devRows,displayEndpoint,displaySettingValue,engineIntegrations,enginesNeedingHookInstall,enginesWithHooksInstalled,eventRows,findAvailableFolderName,findFileHandler,fuzzyMatch,gatherPRPromptState,generalLabelLayout,generalRows,getCurrentBranch,isBooleanOn,isNoProjectTask,issueChatTaskTitle,issueProjectPrompt,issueWorktreePrompt,keybindingRows,languageRowId,listLocalBranches,nextEnumValue,normalizeColorblind,normalizeGlyphSet,normalizeNumberInput,normalizePrefixTapPresentation,normalizeRunningTitle,normalizeScrollbackRows,normalizeSplitStyle,normalizeTaskColors,normalizeWorkingBorder,openExternally,openWorktree,persistedScrollbackRows,pluginPageErrorState,prefixTapPresentationRowId,readPluginRows,reconcileStableRows,relativeAge,relativeBuckets,repoBasename,resolveCloneTarget,resolveTabStripMode,rowAt,rowIndex,rowLiveBranchPath,sectionRows,setPluginEnabled,setPluginSetting,sidebarPrChip,sidebarProjectKeyOfTask,sidebarProjectKeyResolver,sidebarProjectLabel,sidebarRepoLabel,spawnDetached,subscribeBackgroundPolls,tabStripVisible,taskColor,toggledBooleanValue,truncateEnd,truncateEndCells,truncateStartCells,unifiedDiffRows,unsentComments,validateCloneTarget,validateGitUrl,validateRepoPath,withImagePlaceholders,worktreeRowLabel}from"./chunk-nhd4y1dw.js";import{machineOfTask,useMachineRows,useMergedTasks}from"./chunk-stng29vp.js";import{trackWelcomeWrite}from"./chunk-9s7q3432.js";import{installSkillNow,skillMissing}from"./chunk-676f3tva.js";import{fetchMarketplace}from"./chunk-grr2fn38.js";import"./chunk-c25vea1q.js";import{failureHint}from"./chunk-t2p22ww7.js";import{preparePluginInstall}from"./chunk-se00fc8v.js";import{formatBytes}from"./chunk-my20q579.js";import"./chunk-x89zw7br.js";import{humanOnlyFix,noEngineFix}from"./chunk-am5cpb9n.js";import{embeddedTerminalEnv}from"./chunk-7bgbansg.js";import{deriveTitleFromSessionId,startTaskSessionWithPromptAdapter}from"./chunk-1cyeyw6g.js";import{buildCIPromptForWorktree}from"./chunk-vkz6kkmm.js";import{canonPath,checkResolutionNotify}from"./chunk-1wwqf6kx.js";import{readLastActiveTaskId}from"./chunk-c1dz3qg3.js";import{isValidCron,nextCronAfter}from"./chunk-a4hsqj1b.js";import{tabStatus,taskStatus}from"./chunk-6hcyvg0m.js";import{installSkillErrors,skillTargets}from"./chunk-5vrg6h71.js";import{DIRECT_GUIDE_PREFIX_ACTION_ID,MarkdownText,PaneErrorBoundary,ReleaseNotesBody,RenderProfiler,armPrefixFromCurrentStack,bindByIds,bootPaneHost,currentBindingReachability,currentPaletteActions,defaultChordsOf,findBinding,formatChord,hostTargetFps,imeAnchorController,invokeArmedPrefixActionFromCurrentStack,isNarrowWidth,keymapVersion,modalActive,narrowSurface,pageCloseBindings,pluginKeybindings,redrawScreen,reloadUserKeybindings,runShellUpdater,shortcutCaption,showDialog,subscribeBindingStack,subscribeKeymapVersion,useAccessor,useBindingStackVersion,useBindings,useDialog,useDialogPaddingX,useFocus,useKV,useLatest,useNotifications,useOptionalDialog,useOptionalFocus,useOptionalKV,useOptionalNotifications,useT,useTerminalSize,useTheme,userKeybindingsReport}from"./chunk-7ks7rrnr.js";import{DEFAULT_SOUND_VOLUME,FINISHED_ALERTS_KEY,FIXED_BINDING_IDS,PREFIX_GUIDE_DELAY_MS,PREFIX_HUD_TTL_MS,RAIL_FOLD_STYLE_KEY,RoveKeymap,SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,SOUND_VOLUME_KEY,ZEN_ACTIVE_KEY,ZEN_DEFAULT,attentionEdges,attentionKindFor,chipAttentionKind,currentPrefixConfiguration,isKittyModifierKeyEvent,nextSoundVolume,normalizeSoundVolume,prefixAction,prefixHudClock,prefixHudState}from"./chunk-x85rcep5.js";import{$Fragment,$jsx,$jsxs,flushSync,usePaste,useRenderer}from"./chunk-29kvfqeh.js";import{require_react_production}from"./chunk-2wd4744g.js";import{RemoteOrchestrator,absorbTab,adoptTabs,liveRowTokens}from"./chunk-v6v272b3.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-6xr1prk6.js";import"./chunk-764bsyb0.js";import{UPDATE_CHANNEL_KEY,UPDATE_NOTIFY_KEY,normalizeReleaseChannel,preferredReleaseChannel,updateNotifyEnabled}from"./chunk-m98jd1fz.js";import"./chunk-xte4phd1.js";import{AUTO_ROUTING_TIERS,autoRoutingKey,classifyScreen,contentFirstLine,deriveTaskGroup,describeTierBlock,filetypeOf,isCombinedPathspec,isImagePath,listFiles,liveSourceProtocol,loadPreviewData,patchFirstLine,planChatContinuation,planWorktreeHandoff,readAutoRoutingTable,readClassifierConfig,resolveBase,searchTasks,secretStatus,statusFiles,statusFilesBranch,taskGroupRank,tierBlock,unifiedDiffFiles,worktreeFilePath,writeSecret}from"./chunk-kgpj4k4z.js";import{reloadPluginEngines}from"./chunk-kdnk8m5j.js";import{listPaneLaunches}from"./chunk-rjfdzjhj.js";import{detectEngineStatus,detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-r2bb8b11.js";import{DEFAULT_EDITOR_KIND,EDITOR_CUSTOM_KEY,EDITOR_KINDS,EDITOR_KIND_KEY,normalizeEditorKind,resolveEditorLaunch}from"./chunk-agvtzads.js";import{SHELL_TASK_TITLE,deriveTitleFromPrompt}from"./chunk-2xsxcdp6.js";import"./chunk-17e2tgyg.js";import{FORK_UNSUPPORTED_CODE,PROJECT_SIBLING_BASE,TASK_DELETING_CODE,TaskDeletingError,WORKTREE_BASE_CUSTOM_KEY,dirtyRefusalReason,worktreeBaseKindOf}from"./chunk-1vxtd8rh.js";import{ISSUE_STATUSES}from"./chunk-4hestsjp.js";import"./chunk-qgrg9a5n.js";import"./chunk-2bgmby1d.js";import{loadPluginRegistry,readPluginManifest}from"./chunk-n0rdn2fn.js";import"./chunk-5mhvjytn.js";import"./chunk-atn06ncf.js";import{submitFeedback}from"./chunk-tt58819p.js";import{forwardVerb,requireMachine}from"./chunk-k9jhy3yx.js";import"./chunk-vytrhm50.js";import"./chunk-vp29jgbt.js";import{PROJECT_DIR_TOKEN,WORKTREE_BASE_KEY,hasProjectDirToken,normalizeWorktreeBase}from"./chunk-gq36nzg8.js";import"./chunk-sq6zj3fb.js";import{ulid}from"./chunk-qkehg2c1.js";import{approxCellWidth,approxCharCells,charWidth,displayWidth,padEndCells}from"./chunk-dvcb6mk4.js";import{hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp}from"./chunk-2drde6sc.js";import{ensurePtyHostReachable}from"./chunk-z43e08kw.js";import"./chunk-w77s2df8.js";import{DEFAULT_TERMINAL_COLORS,formatDefaultColorReply,parseTerminalDefaultColors}from"./chunk-mqfvzdpr.js";import{LOCALE_KEY,breathColor,breathGlyph,diffInks,mixInk,turnHue}from"./chunk-f7egph8g.js";import"./chunk-rxqdw6s5.js";import"./chunk-kxp04jnp.js";import{addTab,closeActiveTab,closeTab,collapseSplit,conversationTitle,cycleLeaf,cycleTab,engineTabSpawnFor,expandHome,filterSubdirs,findEditorTab,gotoTab,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,tabCwdFor,tabExitAction,tabPtyKey,tabPtyKeyFor,tabTitle,tabTitleStable,visibleNativeStatus}from"./chunk-d6j2d6fk.js";import{AUTO_STATUS_KEY,DISPATCHER_KEY,repoEnv}from"./chunk-61cn88e7.js";import{ENGINE_PROTOCOLS,applyTabOps,defaultEngineCommand,diffTabs,engineCommandKey,engineDisplayName,engineLaunchArgv,engineNameKey,engineProtocolKey,engineRenamedFrom,humanizeSlug,interactiveEngineCommand,pickUnclaimedSessionId,protocolEntry,roveApiInvocation,withPinnedSessionId}from"./chunk-atg13xab.js";import"./chunk-r5j8fycq.js";import{isBuiltinModInstalled,setBuiltinModInstalled}from"./chunk-xfgqae9t.js";import{builtinModsPath}from"./chunk-j1z9kgyd.js";import{aliasedKeys,isUnderKey,teardownScope}from"./chunk-g9ba25q5.js";import"./chunk-ggnq2vvk.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import{terminalTabsKey}from"./chunk-mdc7b01e.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{execHostForWorktreePath,remoteKeyForRepo}from"./chunk-895yqjjz.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import{connectOrStartDaemon}from"./chunk-e58kj4gm.js";import"./chunk-0a65j1zj.js";import"./chunk-bcyex84w.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-vvqwgcge.js";import{createEngineHookAdapter,engineEntry,engineSessionIdFromTitle,engineTitleTurnHint,getCapabilities,stripEngineStatusPrefix}from"./chunk-x83xbzjd.js";import{spawnCapture}from"./chunk-2tfnscxk.js";import{availableEngineIds,installedEngineIds}from"./chunk-hzz020xx.js";import"./chunk-w7zv47mp.js";import"./chunk-etfh8f4z.js";import{getGlobalDefaultVendor,resolvePreferredVendor,setGlobalDefaultVendor,setRepoLastActiveVendor}from"./chunk-9rj2fx6v.js";import{addSavedRepo,getSavedRepos,isGitRepo,isRemoteRepoKey,resolveMainRepoRoot}from"./chunk-rfp0ayra.js";import{parsePorcelain,sameWorktreeChanges}from"./chunk-0r1jf8m9.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import{recordSpawn}from"./chunk-40dgv828.js";import"./chunk-kg9kmwt9.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{processCwd}from"./chunk-3n0y9vpj.js";import{matchPathGlob}from"./chunk-kg11c1py.js";import{CURRENT_VERSION,RELEASE_CHANNELS,channelOf,checkLatestVersion,fetchReleaseNotesRange,releasePageUrl,updateCommandFor}from"./chunk-9ckvdy0j.js";import"./chunk-zsfyj36g.js";import{tildify}from"./chunk-2r1fgng9.js";import{errorMessage,userFacingErrorMessage}from"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import{currentLang,intlLocale,registerMessages,setLocaleLang,t,tKeys}from"./chunk-nqwza8b0.js";import{LOCALES}from"./chunk-ve76p2mx.js";import{createStateCell,profileSpan,profileTick}from"./chunk-cmp64q4j.js";import{CHANNEL_NAMES,RoveDaemonClient,attentionInboxItemKey,automationRunNeedsAttention,isRoutineInboxState,routineRunResponseState}from"./chunk-qzzmd63x.js";import"./chunk-96kvwzj8.js";import"./chunk-7bakcyes.js";import{roveCliInvocation}from"./chunk-8qkyd589.js";import"./chunk-7kysxgbq.js";import"./chunk-hz1x3hak.js";import{MULTI_REPO_CAP,childrenOf,isSharedChild,rollupPr,taskCwd,taskRepos,workspaceCapabilities}from"./chunk-x1jxxmtc.js";import{DEFAULT_TASK_VENDOR,TASK_STATUSES}from"./chunk-xy8be792.js";import{ALL_VENDORS,isBuiltinVendor,nextVendorWithin,prevVendorWithin}from"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import{isDev,roveStateDir}from"./chunk-z1nj22va.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{logClientError}from"./chunk-0g4wc808.js";import{pathIdentity,pathSyntax,pathWithin,samePath}from"./chunk-pn5ygqn6.js";import{defaultDaemonSocketPath}from"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import{readRoveEnv}from"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import{__commonJS,__require,__toESM}from"./chunk-91sykzqq.js";var require_xterm_headless=__commonJS((exports)=>{(()=>{var e2={5639:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.CircularList=void 0;let i3=s3(7150),r7=s3(802);class n3 extends i3.Disposable{constructor(e4){super(),this._maxLength=e4,this.onDeleteEmitter=this._register(new r7.Emitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new r7.Emitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new r7.Emitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e4){if(this._maxLength===e4)return;let t5=Array(e4);for(let s4=0;s4<Math.min(e4,this.length);s4++)t5[s4]=this._array[this._getCyclicIndex(s4)];this._array=t5,this._maxLength=e4,this._startIndex=0}get length(){return this._length}set length(e4){if(e4>this._length)for(let t5=this._length;t5<e4;t5++)this._array[t5]=void 0;this._length=e4}get(e4){return this._array[this._getCyclicIndex(e4)]}set(e4,t5){this._array[this._getCyclicIndex(e4)]=t5}push(e4){this._array[this._getCyclicIndex(this._length)]=e4,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e4,t5,...s4){if(t5){for(let s5=e4;s5<this._length-t5;s5++)this._array[this._getCyclicIndex(s5)]=this._array[this._getCyclicIndex(s5+t5)];this._length-=t5,this.onDeleteEmitter.fire({index:e4,amount:t5})}for(let t6=this._length-1;t6>=e4;t6--)this._array[this._getCyclicIndex(t6+s4.length)]=this._array[this._getCyclicIndex(t6)];for(let t6=0;t6<s4.length;t6++)this._array[this._getCyclicIndex(e4+t6)]=s4[t6];if(s4.length&&this.onInsertEmitter.fire({index:e4,amount:s4.length}),this._length+s4.length>this._maxLength){let e5=this._length+s4.length-this._maxLength;this._startIndex+=e5,this._length=this._maxLength,this.onTrimEmitter.fire(e5)}else this._length+=s4.length}trimStart(e4){e4>this._length&&(e4=this._length),this._startIndex+=e4,this._length-=e4,this.onTrimEmitter.fire(e4)}shiftElements(e4,t5,s4){if(!(t5<=0)){if(e4<0||e4>=this._length)throw Error("start argument out of range");if(e4+s4<0)throw Error("Cannot shift elements in list beyond index 0");if(s4>0){for(let i5=t5-1;i5>=0;i5--)this.set(e4+i5+s4,this.get(e4+i5));let i4=e4+t5+s4-this._length;if(i4>0)for(this._length+=i4;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let i4=0;i4<t5;i4++)this.set(e4+i4+s4,this.get(e4+i4))}}_getCyclicIndex(e4){return(this._startIndex+e4)%this._maxLength}}t4.CircularList=n3},7453:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.clone=function e4(t5,s3=5){if(typeof t5!="object")return t5;let i3=Array.isArray(t5)?[]:{};for(let r7 in t5)i3[r7]=s3<=1?t5[r7]:t5[r7]&&e4(t5[r7],s3-1);return i3}},5777:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.CoreTerminal=void 0;let i3=s3(6501),r7=s3(6025),n3=s3(7276),o2=s3(9640),a2=s3(56),h2=s3(4071),c2=s3(7792),l2=s3(6415),u2=s3(5746),d2=s3(5882),f2=s3(2486),_4=s3(3562),p3=s3(8811),g3=s3(802),v3=s3(7150),m3=!1;class b3 extends v3.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new g3.Emitter),this._onScroll.event((e4)=>{this._onScrollApi?.fire(e4.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e4){for(let t5 in e4)this.optionsService.options[t5]=e4[t5]}constructor(e4){super(),this._windowsWrappingHeuristics=this._register(new v3.MutableDisposable),this._onBinary=this._register(new g3.Emitter),this.onBinary=this._onBinary.event,this._onData=this._register(new g3.Emitter),this.onData=this._onData.event,this._onLineFeed=this._register(new g3.Emitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new g3.Emitter),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new g3.Emitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new g3.Emitter),this._instantiationService=new r7.InstantiationService,this.optionsService=this._register(new a2.OptionsService(e4)),this._instantiationService.setService(i3.IOptionsService,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(o2.BufferService)),this._instantiationService.setService(i3.IBufferService,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(n3.LogService)),this._instantiationService.setService(i3.ILogService,this._logService),this.coreService=this._register(this._instantiationService.createInstance(h2.CoreService)),this._instantiationService.setService(i3.ICoreService,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(c2.CoreMouseService)),this._instantiationService.setService(i3.ICoreMouseService,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(l2.UnicodeService)),this._instantiationService.setService(i3.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(u2.CharsetService),this._instantiationService.setService(i3.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(p3.OscLinkService),this._instantiationService.setService(i3.IOscLinkService,this._oscLinkService),this._inputHandler=this._register(new f2.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(g3.Event.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(g3.Event.forward(this._bufferService.onResize,this._onResize)),this._register(g3.Event.forward(this.coreService.onData,this._onData)),this._register(g3.Event.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new _4.WriteBuffer((e5,t5)=>this._inputHandler.parse(e5,t5))),this._register(g3.Event.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(e4,t5){this._writeBuffer.write(e4,t5)}writeSync(e4,t5){this._logService.logLevel<=i3.LogLevelEnum.WARN&&!m3&&(this._logService.warn("writeSync is unreliable and will be removed soon."),m3=!0),this._writeBuffer.writeSync(e4,t5)}input(e4,t5=!0){this.coreService.triggerDataEvent(e4,t5)}resize(e4,t5){isNaN(e4)||isNaN(t5)||(e4=Math.max(e4,o2.MINIMUM_COLS),t5=Math.max(t5,o2.MINIMUM_ROWS),this._bufferService.resize(e4,t5))}scroll(e4,t5=!1){this._bufferService.scroll(e4,t5)}scrollLines(e4,t5){this._bufferService.scrollLines(e4,t5)}scrollPages(e4){this.scrollLines(e4*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e4){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e4){let t5=e4-this._bufferService.buffer.ydisp;t5!==0&&this.scrollLines(t5)}registerEscHandler(e4,t5){return this._inputHandler.registerEscHandler(e4,t5)}registerDcsHandler(e4,t5){return this._inputHandler.registerDcsHandler(e4,t5)}registerCsiHandler(e4,t5){return this._inputHandler.registerCsiHandler(e4,t5)}registerOscHandler(e4,t5){return this._inputHandler.registerOscHandler(e4,t5)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e4=!1,t5=this.optionsService.rawOptions.windowsPty;t5&&t5.buildNumber!==void 0&&t5.buildNumber!==void 0?e4=t5.backend==="conpty"&&t5.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e4=!0),e4?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e4=[];e4.push(this.onLineFeed(d2.updateWindowsModeWrappedState.bind(null,this._bufferService))),e4.push(this.registerCsiHandler({final:"H"},()=>((0,d2.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,v3.toDisposable)(()=>{for(let t5 of e4)t5.dispose()})}}}t4.CoreTerminal=b3},2486:function(e3,t4,s3){var i3=this&&this.__decorate||function(e4,t5,s4,i4){var r8,n4=arguments.length,o3=n4<3?t5:i4===null?i4=Object.getOwnPropertyDescriptor(t5,s4):i4;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o3=Reflect.decorate(e4,t5,s4,i4);else for(var a3=e4.length-1;a3>=0;a3--)(r8=e4[a3])&&(o3=(n4<3?r8(o3):n4>3?r8(t5,s4,o3):r8(t5,s4))||o3);return n4>3&&o3&&Object.defineProperty(t5,s4,o3),o3},r7=this&&this.__param||function(e4,t5){return function(s4,i4){t5(s4,i4,e4)}};Object.defineProperty(t4,"__esModule",{value:!0}),t4.InputHandler=t4.WindowsOptionsReportType=void 0,t4.isValidColorIndex=k3;let n3=s3(3534),o2=s3(6760),a2=s3(6717),h2=s3(7150),c2=s3(726),l2=s3(6107),u2=s3(8938),d2=s3(3055),f2=s3(5451),_4=s3(6501),p3=s3(6415),g3=s3(1346),v3=s3(9823),m3=s3(8693),b3=s3(802),S3={"(":0,")":1,"*":2,"+":3,"-":1,".":2},y3=131072;function C3(e4,t5){if(e4>24)return t5.setWinLines||!1;switch(e4){case 1:return!!t5.restoreWin;case 2:return!!t5.minimizeWin;case 3:return!!t5.setWinPosition;case 4:return!!t5.setWinSizePixels;case 5:return!!t5.raiseWin;case 6:return!!t5.lowerWin;case 7:return!!t5.refreshWin;case 8:return!!t5.setWinSizeChars;case 9:return!!t5.maximizeWin;case 10:return!!t5.fullscreenWin;case 11:return!!t5.getWinState;case 13:return!!t5.getWinPosition;case 14:return!!t5.getWinSizePixels;case 15:return!!t5.getScreenSizePixels;case 16:return!!t5.getCellSizePixels;case 18:return!!t5.getWinSizeChars;case 19:return!!t5.getScreenSizeChars;case 20:return!!t5.getIconTitle;case 21:return!!t5.getWinTitle;case 22:return!!t5.pushTitle;case 23:return!!t5.popTitle;case 24:return!!t5.setWinLines}return!1}var w4;(function(e4){e4[e4.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",e4[e4.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(w4||(t4.WindowsOptionsReportType=w4={}));let E3=0;class A4 extends h2.Disposable{getAttrData(){return this._curAttrData}constructor(e4,t5,s4,i4,r8,h3,u3,d3,f3=new a2.EscapeSequenceParser){super(),this._bufferService=e4,this._charsetService=t5,this._coreService=s4,this._logService=i4,this._optionsService=r8,this._oscLinkService=h3,this._coreMouseService=u3,this._unicodeService=d3,this._parser=f3,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new c2.StringToUtf32,this._utf8Decoder=new c2.Utf8ToUtf32,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=l2.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=l2.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this._register(new b3.Emitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new b3.Emitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new b3.Emitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new b3.Emitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new b3.Emitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new b3.Emitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new b3.Emitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new b3.Emitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new b3.Emitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new b3.Emitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new b3.Emitter),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new b3.Emitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new b3.Emitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new L2(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate((e5)=>this._activeBuffer=e5.activeBuffer)),this._parser.setCsiHandlerFallback((e5,t6)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(e5),params:t6.toArray()})}),this._parser.setEscHandlerFallback((e5)=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(e5)})}),this._parser.setExecuteHandlerFallback((e5)=>{this._logService.debug("Unknown EXECUTE code: ",{code:e5})}),this._parser.setOscHandlerFallback((e5,t6,s5)=>{this._logService.debug("Unknown OSC code: ",{identifier:e5,action:t6,data:s5})}),this._parser.setDcsHandlerFallback((e5,t6,s5)=>{t6==="HOOK"&&(s5=s5.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(e5),action:t6,payload:s5})}),this._parser.setPrintHandler((e5,t6,s5)=>this.print(e5,t6,s5)),this._parser.registerCsiHandler({final:"@"},(e5)=>this.insertChars(e5)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(e5)=>this.scrollLeft(e5)),this._parser.registerCsiHandler({final:"A"},(e5)=>this.cursorUp(e5)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(e5)=>this.scrollRight(e5)),this._parser.registerCsiHandler({final:"B"},(e5)=>this.cursorDown(e5)),this._parser.registerCsiHandler({final:"C"},(e5)=>this.cursorForward(e5)),this._parser.registerCsiHandler({final:"D"},(e5)=>this.cursorBackward(e5)),this._parser.registerCsiHandler({final:"E"},(e5)=>this.cursorNextLine(e5)),this._parser.registerCsiHandler({final:"F"},(e5)=>this.cursorPrecedingLine(e5)),this._parser.registerCsiHandler({final:"G"},(e5)=>this.cursorCharAbsolute(e5)),this._parser.registerCsiHandler({final:"H"},(e5)=>this.cursorPosition(e5)),this._parser.registerCsiHandler({final:"I"},(e5)=>this.cursorForwardTab(e5)),this._parser.registerCsiHandler({final:"J"},(e5)=>this.eraseInDisplay(e5,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},(e5)=>this.eraseInDisplay(e5,!0)),this._parser.registerCsiHandler({final:"K"},(e5)=>this.eraseInLine(e5,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},(e5)=>this.eraseInLine(e5,!0)),this._parser.registerCsiHandler({final:"L"},(e5)=>this.insertLines(e5)),this._parser.registerCsiHandler({final:"M"},(e5)=>this.deleteLines(e5)),this._parser.registerCsiHandler({final:"P"},(e5)=>this.deleteChars(e5)),this._parser.registerCsiHandler({final:"S"},(e5)=>this.scrollUp(e5)),this._parser.registerCsiHandler({final:"T"},(e5)=>this.scrollDown(e5)),this._parser.registerCsiHandler({final:"X"},(e5)=>this.eraseChars(e5)),this._parser.registerCsiHandler({final:"Z"},(e5)=>this.cursorBackwardTab(e5)),this._parser.registerCsiHandler({final:"`"},(e5)=>this.charPosAbsolute(e5)),this._parser.registerCsiHandler({final:"a"},(e5)=>this.hPositionRelative(e5)),this._parser.registerCsiHandler({final:"b"},(e5)=>this.repeatPrecedingCharacter(e5)),this._parser.registerCsiHandler({final:"c"},(e5)=>this.sendDeviceAttributesPrimary(e5)),this._parser.registerCsiHandler({prefix:">",final:"c"},(e5)=>this.sendDeviceAttributesSecondary(e5)),this._parser.registerCsiHandler({final:"d"},(e5)=>this.linePosAbsolute(e5)),this._parser.registerCsiHandler({final:"e"},(e5)=>this.vPositionRelative(e5)),this._parser.registerCsiHandler({final:"f"},(e5)=>this.hVPosition(e5)),this._parser.registerCsiHandler({final:"g"},(e5)=>this.tabClear(e5)),this._parser.registerCsiHandler({final:"h"},(e5)=>this.setMode(e5)),this._parser.registerCsiHandler({prefix:"?",final:"h"},(e5)=>this.setModePrivate(e5)),this._parser.registerCsiHandler({final:"l"},(e5)=>this.resetMode(e5)),this._parser.registerCsiHandler({prefix:"?",final:"l"},(e5)=>this.resetModePrivate(e5)),this._parser.registerCsiHandler({final:"m"},(e5)=>this.charAttributes(e5)),this._parser.registerCsiHandler({final:"n"},(e5)=>this.deviceStatus(e5)),this._parser.registerCsiHandler({prefix:"?",final:"n"},(e5)=>this.deviceStatusPrivate(e5)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(e5)=>this.softReset(e5)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(e5)=>this.setCursorStyle(e5)),this._parser.registerCsiHandler({final:"r"},(e5)=>this.setScrollRegion(e5)),this._parser.registerCsiHandler({final:"s"},(e5)=>this.saveCursor(e5)),this._parser.registerCsiHandler({final:"t"},(e5)=>this.windowOptions(e5)),this._parser.registerCsiHandler({final:"u"},(e5)=>this.restoreCursor(e5)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(e5)=>this.insertColumns(e5)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(e5)=>this.deleteColumns(e5)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(e5)=>this.selectProtected(e5)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(e5)=>this.requestMode(e5,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(e5)=>this.requestMode(e5,!1)),this._parser.setExecuteHandler(n3.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(n3.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(n3.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(n3.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(n3.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(n3.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(n3.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(n3.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(n3.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(n3.C1.IND,()=>this.index()),this._parser.setExecuteHandler(n3.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(n3.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new g3.OscHandler((e5)=>(this.setTitle(e5),this.setIconName(e5),!0))),this._parser.registerOscHandler(1,new g3.OscHandler((e5)=>this.setIconName(e5))),this._parser.registerOscHandler(2,new g3.OscHandler((e5)=>this.setTitle(e5))),this._parser.registerOscHandler(4,new g3.OscHandler((e5)=>this.setOrReportIndexedColor(e5))),this._parser.registerOscHandler(8,new g3.OscHandler((e5)=>this.setHyperlink(e5))),this._parser.registerOscHandler(10,new g3.OscHandler((e5)=>this.setOrReportFgColor(e5))),this._parser.registerOscHandler(11,new g3.OscHandler((e5)=>this.setOrReportBgColor(e5))),this._parser.registerOscHandler(12,new g3.OscHandler((e5)=>this.setOrReportCursorColor(e5))),this._parser.registerOscHandler(104,new g3.OscHandler((e5)=>this.restoreIndexedColor(e5))),this._parser.registerOscHandler(110,new g3.OscHandler((e5)=>this.restoreFgColor(e5))),this._parser.registerOscHandler(111,new g3.OscHandler((e5)=>this.restoreBgColor(e5))),this._parser.registerOscHandler(112,new g3.OscHandler((e5)=>this.restoreCursorColor(e5))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let e5 in o2.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:e5},()=>this.selectCharset("("+e5)),this._parser.registerEscHandler({intermediates:")",final:e5},()=>this.selectCharset(")"+e5)),this._parser.registerEscHandler({intermediates:"*",final:e5},()=>this.selectCharset("*"+e5)),this._parser.registerEscHandler({intermediates:"+",final:e5},()=>this.selectCharset("+"+e5)),this._parser.registerEscHandler({intermediates:"-",final:e5},()=>this.selectCharset("-"+e5)),this._parser.registerEscHandler({intermediates:".",final:e5},()=>this.selectCharset("."+e5)),this._parser.registerEscHandler({intermediates:"/",final:e5},()=>this.selectCharset("/"+e5));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler((e5)=>(this._logService.error("Parsing error: ",e5),e5)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new v3.DcsHandler((e5,t6)=>this.requestStatusString(e5,t6)))}_preserveStack(e4,t5,s4,i4){this._parseStack.paused=!0,this._parseStack.cursorStartX=e4,this._parseStack.cursorStartY=t5,this._parseStack.decodedLength=s4,this._parseStack.position=i4}_logSlowResolvingAsync(e4){this._logService.logLevel<=_4.LogLevelEnum.WARN&&Promise.race([e4,new Promise((e5,t5)=>setTimeout(()=>t5("#SLOW_TIMEOUT"),5000))]).catch((e5)=>{if(e5!=="#SLOW_TIMEOUT")throw e5;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e4,t5){let s4,i4=this._activeBuffer.x,r8=this._activeBuffer.y,n4=0,o3=this._parseStack.paused;if(o3){if(s4=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t5))return this._logSlowResolvingAsync(s4),s4;i4=this._parseStack.cursorStartX,r8=this._parseStack.cursorStartY,this._parseStack.paused=!1,e4.length>y3&&(n4=this._parseStack.position+y3)}if(this._logService.logLevel<=_4.LogLevelEnum.DEBUG&&this._logService.debug("parsing data "+(typeof e4=="string"?` "${e4}"`:` "${Array.prototype.map.call(e4,(e5)=>String.fromCharCode(e5)).join("")}"`)),this._logService.logLevel===_4.LogLevelEnum.TRACE&&this._logService.trace("parsing data (codes)",typeof e4=="string"?e4.split("").map((e5)=>e5.charCodeAt(0)):e4),this._parseBuffer.length<e4.length&&this._parseBuffer.length<y3&&(this._parseBuffer=new Uint32Array(Math.min(e4.length,y3))),o3||this._dirtyRowTracker.clearRange(),e4.length>y3)for(let t6=n4;t6<e4.length;t6+=y3){let n5=t6+y3<e4.length?t6+y3:e4.length,o4=typeof e4=="string"?this._stringDecoder.decode(e4.substring(t6,n5),this._parseBuffer):this._utf8Decoder.decode(e4.subarray(t6,n5),this._parseBuffer);if(s4=this._parser.parse(this._parseBuffer,o4))return this._preserveStack(i4,r8,o4,t6),this._logSlowResolvingAsync(s4),s4}else if(!o3){let t6=typeof e4=="string"?this._stringDecoder.decode(e4,this._parseBuffer):this._utf8Decoder.decode(e4,this._parseBuffer);if(s4=this._parser.parse(this._parseBuffer,t6))return this._preserveStack(i4,r8,t6,0),this._logSlowResolvingAsync(s4),s4}this._activeBuffer.x===i4&&this._activeBuffer.y===r8||this._onCursorMove.fire();let a3=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),h3=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);h3<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(h3,this._bufferService.rows-1),end:Math.min(a3,this._bufferService.rows-1)})}print(e4,t5,s4){let i4,r8,n4=this._charsetService.charset,o3=this._optionsService.rawOptions.screenReaderMode,a3=this._bufferService.cols,h3=this._coreService.decPrivateModes.wraparound,d3=this._coreService.modes.insertMode,f3=this._curAttrData,_5=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&s4-t5>0&&_5.getWidth(this._activeBuffer.x-1)===2&&_5.setCellFromCodepoint(this._activeBuffer.x-1,0,1,f3);let g4=this._parser.precedingJoinState;for(let v4=t5;v4<s4;++v4){if(i4=e4[v4],i4<127&&n4){let e5=n4[String.fromCharCode(i4)];e5&&(i4=e5.charCodeAt(0))}let t6=this._unicodeService.charProperties(i4,g4);r8=p3.UnicodeService.extractWidth(t6);let s5=p3.UnicodeService.extractShouldJoin(t6),m4=s5?p3.UnicodeService.extractWidth(g4):0;if(g4=t6,o3&&this._onA11yChar.fire((0,c2.stringFromCodePoint)(i4)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+r8-m4>a3){if(h3){let e5=_5,t7=this._activeBuffer.x-m4;for(this._activeBuffer.x=m4,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),_5=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m4>0&&_5 instanceof l2.BufferLine&&_5.copyCellsFrom(e5,t7,0,m4,!1);t7<a3;)e5.setCellFromCodepoint(t7++,0,1,f3)}else if(this._activeBuffer.x=a3-1,r8===2)continue}if(s5&&this._activeBuffer.x){let e5=_5.getWidth(this._activeBuffer.x-1)?1:2;_5.addCodepointToCell(this._activeBuffer.x-e5,i4,r8);for(let e6=r8-m4;--e6>=0;)_5.setCellFromCodepoint(this._activeBuffer.x++,0,0,f3)}else if(d3&&(_5.insertCells(this._activeBuffer.x,r8-m4,this._activeBuffer.getNullCell(f3)),_5.getWidth(a3-1)===2&&_5.setCellFromCodepoint(a3-1,u2.NULL_CELL_CODE,u2.NULL_CELL_WIDTH,f3)),_5.setCellFromCodepoint(this._activeBuffer.x++,i4,r8,f3),r8>0)for(;--r8;)_5.setCellFromCodepoint(this._activeBuffer.x++,0,0,f3)}this._parser.precedingJoinState=g4,this._activeBuffer.x<a3&&s4-t5>0&&_5.getWidth(this._activeBuffer.x)===0&&!_5.hasContent(this._activeBuffer.x)&&_5.setCellFromCodepoint(this._activeBuffer.x,0,1,f3),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e4,t5){return e4.final!=="t"||e4.prefix||e4.intermediates?this._parser.registerCsiHandler(e4,t5):this._parser.registerCsiHandler(e4,(e5)=>!C3(e5.params[0],this._optionsService.rawOptions.windowOptions)||t5(e5))}registerDcsHandler(e4,t5){return this._parser.registerDcsHandler(e4,new v3.DcsHandler(t5))}registerEscHandler(e4,t5){return this._parser.registerEscHandler(e4,t5)}registerOscHandler(e4,t5){return this._parser.registerOscHandler(e4,new g3.OscHandler(t5))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e4=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e4.hasWidth(this._activeBuffer.x)&&!e4.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e4=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e4),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e4=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e4,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e4,t5){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e4,this._activeBuffer.y=this._activeBuffer.scrollTop+t5):(this._activeBuffer.x=e4,this._activeBuffer.y=t5),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e4,t5){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e4,this._activeBuffer.y+t5)}cursorUp(e4){let t5=this._activeBuffer.y-this._activeBuffer.scrollTop;return t5>=0?this._moveCursor(0,-Math.min(t5,e4.params[0]||1)):this._moveCursor(0,-(e4.params[0]||1)),!0}cursorDown(e4){let t5=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t5>=0?this._moveCursor(0,Math.min(t5,e4.params[0]||1)):this._moveCursor(0,e4.params[0]||1),!0}cursorForward(e4){return this._moveCursor(e4.params[0]||1,0),!0}cursorBackward(e4){return this._moveCursor(-(e4.params[0]||1),0),!0}cursorNextLine(e4){return this.cursorDown(e4),this._activeBuffer.x=0,!0}cursorPrecedingLine(e4){return this.cursorUp(e4),this._activeBuffer.x=0,!0}cursorCharAbsolute(e4){return this._setCursor((e4.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e4){return this._setCursor(e4.length>=2?(e4.params[1]||1)-1:0,(e4.params[0]||1)-1),!0}charPosAbsolute(e4){return this._setCursor((e4.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e4){return this._moveCursor(e4.params[0]||1,0),!0}linePosAbsolute(e4){return this._setCursor(this._activeBuffer.x,(e4.params[0]||1)-1),!0}vPositionRelative(e4){return this._moveCursor(0,e4.params[0]||1),!0}hVPosition(e4){return this.cursorPosition(e4),!0}tabClear(e4){let t5=e4.params[0];return t5===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t5===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e4){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t5=e4.params[0]||1;for(;t5--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e4){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t5=e4.params[0]||1;for(;t5--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e4){let t5=e4.params[0];return t5===1&&(this._curAttrData.bg|=536870912),t5!==2&&t5!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e4,t5,s4,i4=!1,r8=!1){let n4=this._activeBuffer.lines.get(this._activeBuffer.ybase+e4);n4.replaceCells(t5,s4,this._activeBuffer.getNullCell(this._eraseAttrData()),r8),i4&&(n4.isWrapped=!1)}_resetBufferLine(e4,t5=!1){let s4=this._activeBuffer.lines.get(this._activeBuffer.ybase+e4);s4&&(s4.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t5),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e4),s4.isWrapped=!1)}eraseInDisplay(e4,t5=!1){let s4;switch(this._restrictCursor(this._bufferService.cols),e4.params[0]){case 0:for(s4=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s4),this._eraseInBufferLine(s4++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t5);s4<this._bufferService.rows;s4++)this._resetBufferLine(s4,t5);this._dirtyRowTracker.markDirty(s4);break;case 1:for(s4=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s4),this._eraseInBufferLine(s4,0,this._activeBuffer.x+1,!0,t5),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(s4+1).isWrapped=!1);s4--;)this._resetBufferLine(s4,t5);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(s4=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,s4-1);s4--;)if(this._activeBuffer.lines.get(this._activeBuffer.ybase+s4)?.getTrimmedLength())break;for(;s4>=0;s4--)this._bufferService.scroll(this._eraseAttrData())}else{for(s4=this._bufferService.rows,this._dirtyRowTracker.markDirty(s4-1);s4--;)this._resetBufferLine(s4,t5);this._dirtyRowTracker.markDirty(0)}break;case 3:let e5=this._activeBuffer.lines.length-this._bufferService.rows;e5>0&&(this._activeBuffer.lines.trimStart(e5),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e5,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e5,0),this._onScroll.fire(0))}return!0}eraseInLine(e4,t5=!1){switch(this._restrictCursor(this._bufferService.cols),e4.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t5);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t5);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t5)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e4){this._restrictCursor();let t5=e4.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let s4=this._activeBuffer.ybase+this._activeBuffer.y,i4=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r8=this._bufferService.rows-1+this._activeBuffer.ybase-i4+1;for(;t5--;)this._activeBuffer.lines.splice(r8-1,1),this._activeBuffer.lines.splice(s4,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e4){this._restrictCursor();let t5=e4.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let s4=this._activeBuffer.ybase+this._activeBuffer.y,i4;for(i4=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i4=this._bufferService.rows-1+this._activeBuffer.ybase-i4;t5--;)this._activeBuffer.lines.splice(s4,1),this._activeBuffer.lines.splice(i4,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e4){this._restrictCursor();let t5=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t5&&(t5.insertCells(this._activeBuffer.x,e4.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e4){this._restrictCursor();let t5=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t5&&(t5.deleteCells(this._activeBuffer.x,e4.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e4){let t5=e4.params[0]||1;for(;t5--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e4){let t5=e4.params[0]||1;for(;t5--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(l2.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e4){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t5=e4.params[0]||1;for(let e5=this._activeBuffer.scrollTop;e5<=this._activeBuffer.scrollBottom;++e5){let s4=this._activeBuffer.lines.get(this._activeBuffer.ybase+e5);s4.deleteCells(0,t5,this._activeBuffer.getNullCell(this._eraseAttrData())),s4.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e4){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t5=e4.params[0]||1;for(let e5=this._activeBuffer.scrollTop;e5<=this._activeBuffer.scrollBottom;++e5){let s4=this._activeBuffer.lines.get(this._activeBuffer.ybase+e5);s4.insertCells(0,t5,this._activeBuffer.getNullCell(this._eraseAttrData())),s4.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e4){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t5=e4.params[0]||1;for(let e5=this._activeBuffer.scrollTop;e5<=this._activeBuffer.scrollBottom;++e5){let s4=this._activeBuffer.lines.get(this._activeBuffer.ybase+e5);s4.insertCells(this._activeBuffer.x,t5,this._activeBuffer.getNullCell(this._eraseAttrData())),s4.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e4){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t5=e4.params[0]||1;for(let e5=this._activeBuffer.scrollTop;e5<=this._activeBuffer.scrollBottom;++e5){let s4=this._activeBuffer.lines.get(this._activeBuffer.ybase+e5);s4.deleteCells(this._activeBuffer.x,t5,this._activeBuffer.getNullCell(this._eraseAttrData())),s4.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e4){this._restrictCursor();let t5=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t5&&(t5.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e4.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e4){let t5=this._parser.precedingJoinState;if(!t5)return!0;let s4=e4.params[0]||1,i4=p3.UnicodeService.extractWidth(t5),r8=this._activeBuffer.x-i4,n4=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(r8),o3=new Uint32Array(n4.length*s4),a3=0;for(let e5=0;e5<n4.length;){let t6=n4.codePointAt(e5)||0;o3[a3++]=t6,e5+=t6>65535?2:1}let h3=a3;for(let e5=1;e5<s4;++e5)o3.copyWithin(h3,0,a3),h3+=a3;return this.print(o3,0,h3),!0}sendDeviceAttributesPrimary(e4){return e4.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(n3.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(n3.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e4){return e4.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(n3.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(n3.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e4.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(n3.C0.ESC+"[>83;40003;0c")),!0}_is(e4){return(this._optionsService.rawOptions.termName+"").indexOf(e4)===0}setMode(e4){for(let t5=0;t5<e4.length;t5++)switch(e4.params[t5]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e4){for(let t5=0;t5<e4.length;t5++)switch(e4.params[t5]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,o2.DEFAULT_CHARSET),this._charsetService.setgCharset(1,o2.DEFAULT_CHARSET),this._charsetService.setgCharset(2,o2.DEFAULT_CHARSET),this._charsetService.setgCharset(3,o2.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1000:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e4){for(let t5=0;t5<e4.length;t5++)switch(e4.params[t5]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e4){for(let t5=0;t5<e4.length;t5++)switch(e4.params[t5]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1000:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e4.params[t5]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e4,t5){let s4=this._coreService.decPrivateModes,{activeProtocol:i4,activeEncoding:r8}=this._coreMouseService,o3=this._coreService,{buffers:a3,cols:h3}=this._bufferService,{active:c3,alt:l3}=a3,u3=this._optionsService.rawOptions,d3=(e5)=>e5?1:2,f3=e4.params[0];return _5=f3,p4=t5?f3===2?4:f3===4?d3(o3.modes.insertMode):f3===12?3:f3===20?d3(u3.convertEol):0:f3===1?d3(s4.applicationCursorKeys):f3===3?u3.windowOptions.setWinLines?h3===80?2:h3===132?1:0:0:f3===6?d3(s4.origin):f3===7?d3(s4.wraparound):f3===8?3:f3===9?d3(i4==="X10"):f3===12?d3(u3.cursorBlink):f3===25?d3(!o3.isCursorHidden):f3===45?d3(s4.reverseWraparound):f3===66?d3(s4.applicationKeypad):f3===67?4:f3===1000?d3(i4==="VT200"):f3===1002?d3(i4==="DRAG"):f3===1003?d3(i4==="ANY"):f3===1004?d3(s4.sendFocus):f3===1005?4:f3===1006?d3(r8==="SGR"):f3===1015?4:f3===1016?d3(r8==="SGR_PIXELS"):f3===1048?1:f3===47||f3===1047||f3===1049?d3(c3===l3):f3===2004?d3(s4.bracketedPasteMode):f3===2026?d3(s4.synchronizedOutput):0,o3.triggerDataEvent(`${n3.C0.ESC}[${t5?"":"?"}${_5};${p4}$y`),!0;var _5,p4}_updateAttrColor(e4,t5,s4,i4,r8){return t5===2?(e4|=50331648,e4&=-16777216,e4|=f2.AttributeData.fromColorRGB([s4,i4,r8])):t5===5&&(e4&=-50331904,e4|=33554432|255&s4),e4}_extractColor(e4,t5,s4){let i4=[0,0,-1,0,0,0],r8=0,n4=0;do{if(i4[n4+r8]=e4.params[t5+n4],e4.hasSubParams(t5+n4)){let s5=e4.getSubParams(t5+n4),o3=0;do i4[1]===5&&(r8=1),i4[n4+o3+1+r8]=s5[o3];while(++o3<s5.length&&o3+n4+1+r8<i4.length);break}if(i4[1]===5&&n4+r8>=2||i4[1]===2&&n4+r8>=5)break;i4[1]&&(r8=1)}while(++n4+t5<e4.length&&n4+r8<i4.length);for(let e5=2;e5<i4.length;++e5)i4[e5]===-1&&(i4[e5]=0);switch(i4[0]){case 38:s4.fg=this._updateAttrColor(s4.fg,i4[1],i4[3],i4[4],i4[5]);break;case 48:s4.bg=this._updateAttrColor(s4.bg,i4[1],i4[3],i4[4],i4[5]);break;case 58:s4.extended=s4.extended.clone(),s4.extended.underlineColor=this._updateAttrColor(s4.extended.underlineColor,i4[1],i4[3],i4[4],i4[5])}return n4}_processUnderline(e4,t5){t5.extended=t5.extended.clone(),(!~e4||e4>5)&&(e4=1),t5.extended.underlineStyle=e4,t5.fg|=268435456,e4===0&&(t5.fg&=-268435457),t5.updateExtended()}_processSGR0(e4){e4.fg=l2.DEFAULT_ATTR_DATA.fg,e4.bg=l2.DEFAULT_ATTR_DATA.bg,e4.extended=e4.extended.clone(),e4.extended.underlineStyle=0,e4.extended.underlineColor&=-67108864,e4.updateExtended()}charAttributes(e4){if(e4.length===1&&e4.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t5=e4.length,s4,i4=this._curAttrData;for(let r8=0;r8<t5;r8++)s4=e4.params[r8],s4>=30&&s4<=37?(i4.fg&=-50331904,i4.fg|=16777216|s4-30):s4>=40&&s4<=47?(i4.bg&=-50331904,i4.bg|=16777216|s4-40):s4>=90&&s4<=97?(i4.fg&=-50331904,i4.fg|=16777224|s4-90):s4>=100&&s4<=107?(i4.bg&=-50331904,i4.bg|=16777224|s4-100):s4===0?this._processSGR0(i4):s4===1?i4.fg|=134217728:s4===3?i4.bg|=67108864:s4===4?(i4.fg|=268435456,this._processUnderline(e4.hasSubParams(r8)?e4.getSubParams(r8)[0]:1,i4)):s4===5?i4.fg|=536870912:s4===7?i4.fg|=67108864:s4===8?i4.fg|=1073741824:s4===9?i4.fg|=2147483648:s4===2?i4.bg|=134217728:s4===21?this._processUnderline(2,i4):s4===22?(i4.fg&=-134217729,i4.bg&=-134217729):s4===23?i4.bg&=-67108865:s4===24?(i4.fg&=-268435457,this._processUnderline(0,i4)):s4===25?i4.fg&=-536870913:s4===27?i4.fg&=-67108865:s4===28?i4.fg&=-1073741825:s4===29?i4.fg&=2147483647:s4===39?(i4.fg&=-67108864,i4.fg|=16777215&l2.DEFAULT_ATTR_DATA.fg):s4===49?(i4.bg&=-67108864,i4.bg|=16777215&l2.DEFAULT_ATTR_DATA.bg):s4===38||s4===48||s4===58?r8+=this._extractColor(e4,r8,i4):s4===53?i4.bg|=1073741824:s4===55?i4.bg&=-1073741825:s4===59?(i4.extended=i4.extended.clone(),i4.extended.underlineColor=-1,i4.updateExtended()):s4===100?(i4.fg&=-67108864,i4.fg|=16777215&l2.DEFAULT_ATTR_DATA.fg,i4.bg&=-67108864,i4.bg|=16777215&l2.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",s4);return!0}deviceStatus(e4){switch(e4.params[0]){case 5:this._coreService.triggerDataEvent(`${n3.C0.ESC}[0n`);break;case 6:let e5=this._activeBuffer.y+1,t5=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n3.C0.ESC}[${e5};${t5}R`)}return!0}deviceStatusPrivate(e4){if(e4.params[0]===6){let e5=this._activeBuffer.y+1,t5=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n3.C0.ESC}[?${e5};${t5}R`)}return!0}softReset(e4){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=l2.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e4){let t5=e4.length===0?1:e4.params[0];if(t5===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t5){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar"}let e5=t5%2==1;this._coreService.decPrivateModes.cursorBlink=e5}return!0}setScrollRegion(e4){let t5=e4.params[0]||1,s4;return(e4.length<2||(s4=e4.params[1])>this._bufferService.rows||s4===0)&&(s4=this._bufferService.rows),s4>t5&&(this._activeBuffer.scrollTop=t5-1,this._activeBuffer.scrollBottom=s4-1,this._setCursor(0,0)),!0}windowOptions(e4){if(!C3(e4.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t5=e4.length>1?e4.params[1]:0;switch(e4.params[0]){case 14:t5!==2&&this._onRequestWindowsOptionsReport.fire(w4.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(w4.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${n3.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:t5!==0&&t5!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),t5!==0&&t5!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:t5!==0&&t5!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),t5!==0&&t5!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e4){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e4){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e4){return this._windowTitle=e4,this._onTitleChange.fire(e4),!0}setIconName(e4){return this._iconName=e4,!0}setOrReportIndexedColor(e4){let t5=[],s4=e4.split(";");for(;s4.length>1;){let e5=s4.shift(),i4=s4.shift();if(/^\d+$/.exec(e5)){let s5=parseInt(e5);if(k3(s5))if(i4==="?")t5.push({type:0,index:s5});else{let e6=(0,m3.parseColor)(i4);e6&&t5.push({type:1,index:s5,color:e6})}}}return t5.length&&this._onColor.fire(t5),!0}setHyperlink(e4){let t5=e4.indexOf(";");if(t5===-1)return!0;let s4=e4.slice(0,t5).trim(),i4=e4.slice(t5+1);return i4?this._createHyperlink(s4,i4):!s4.trim()&&this._finishHyperlink()}_createHyperlink(e4,t5){this._getCurrentLinkId()&&this._finishHyperlink();let s4=e4.split(":"),i4,r8=s4.findIndex((e5)=>e5.startsWith("id="));return r8!==-1&&(i4=s4[r8].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:i4,uri:t5}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e4,t5){let s4=e4.split(";");for(let e5=0;e5<s4.length&&!(t5>=this._specialColors.length);++e5,++t5)if(s4[e5]==="?")this._onColor.fire([{type:0,index:this._specialColors[t5]}]);else{let i4=(0,m3.parseColor)(s4[e5]);i4&&this._onColor.fire([{type:1,index:this._specialColors[t5],color:i4}])}return!0}setOrReportFgColor(e4){return this._setOrReportSpecialColor(e4,0)}setOrReportBgColor(e4){return this._setOrReportSpecialColor(e4,1)}setOrReportCursorColor(e4){return this._setOrReportSpecialColor(e4,2)}restoreIndexedColor(e4){if(!e4)return this._onColor.fire([{type:2}]),!0;let t5=[],s4=e4.split(";");for(let e5=0;e5<s4.length;++e5)if(/^\d+$/.exec(s4[e5])){let i4=parseInt(s4[e5]);k3(i4)&&t5.push({type:2,index:i4})}return t5.length&&this._onColor.fire(t5),!0}restoreFgColor(e4){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e4){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e4){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,o2.DEFAULT_CHARSET),!0}selectCharset(e4){return e4.length!==2?(this.selectDefaultCharset(),!0):(e4[0]==="/"||this._charsetService.setgCharset(S3[e4[0]],o2.CHARSETS[e4[1]]||o2.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e4=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e4,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=l2.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=l2.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e4){return this._charsetService.setgLevel(e4),!0}screenAlignmentPattern(){let e4=new d2.CellData;e4.content=4194373,e4.fg=this._curAttrData.fg,e4.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t5=0;t5<this._bufferService.rows;++t5){let s4=this._activeBuffer.ybase+this._activeBuffer.y+t5,i4=this._activeBuffer.lines.get(s4);i4&&(i4.fill(e4),i4.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e4,t5){let s4=this._bufferService.buffer,i4=this._optionsService.rawOptions;return((e5)=>(this._coreService.triggerDataEvent(`${n3.C0.ESC}${e5}${n3.C0.ESC}\\`),!0))(e4==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e4==='"p'?'P1$r61;1"p':e4==="r"?`P1$r${s4.scrollTop+1};${s4.scrollBottom+1}r`:e4==="m"?"P1$r0m":e4===" q"?`P1$r${{block:2,underline:4,bar:6}[i4.cursorStyle]-(i4.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e4,t5){this._dirtyRowTracker.markRangeDirty(e4,t5)}}t4.InputHandler=A4;let L2=class{constructor(e4){this._bufferService=e4,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e4){e4<this.start?this.start=e4:e4>this.end&&(this.end=e4)}markRangeDirty(e4,t5){e4>t5&&(E3=e4,e4=t5,t5=E3),e4<this.start&&(this.start=e4),t5>this.end&&(this.end=t5)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function k3(e4){return 0<=e4&&e4<256}L2=i3([r7(0,_4.IBufferService)],L2)},701:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.isChromeOS=t4.isLinux=t4.isWindows=t4.isIphone=t4.isIpad=t4.isMac=t4.isSafari=t4.isLegacyEdge=t4.isFirefox=t4.isNode=void 0,t4.getSafariVersion=function(){if(!t4.isSafari)return 0;let e4=s3.match(/Version\/(\d+)/);return e4===null||e4.length<2?0:parseInt(e4[1])},t4.isNode=typeof process<"u"&&"title"in process;let s3=t4.isNode?"node":navigator.userAgent,i3=t4.isNode?"node":navigator.platform;t4.isFirefox=s3.includes("Firefox"),t4.isLegacyEdge=s3.includes("Edge"),t4.isSafari=/^((?!chrome|android).)*safari/i.test(s3),t4.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(i3),t4.isIpad=i3==="iPad",t4.isIphone=i3==="iPhone",t4.isWindows=["Windows","Win16","Win32","WinCE"].includes(i3),t4.isLinux=i3.indexOf("Linux")>=0,t4.isChromeOS=/\bCrOS\b/.test(s3)},6168:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.DebouncedIdleTask=t4.IdleTaskQueue=t4.PriorityTaskQueue=void 0;let i3=s3(701);class r7{constructor(){this._tasks=[],this._i=0}enqueue(e4){this._tasks.push(e4),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(e4){this._idleCallback=void 0;let t5=0,s4=0,i4=e4.timeRemaining(),r8=0;for(;this._i<this._tasks.length;){if(t5=performance.now(),this._tasks[this._i]()||this._i++,t5=Math.max(1,performance.now()-t5),s4=Math.max(t5,s4),r8=e4.timeRemaining(),1.5*s4>r8)return i4-t5<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(i4-t5))}ms`),void this._start();i4=r8}this.clear()}}class n3 extends r7{_requestCallback(e4){return setTimeout(()=>e4(this._createDeadline(16)))}_cancelCallback(e4){clearTimeout(e4)}_createDeadline(e4){let t5=performance.now()+e4;return{timeRemaining:()=>Math.max(0,t5-performance.now())}}}t4.PriorityTaskQueue=n3,t4.IdleTaskQueue=!i3.isNode&&"requestIdleCallback"in window?class extends r7{_requestCallback(e4){return requestIdleCallback(e4)}_cancelCallback(e4){cancelIdleCallback(e4)}}:n3,t4.DebouncedIdleTask=class{constructor(){this._queue=new t4.IdleTaskQueue}set(e4){this._queue.clear(),this._queue.enqueue(e4)}flush(){this._queue.flush()}}},5882:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.updateWindowsModeWrappedState=function(e4){let t5=e4.buffer.lines.get(e4.buffer.ybase+e4.buffer.y-1),s4=t5?.get(e4.cols-1),r7=e4.buffer.lines.get(e4.buffer.ybase+e4.buffer.y);r7&&s4&&(r7.isWrapped=s4[i3.CHAR_DATA_CODE_INDEX]!==i3.NULL_CELL_CODE&&s4[i3.CHAR_DATA_CODE_INDEX]!==i3.WHITESPACE_CELL_CODE)};let i3=s3(8938)},5451:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.ExtendedAttrs=t4.AttributeData=void 0;class s3{constructor(){this.fg=0,this.bg=0,this.extended=new i3}static toColorRGB(e4){return[e4>>>16&255,e4>>>8&255,255&e4]}static fromColorRGB(e4){return(255&e4[0])<<16|(255&e4[1])<<8|255&e4[2]}clone(){let e4=new s3;return e4.fg=this.fg,e4.bg=this.bg,e4.extended=this.extended.clone(),e4}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}t4.AttributeData=s3;class i3{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e4){this._ext=e4}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e4){this._ext&=-469762049,this._ext|=e4<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e4){this._ext&=-67108864,this._ext|=67108863&e4}get urlId(){return this._urlId}set urlId(e4){this._urlId=e4}get underlineVariantOffset(){let e4=(3758096384&this._ext)>>29;return e4<0?4294967288^e4:e4}set underlineVariantOffset(e4){this._ext&=536870911,this._ext|=e4<<29&3758096384}constructor(e4=0,t5=0){this._ext=0,this._urlId=0,this._ext=e4,this._urlId=t5}clone(){return new i3(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}t4.ExtendedAttrs=i3},1073:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.Buffer=t4.MAX_BUFFER_SIZE=void 0;let i3=s3(5639),r7=s3(6168),n3=s3(5451),o2=s3(6107),a2=s3(732),h2=s3(3055),c2=s3(8938),l2=s3(8158),u2=s3(6760);t4.MAX_BUFFER_SIZE=4294967295,t4.Buffer=class{constructor(e4,t5,s4){this._hasScrollback=e4,this._optionsService=t5,this._bufferService=s4,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=o2.DEFAULT_ATTR_DATA.clone(),this.savedCharset=u2.DEFAULT_CHARSET,this.markers=[],this._nullCell=h2.CellData.fromCharData([0,c2.NULL_CELL_CHAR,c2.NULL_CELL_WIDTH,c2.NULL_CELL_CODE]),this._whitespaceCell=h2.CellData.fromCharData([0,c2.WHITESPACE_CELL_CHAR,c2.WHITESPACE_CELL_WIDTH,c2.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new r7.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new i3.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e4){return e4?(this._nullCell.fg=e4.fg,this._nullCell.bg=e4.bg,this._nullCell.extended=e4.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new n3.ExtendedAttrs),this._nullCell}getWhitespaceCell(e4){return e4?(this._whitespaceCell.fg=e4.fg,this._whitespaceCell.bg=e4.bg,this._whitespaceCell.extended=e4.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new n3.ExtendedAttrs),this._whitespaceCell}getBlankLine(e4,t5){return new o2.BufferLine(this._bufferService.cols,this.getNullCell(e4),t5)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e4=this.ybase+this.y-this.ydisp;return e4>=0&&e4<this._rows}_getCorrectBufferLength(e4){if(!this._hasScrollback)return e4;let s4=e4+this._optionsService.rawOptions.scrollback;return s4>t4.MAX_BUFFER_SIZE?t4.MAX_BUFFER_SIZE:s4}fillViewportRows(e4){if(this.lines.length===0){e4===void 0&&(e4=o2.DEFAULT_ATTR_DATA);let t5=this._rows;for(;t5--;)this.lines.push(this.getBlankLine(e4))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new i3.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e4,t5){let s4=this.getNullCell(o2.DEFAULT_ATTR_DATA),i4=0,r8=this._getCorrectBufferLength(t5);if(r8>this.lines.maxLength&&(this.lines.maxLength=r8),this.lines.length>0){if(this._cols<e4)for(let t6=0;t6<this.lines.length;t6++)i4+=+this.lines.get(t6).resize(e4,s4);let n4=0;if(this._rows<t5)for(let i5=this._rows;i5<t5;i5++)this.lines.length<t5+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new o2.BufferLine(e4,s4)):this.ybase>0&&this.lines.length<=this.ybase+this.y+n4+1?(this.ybase--,n4++,this.ydisp>0&&this.ydisp--):this.lines.push(new o2.BufferLine(e4,s4)));else for(let e5=this._rows;e5>t5;e5--)this.lines.length>t5+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r8<this.lines.maxLength){let e5=this.lines.length-r8;e5>0&&(this.lines.trimStart(e5),this.ybase=Math.max(this.ybase-e5,0),this.ydisp=Math.max(this.ydisp-e5,0),this.savedY=Math.max(this.savedY-e5,0)),this.lines.maxLength=r8}this.x=Math.min(this.x,e4-1),this.y=Math.min(this.y,t5-1),n4&&(this.y+=n4),this.savedX=Math.min(this.savedX,e4-1),this.scrollTop=0}if(this.scrollBottom=t5-1,this._isReflowEnabled&&(this._reflow(e4,t5),this._cols>e4))for(let t6=0;t6<this.lines.length;t6++)i4+=+this.lines.get(t6).resize(e4,s4);this._cols=e4,this._rows=t5,this._memoryCleanupQueue.clear(),i4>0.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e4=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e4=!1);let t5=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t5+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t5>100)return!0;return e4}get _isReflowEnabled(){let e4=this._optionsService.rawOptions.windowsPty;return e4&&e4.buildNumber?this._hasScrollback&&e4.backend==="conpty"&&e4.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e4,t5){this._cols!==e4&&(e4>this._cols?this._reflowLarger(e4,t5):this._reflowSmaller(e4,t5))}_reflowLarger(e4,t5){let s4=this._optionsService.rawOptions.reflowCursorLine,i4=(0,a2.reflowLargerGetLinesToRemove)(this.lines,this._cols,e4,this.ybase+this.y,this.getNullCell(o2.DEFAULT_ATTR_DATA),s4);if(i4.length>0){let s5=(0,a2.reflowLargerCreateNewLayout)(this.lines,i4);(0,a2.reflowLargerApplyNewLayout)(this.lines,s5.layout),this._reflowLargerAdjustViewport(e4,t5,s5.countRemoved)}}_reflowLargerAdjustViewport(e4,t5,s4){let i4=this.getNullCell(o2.DEFAULT_ATTR_DATA),r8=s4;for(;r8-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t5&&this.lines.push(new o2.BufferLine(e4,i4))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-s4,0)}_reflowSmaller(e4,t5){let s4=this._optionsService.rawOptions.reflowCursorLine,i4=this.getNullCell(o2.DEFAULT_ATTR_DATA),r8=[],n4=0;for(let h3=this.lines.length-1;h3>=0;h3--){let c3=this.lines.get(h3);if(!c3||!c3.isWrapped&&c3.getTrimmedLength()<=e4)continue;let l3=[c3];for(;c3.isWrapped&&h3>0;)c3=this.lines.get(--h3),l3.unshift(c3);if(!s4){let e5=this.ybase+this.y;if(e5>=h3&&e5<h3+l3.length)continue}let u3=l3[l3.length-1].getTrimmedLength(),d2=(0,a2.reflowSmallerGetNewLineLengths)(l3,this._cols,e4),f2=d2.length-l3.length,_4;_4=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+f2):Math.max(0,this.lines.length-this.lines.maxLength+f2);let p3=[];for(let e5=0;e5<f2;e5++){let e6=this.getBlankLine(o2.DEFAULT_ATTR_DATA,!0);p3.push(e6)}p3.length>0&&(r8.push({start:h3+l3.length+n4,newLines:p3}),n4+=p3.length),l3.push(...p3);let g3=d2.length-1,v3=d2[g3];v3===0&&(g3--,v3=d2[g3]);let m3=l3.length-f2-1,b3=u3;for(;m3>=0;){let e5=Math.min(b3,v3);if(l3[g3]===void 0)break;if(l3[g3].copyCellsFrom(l3[m3],b3-e5,v3-e5,e5,!0),v3-=e5,v3===0&&(g3--,v3=d2[g3]),b3-=e5,b3===0){m3--;let e6=Math.max(m3,0);b3=(0,a2.getWrappedLineTrimmedLength)(l3,e6,this._cols)}}for(let t6=0;t6<l3.length;t6++)d2[t6]<e4&&l3[t6].setCell(d2[t6],i4);let S3=f2-_4;for(;S3-- >0;)this.ybase===0?this.y<t5-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+n4)-t5&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+f2,this.ybase+t5-1)}if(r8.length>0){let e5=[],t6=[];for(let e6=0;e6<this.lines.length;e6++)t6.push(this.lines.get(e6));let s5=this.lines.length,i5=s5-1,o3=0,a3=r8[o3];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+n4);let h3=0;for(let c4=Math.min(this.lines.maxLength-1,s5+n4-1);c4>=0;c4--)if(a3&&a3.start>i5+h3){for(let e6=a3.newLines.length-1;e6>=0;e6--)this.lines.set(c4--,a3.newLines[e6]);c4++,e5.push({index:i5+1,amount:a3.newLines.length}),h3+=a3.newLines.length,a3=r8[++o3]}else this.lines.set(c4,t6[i5--]);let c3=0;for(let t7=e5.length-1;t7>=0;t7--)e5[t7].index+=c3,this.lines.onInsertEmitter.fire(e5[t7]),c3+=e5[t7].amount;let l3=Math.max(0,s5+n4-this.lines.maxLength);l3>0&&this.lines.onTrimEmitter.fire(l3)}}translateBufferLineToString(e4,t5,s4=0,i4){let r8=this.lines.get(e4);return r8?r8.translateToString(t5,s4,i4):""}getWrappedRangeForLine(e4){let t5=e4,s4=e4;for(;t5>0&&this.lines.get(t5).isWrapped;)t5--;for(;s4+1<this.lines.length&&this.lines.get(s4+1).isWrapped;)s4++;return{first:t5,last:s4}}setupTabStops(e4){for(e4!=null?this.tabs[e4]||(e4=this.prevStop(e4)):(this.tabs={},e4=0);e4<this._cols;e4+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e4]=!0}prevStop(e4){for(e4==null&&(e4=this.x);!this.tabs[--e4]&&e4>0;);return e4>=this._cols?this._cols-1:e4<0?0:e4}nextStop(e4){for(e4==null&&(e4=this.x);!this.tabs[++e4]&&e4<this._cols;);return e4>=this._cols?this._cols-1:e4<0?0:e4}clearMarkers(e4){this._isClearing=!0;for(let t5=0;t5<this.markers.length;t5++)this.markers[t5].line===e4&&(this.markers[t5].dispose(),this.markers.splice(t5--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e4=0;e4<this.markers.length;e4++)this.markers[e4].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e4){let t5=new l2.Marker(e4);return this.markers.push(t5),t5.register(this.lines.onTrim((e5)=>{t5.line-=e5,t5.line<0&&t5.dispose()})),t5.register(this.lines.onInsert((e5)=>{t5.line>=e5.index&&(t5.line+=e5.amount)})),t5.register(this.lines.onDelete((e5)=>{t5.line>=e5.index&&t5.line<e5.index+e5.amount&&t5.dispose(),t5.line>e5.index&&(t5.line-=e5.amount)})),t5.register(t5.onDispose(()=>this._removeMarker(t5))),t5}_removeMarker(e4){this._isClearing||this.markers.splice(this.markers.indexOf(e4),1)}}},6107:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.BufferLine=t4.DEFAULT_ATTR_DATA=void 0;let i3=s3(5451),r7=s3(3055),n3=s3(8938),o2=s3(726);t4.DEFAULT_ATTR_DATA=Object.freeze(new i3.AttributeData);let a2=0;class h2{constructor(e4,t5,s4=!1){this.isWrapped=s4,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e4);let i4=t5||r7.CellData.fromCharData([0,n3.NULL_CELL_CHAR,n3.NULL_CELL_WIDTH,n3.NULL_CELL_CODE]);for(let t6=0;t6<e4;++t6)this.setCell(t6,i4);this.length=e4}get(e4){let t5=this._data[3*e4+0],s4=2097151&t5;return[this._data[3*e4+1],2097152&t5?this._combined[e4]:s4?(0,o2.stringFromCodePoint)(s4):"",t5>>22,2097152&t5?this._combined[e4].charCodeAt(this._combined[e4].length-1):s4]}set(e4,t5){this._data[3*e4+1]=t5[n3.CHAR_DATA_ATTR_INDEX],t5[n3.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e4]=t5[1],this._data[3*e4+0]=2097152|e4|t5[n3.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*e4+0]=t5[n3.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t5[n3.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(e4){return this._data[3*e4+0]>>22}hasWidth(e4){return 12582912&this._data[3*e4+0]}getFg(e4){return this._data[3*e4+1]}getBg(e4){return this._data[3*e4+2]}hasContent(e4){return 4194303&this._data[3*e4+0]}getCodePoint(e4){let t5=this._data[3*e4+0];return 2097152&t5?this._combined[e4].charCodeAt(this._combined[e4].length-1):2097151&t5}isCombined(e4){return 2097152&this._data[3*e4+0]}getString(e4){let t5=this._data[3*e4+0];return 2097152&t5?this._combined[e4]:2097151&t5?(0,o2.stringFromCodePoint)(2097151&t5):""}isProtected(e4){return 536870912&this._data[3*e4+2]}loadCell(e4,t5){return a2=3*e4,t5.content=this._data[a2+0],t5.fg=this._data[a2+1],t5.bg=this._data[a2+2],2097152&t5.content&&(t5.combinedData=this._combined[e4]),268435456&t5.bg&&(t5.extended=this._extendedAttrs[e4]),t5}setCell(e4,t5){2097152&t5.content&&(this._combined[e4]=t5.combinedData),268435456&t5.bg&&(this._extendedAttrs[e4]=t5.extended),this._data[3*e4+0]=t5.content,this._data[3*e4+1]=t5.fg,this._data[3*e4+2]=t5.bg}setCellFromCodepoint(e4,t5,s4,i4){268435456&i4.bg&&(this._extendedAttrs[e4]=i4.extended),this._data[3*e4+0]=t5|s4<<22,this._data[3*e4+1]=i4.fg,this._data[3*e4+2]=i4.bg}addCodepointToCell(e4,t5,s4){let i4=this._data[3*e4+0];2097152&i4?this._combined[e4]+=(0,o2.stringFromCodePoint)(t5):2097151&i4?(this._combined[e4]=(0,o2.stringFromCodePoint)(2097151&i4)+(0,o2.stringFromCodePoint)(t5),i4&=-2097152,i4|=2097152):i4=t5|4194304,s4&&(i4&=-12582913,i4|=s4<<22),this._data[3*e4+0]=i4}insertCells(e4,t5,s4){if((e4%=this.length)&&this.getWidth(e4-1)===2&&this.setCellFromCodepoint(e4-1,0,1,s4),t5<this.length-e4){let i4=new r7.CellData;for(let s5=this.length-e4-t5-1;s5>=0;--s5)this.setCell(e4+t5+s5,this.loadCell(e4+s5,i4));for(let i5=0;i5<t5;++i5)this.setCell(e4+i5,s4)}else for(let t6=e4;t6<this.length;++t6)this.setCell(t6,s4);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,s4)}deleteCells(e4,t5,s4){if(e4%=this.length,t5<this.length-e4){let i4=new r7.CellData;for(let s5=0;s5<this.length-e4-t5;++s5)this.setCell(e4+s5,this.loadCell(e4+t5+s5,i4));for(let e5=this.length-t5;e5<this.length;++e5)this.setCell(e5,s4)}else for(let t6=e4;t6<this.length;++t6)this.setCell(t6,s4);e4&&this.getWidth(e4-1)===2&&this.setCellFromCodepoint(e4-1,0,1,s4),this.getWidth(e4)!==0||this.hasContent(e4)||this.setCellFromCodepoint(e4,0,1,s4)}replaceCells(e4,t5,s4,i4=!1){if(i4)for(e4&&this.getWidth(e4-1)===2&&!this.isProtected(e4-1)&&this.setCellFromCodepoint(e4-1,0,1,s4),t5<this.length&&this.getWidth(t5-1)===2&&!this.isProtected(t5)&&this.setCellFromCodepoint(t5,0,1,s4);e4<t5&&e4<this.length;)this.isProtected(e4)||this.setCell(e4,s4),e4++;else for(e4&&this.getWidth(e4-1)===2&&this.setCellFromCodepoint(e4-1,0,1,s4),t5<this.length&&this.getWidth(t5-1)===2&&this.setCellFromCodepoint(t5,0,1,s4);e4<t5&&e4<this.length;)this.setCell(e4++,s4)}resize(e4,t5){if(e4===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let s4=3*e4;if(e4>this.length){if(this._data.buffer.byteLength>=4*s4)this._data=new Uint32Array(this._data.buffer,0,s4);else{let e5=new Uint32Array(s4);e5.set(this._data),this._data=e5}for(let s5=this.length;s5<e4;++s5)this.setCell(s5,t5)}else{this._data=this._data.subarray(0,s4);let t6=Object.keys(this._combined);for(let s5=0;s5<t6.length;s5++){let i5=parseInt(t6[s5],10);i5>=e4&&delete this._combined[i5]}let i4=Object.keys(this._extendedAttrs);for(let t7=0;t7<i4.length;t7++){let s5=parseInt(i4[t7],10);s5>=e4&&delete this._extendedAttrs[s5]}}return this.length=e4,4*s4*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let e4=new Uint32Array(this._data.length);return e4.set(this._data),this._data=e4,1}return 0}fill(e4,t5=!1){if(t5)for(let t6=0;t6<this.length;++t6)this.isProtected(t6)||this.setCell(t6,e4);else{this._combined={},this._extendedAttrs={};for(let t6=0;t6<this.length;++t6)this.setCell(t6,e4)}}copyFrom(e4){this.length!==e4.length?this._data=new Uint32Array(e4._data):this._data.set(e4._data),this.length=e4.length,this._combined={};for(let t5 in e4._combined)this._combined[t5]=e4._combined[t5];this._extendedAttrs={};for(let t5 in e4._extendedAttrs)this._extendedAttrs[t5]=e4._extendedAttrs[t5];this.isWrapped=e4.isWrapped}clone(){let e4=new h2(0);e4._data=new Uint32Array(this._data),e4.length=this.length;for(let t5 in this._combined)e4._combined[t5]=this._combined[t5];for(let t5 in this._extendedAttrs)e4._extendedAttrs[t5]=this._extendedAttrs[t5];return e4.isWrapped=this.isWrapped,e4}getTrimmedLength(){for(let e4=this.length-1;e4>=0;--e4)if(4194303&this._data[3*e4+0])return e4+(this._data[3*e4+0]>>22);return 0}getNoBgTrimmedLength(){for(let e4=this.length-1;e4>=0;--e4)if(4194303&this._data[3*e4+0]||50331648&this._data[3*e4+2])return e4+(this._data[3*e4+0]>>22);return 0}copyCellsFrom(e4,t5,s4,i4,r8){let n4=e4._data;if(r8)for(let r9=i4-1;r9>=0;r9--){for(let e5=0;e5<3;e5++)this._data[3*(s4+r9)+e5]=n4[3*(t5+r9)+e5];268435456&n4[3*(t5+r9)+2]&&(this._extendedAttrs[s4+r9]=e4._extendedAttrs[t5+r9])}else for(let r9=0;r9<i4;r9++){for(let e5=0;e5<3;e5++)this._data[3*(s4+r9)+e5]=n4[3*(t5+r9)+e5];268435456&n4[3*(t5+r9)+2]&&(this._extendedAttrs[s4+r9]=e4._extendedAttrs[t5+r9])}let o3=Object.keys(e4._combined);for(let i5=0;i5<o3.length;i5++){let r9=parseInt(o3[i5],10);r9>=t5&&(this._combined[r9-t5+s4]=e4._combined[r9])}}translateToString(e4,t5,s4,i4){t5=t5??0,s4=s4??this.length,e4&&(s4=Math.min(s4,this.getTrimmedLength())),i4&&(i4.length=0);let r8="";for(;t5<s4;){let e5=this._data[3*t5+0],s5=2097151&e5,a3=2097152&e5?this._combined[t5]:s5?(0,o2.stringFromCodePoint)(s5):n3.WHITESPACE_CELL_CHAR;if(r8+=a3,i4)for(let e6=0;e6<a3.length;++e6)i4.push(t5);t5+=e5>>22||1}return i4&&i4.push(t5),r8}}t4.BufferLine=h2},732:(e3,t4)=>{function s3(e4,t5,s4){if(t5===e4.length-1)return e4[t5].getTrimmedLength();let i3=!e4[t5].hasContent(s4-1)&&e4[t5].getWidth(s4-1)===1,r7=e4[t5+1].getWidth(0)===2;return i3&&r7?s4-1:s4}Object.defineProperty(t4,"__esModule",{value:!0}),t4.reflowLargerGetLinesToRemove=function(e4,t5,i3,r7,n3,o2){let a2=[];for(let h2=0;h2<e4.length-1;h2++){let c2=h2,l2=e4.get(++c2);if(!l2.isWrapped)continue;let u2=[e4.get(h2)];for(;c2<e4.length&&l2.isWrapped;)u2.push(l2),l2=e4.get(++c2);if(!o2&&r7>=h2&&r7<c2){h2+=u2.length-1;continue}let d2=0,f2=s3(u2,d2,t5),_4=1,p3=0;for(;_4<u2.length;){let e5=s3(u2,_4,t5),r8=e5-p3,o3=i3-f2,a3=Math.min(r8,o3);u2[d2].copyCellsFrom(u2[_4],p3,f2,a3,!1),f2+=a3,f2===i3&&(d2++,f2=0),p3+=a3,p3===e5&&(_4++,p3=0),f2===0&&d2!==0&&u2[d2-1].getWidth(i3-1)===2&&(u2[d2].copyCellsFrom(u2[d2-1],i3-1,f2++,1,!1),u2[d2-1].setCell(i3-1,n3))}u2[d2].replaceCells(f2,i3,n3);let g3=0;for(let e5=u2.length-1;e5>0&&(e5>d2||u2[e5].getTrimmedLength()===0);e5--)g3++;g3>0&&(a2.push(h2+u2.length-g3),a2.push(g3)),h2+=u2.length-1}return a2},t4.reflowLargerCreateNewLayout=function(e4,t5){let s4=[],i3=0,r7=t5[i3],n3=0;for(let o2=0;o2<e4.length;o2++)if(r7===o2){let s5=t5[++i3];e4.onDeleteEmitter.fire({index:o2-n3,amount:s5}),o2+=s5-1,n3+=s5,r7=t5[++i3]}else s4.push(o2);return{layout:s4,countRemoved:n3}},t4.reflowLargerApplyNewLayout=function(e4,t5){let s4=[];for(let i3=0;i3<t5.length;i3++)s4.push(e4.get(t5[i3]));for(let t6=0;t6<s4.length;t6++)e4.set(t6,s4[t6]);e4.length=t5.length},t4.reflowSmallerGetNewLineLengths=function(e4,t5,i3){let r7=[],n3=e4.map((i4,r8)=>s3(e4,r8,t5)).reduce((e5,t6)=>e5+t6),o2=0,a2=0,h2=0;for(;h2<n3;){if(n3-h2<i3){r7.push(n3-h2);break}o2+=i3;let c2=s3(e4,a2,t5);o2>c2&&(o2-=c2,a2++);let l2=e4[a2].getWidth(o2-1)===2;l2&&o2--;let u2=l2?i3-1:i3;r7.push(u2),h2+=u2}return r7},t4.getWrappedLineTrimmedLength=s3},4097:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.BufferSet=void 0;let i3=s3(7150),r7=s3(1073),n3=s3(802);class o2 extends i3.Disposable{constructor(e4,t5){super(),this._optionsService=e4,this._bufferService=t5,this._onBufferActivate=this._register(new n3.Emitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new r7.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new r7.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e4){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e4),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e4,t5){this._normal.resize(e4,t5),this._alt.resize(e4,t5),this.setupTabStops(e4)}setupTabStops(e4){this._normal.setupTabStops(e4),this._alt.setupTabStops(e4)}}t4.BufferSet=o2},3055:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.CellData=void 0;let i3=s3(726),r7=s3(8938),n3=s3(5451);class o2 extends n3.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new n3.ExtendedAttrs,this.combinedData=""}static fromCharData(e4){let t5=new o2;return t5.setFromCharData(e4),t5}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,i3.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e4){this.fg=e4[r7.CHAR_DATA_ATTR_INDEX],this.bg=0;let t5=!1;if(e4[r7.CHAR_DATA_CHAR_INDEX].length>2)t5=!0;else if(e4[r7.CHAR_DATA_CHAR_INDEX].length===2){let s4=e4[r7.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=s4&&s4<=56319){let i4=e4[r7.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=i4&&i4<=57343?this.content=1024*(s4-55296)+i4-56320+65536|e4[r7.CHAR_DATA_WIDTH_INDEX]<<22:t5=!0}else t5=!0}else this.content=e4[r7.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e4[r7.CHAR_DATA_WIDTH_INDEX]<<22;t5&&(this.combinedData=e4[r7.CHAR_DATA_CHAR_INDEX],this.content=2097152|e4[r7.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t4.CellData=o2},8938:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.WHITESPACE_CELL_CODE=t4.WHITESPACE_CELL_WIDTH=t4.WHITESPACE_CELL_CHAR=t4.NULL_CELL_CODE=t4.NULL_CELL_WIDTH=t4.NULL_CELL_CHAR=t4.CHAR_DATA_CODE_INDEX=t4.CHAR_DATA_WIDTH_INDEX=t4.CHAR_DATA_CHAR_INDEX=t4.CHAR_DATA_ATTR_INDEX=t4.DEFAULT_EXT=t4.DEFAULT_ATTR=t4.DEFAULT_COLOR=void 0,t4.DEFAULT_COLOR=0,t4.DEFAULT_ATTR=t4.DEFAULT_COLOR<<9|256,t4.DEFAULT_EXT=0,t4.CHAR_DATA_ATTR_INDEX=0,t4.CHAR_DATA_CHAR_INDEX=1,t4.CHAR_DATA_WIDTH_INDEX=2,t4.CHAR_DATA_CODE_INDEX=3,t4.NULL_CELL_CHAR="",t4.NULL_CELL_WIDTH=1,t4.NULL_CELL_CODE=0,t4.WHITESPACE_CELL_CHAR=" ",t4.WHITESPACE_CELL_WIDTH=1,t4.WHITESPACE_CELL_CODE=32},8158:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.Marker=void 0;let i3=s3(802),r7=s3(7150);class n3{get id(){return this._id}constructor(e4){this.line=e4,this.isDisposed=!1,this._disposables=[],this._id=n3._nextId++,this._onDispose=this.register(new i3.Emitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,r7.dispose)(this._disposables),this._disposables.length=0)}register(e4){return this._disposables.push(e4),e4}}t4.Marker=n3,n3._nextId=1},6760:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.DEFAULT_CHARSET=t4.CHARSETS=void 0,t4.CHARSETS={},t4.DEFAULT_CHARSET=t4.CHARSETS.B,t4.CHARSETS[0]={"`":"\u25C6",a:"\u2592",b:"\u2409",c:"\u240C",d:"\u240D",e:"\u240A",f:"\xB0",g:"\xB1",h:"\u2424",i:"\u240B",j:"\u2518",k:"\u2510",l:"\u250C",m:"\u2514",n:"\u253C",o:"\u23BA",p:"\u23BB",q:"\u2500",r:"\u23BC",s:"\u23BD",t:"\u251C",u:"\u2524",v:"\u2534",w:"\u252C",x:"\u2502",y:"\u2264",z:"\u2265","{":"\u03C0","|":"\u2260","}":"\xA3","~":"\xB7"},t4.CHARSETS.A={"#":"\xA3"},t4.CHARSETS.B=void 0,t4.CHARSETS[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"},t4.CHARSETS.C=t4.CHARSETS[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"},t4.CHARSETS.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"},t4.CHARSETS.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"},t4.CHARSETS.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"},t4.CHARSETS.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"},t4.CHARSETS.E=t4.CHARSETS[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"},t4.CHARSETS.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"},t4.CHARSETS.H=t4.CHARSETS[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"},t4.CHARSETS["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"}},3534:(e3,t4)=>{var s3,i3,r7;Object.defineProperty(t4,"__esModule",{value:!0}),t4.C1_ESCAPED=t4.C1=t4.C0=void 0,function(e4){e4.NUL="\x00",e4.SOH="\x01",e4.STX="\x02",e4.ETX="\x03",e4.EOT="\x04",e4.ENQ="\x05",e4.ACK="\x06",e4.BEL="\x07",e4.BS="\b",e4.HT="\t",e4.LF=`
3
3
  `,e4.VT="\v",e4.FF="\f",e4.CR="\r",e4.SO="\x0E",e4.SI="\x0F",e4.DLE="\x10",e4.DC1="\x11",e4.DC2="\x12",e4.DC3="\x13",e4.DC4="\x14",e4.NAK="\x15",e4.SYN="\x16",e4.ETB="\x17",e4.CAN="\x18",e4.EM="\x19",e4.SUB="\x1A",e4.ESC="\x1B",e4.FS="\x1C",e4.GS="\x1D",e4.RS="\x1E",e4.US="\x1F",e4.SP=" ",e4.DEL="\x7F"}(s3||(t4.C0=s3={})),function(e4){e4.PAD="\x80",e4.HOP="\x81",e4.BPH="\x82",e4.NBH="\x83",e4.IND="\x84",e4.NEL="\x85",e4.SSA="\x86",e4.ESA="\x87",e4.HTS="\x88",e4.HTJ="\x89",e4.VTS="\x8A",e4.PLD="\x8B",e4.PLU="\x8C",e4.RI="\x8D",e4.SS2="\x8E",e4.SS3="\x8F",e4.DCS="\x90",e4.PU1="\x91",e4.PU2="\x92",e4.STS="\x93",e4.CCH="\x94",e4.MW="\x95",e4.SPA="\x96",e4.EPA="\x97",e4.SOS="\x98",e4.SGCI="\x99",e4.SCI="\x9A",e4.CSI="\x9B",e4.ST="\x9C",e4.OSC="\x9D",e4.PM="\x9E",e4.APC="\x9F"}(i3||(t4.C1=i3={})),function(e4){e4.ST=`${s3.ESC}\\`}(r7||(t4.C1_ESCAPED=r7={}))},726:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.Utf8ToUtf32=t4.StringToUtf32=void 0,t4.stringFromCodePoint=function(e4){return e4>65535?(e4-=65536,String.fromCharCode(55296+(e4>>10))+String.fromCharCode(e4%1024+56320)):String.fromCharCode(e4)},t4.utf32ToString=function(e4,t5=0,s3=e4.length){let i3="";for(let r7=t5;r7<s3;++r7){let t6=e4[r7];t6>65535?(t6-=65536,i3+=String.fromCharCode(55296+(t6>>10))+String.fromCharCode(t6%1024+56320)):i3+=String.fromCharCode(t6)}return i3},t4.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e4,t5){let s3=e4.length;if(!s3)return 0;let i3=0,r7=0;if(this._interim){let s4=e4.charCodeAt(r7++);56320<=s4&&s4<=57343?t5[i3++]=1024*(this._interim-55296)+s4-56320+65536:(t5[i3++]=this._interim,t5[i3++]=s4),this._interim=0}for(let n3=r7;n3<s3;++n3){let r8=e4.charCodeAt(n3);if(55296<=r8&&r8<=56319){if(++n3>=s3)return this._interim=r8,i3;let o2=e4.charCodeAt(n3);56320<=o2&&o2<=57343?t5[i3++]=1024*(r8-55296)+o2-56320+65536:(t5[i3++]=r8,t5[i3++]=o2)}else r8!==65279&&(t5[i3++]=r8)}return i3}},t4.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e4,t5){let s3=e4.length;if(!s3)return 0;let i3,r7,n3,o2,a2=0,h2=0,c2=0;if(this.interim[0]){let i4=!1,r8=this.interim[0];r8&=(224&r8)==192?31:(240&r8)==224?15:7;let n4,o3=0;for(;(n4=63&this.interim[++o3])&&o3<4;)r8<<=6,r8|=n4;let h3=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,l3=h3-o3;for(;c2<l3;){if(c2>=s3)return 0;if(n4=e4[c2++],(192&n4)!=128){c2--,i4=!0;break}this.interim[o3++]=n4,r8<<=6,r8|=63&n4}i4||(h3===2?r8<128?c2--:t5[a2++]=r8:h3===3?r8<2048||r8>=55296&&r8<=57343||r8===65279||(t5[a2++]=r8):r8<65536||r8>1114111||(t5[a2++]=r8)),this.interim.fill(0)}let l2=s3-4,u2=c2;for(;u2<s3;){for(;!(!(u2<l2)||128&(i3=e4[u2])||128&(r7=e4[u2+1])||128&(n3=e4[u2+2])||128&(o2=e4[u2+3]));)t5[a2++]=i3,t5[a2++]=r7,t5[a2++]=n3,t5[a2++]=o2,u2+=4;if(i3=e4[u2++],i3<128)t5[a2++]=i3;else if((224&i3)==192){if(u2>=s3)return this.interim[0]=i3,a2;if(r7=e4[u2++],(192&r7)!=128){u2--;continue}if(h2=(31&i3)<<6|63&r7,h2<128){u2--;continue}t5[a2++]=h2}else if((240&i3)==224){if(u2>=s3)return this.interim[0]=i3,a2;if(r7=e4[u2++],(192&r7)!=128){u2--;continue}if(u2>=s3)return this.interim[0]=i3,this.interim[1]=r7,a2;if(n3=e4[u2++],(192&n3)!=128){u2--;continue}if(h2=(15&i3)<<12|(63&r7)<<6|63&n3,h2<2048||h2>=55296&&h2<=57343||h2===65279)continue;t5[a2++]=h2}else if((248&i3)==240){if(u2>=s3)return this.interim[0]=i3,a2;if(r7=e4[u2++],(192&r7)!=128){u2--;continue}if(u2>=s3)return this.interim[0]=i3,this.interim[1]=r7,a2;if(n3=e4[u2++],(192&n3)!=128){u2--;continue}if(u2>=s3)return this.interim[0]=i3,this.interim[1]=r7,this.interim[2]=n3,a2;if(o2=e4[u2++],(192&o2)!=128){u2--;continue}if(h2=(7&i3)<<18|(63&r7)<<12|(63&n3)<<6|63&o2,h2<65536||h2>1114111)continue;t5[a2++]=h2}}return a2}}},7428:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.UnicodeV6=void 0;let i3=s3(6415),r7=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],n3=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],o2;t4.UnicodeV6=class{constructor(){if(this.version="6",!o2){o2=new Uint8Array(65536),o2.fill(1),o2[0]=0,o2.fill(0,1,32),o2.fill(0,127,160),o2.fill(2,4352,4448),o2[9001]=2,o2[9002]=2,o2.fill(2,11904,42192),o2[12351]=1,o2.fill(2,44032,55204),o2.fill(2,63744,64256),o2.fill(2,65040,65050),o2.fill(2,65072,65136),o2.fill(2,65280,65377),o2.fill(2,65504,65511);for(let e4=0;e4<r7.length;++e4)o2.fill(0,r7[e4][0],r7[e4][1]+1)}}wcwidth(e4){return e4<32?0:e4<127?1:e4<65536?o2[e4]:function(e5,t5){let s4,i4=0,r8=t5.length-1;if(e5<t5[0][0]||e5>t5[r8][1])return!1;for(;r8>=i4;)if(s4=i4+r8>>1,e5>t5[s4][1])i4=s4+1;else{if(!(e5<t5[s4][0]))return!0;r8=s4-1}return!1}(e4,n3)?0:e4>=131072&&e4<=196605||e4>=196608&&e4<=262141?2:1}charProperties(e4,t5){let s4=this.wcwidth(e4),r8=s4===0&&t5!==0;if(r8){let e5=i3.UnicodeService.extractWidth(t5);e5===0?r8=!1:e5>s4&&(s4=e5)}return i3.UnicodeService.createPropertyValue(0,s4,r8)}}},3562:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.WriteBuffer=void 0;let i3=s3(7150),r7=s3(802);class n3 extends i3.Disposable{constructor(e4){super(),this._action=e4,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new r7.Emitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e4,t5){if(t5!==void 0&&this._syncCalls>t5)return void(this._syncCalls=0);if(this._pendingData+=e4.length,this._writeBuffer.push(e4),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let s4;for(this._isSyncWriting=!0;s4=this._writeBuffer.shift();){this._action(s4);let e5=this._callbacks.shift();e5&&e5()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e4,t5){if(this._pendingData>50000000)throw Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=e4.length,this._writeBuffer.push(e4),this._callbacks.push(t5),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=e4.length,this._writeBuffer.push(e4),this._callbacks.push(t5)}_innerWrite(e4=0,t5=!0){let s4=e4||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e5=this._writeBuffer[this._bufferOffset],i4=this._action(e5,t5);if(i4){let e6=(e7)=>performance.now()-s4>=12?setTimeout(()=>this._innerWrite(0,e7)):this._innerWrite(s4,e7);return void i4.catch((e7)=>(queueMicrotask(()=>{throw e7}),Promise.resolve(!1))).then(e6)}let r8=this._callbacks[this._bufferOffset];if(r8&&r8(),this._bufferOffset++,this._pendingData-=e5.length,performance.now()-s4>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}t4.WriteBuffer=n3},8693:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.parseColor=function(e4){if(!e4)return;let t5=e4.toLowerCase();if(t5.indexOf("rgb:")===0){t5=t5.slice(4);let e5=s3.exec(t5);if(e5){let t6=e5[1]?15:e5[4]?255:e5[7]?4095:65535;return[Math.round(parseInt(e5[1]||e5[4]||e5[7]||e5[10],16)/t6*255),Math.round(parseInt(e5[2]||e5[5]||e5[8]||e5[11],16)/t6*255),Math.round(parseInt(e5[3]||e5[6]||e5[9]||e5[12],16)/t6*255)]}}else if(t5.indexOf("#")===0&&(t5=t5.slice(1),i3.exec(t5)&&[3,6,9,12].includes(t5.length))){let e5=t5.length/3,s4=[0,0,0];for(let i4=0;i4<3;++i4){let r8=parseInt(t5.slice(e5*i4,e5*i4+e5),16);s4[i4]=e5===1?r8<<4:e5===2?r8:e5===3?r8>>4:r8>>8}return s4}},t4.toRgbString=function(e4,t5=16){let[s4,i4,n3]=e4;return`rgb:${r7(s4,t5)}/${r7(i4,t5)}/${r7(n3,t5)}`};let s3=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,i3=/^[\da-f]+$/;function r7(e4,t5){let s4=e4.toString(16),i4=s4.length<2?"0"+s4:s4;switch(t5){case 4:return s4[0];case 8:return i4;case 12:return(i4+i4).slice(0,3);default:return i4+i4}}},1263:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.PAYLOAD_LIMIT=void 0,t4.PAYLOAD_LIMIT=1e7},9823:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.DcsHandler=t4.DcsParser=void 0;let i3=s3(726),r7=s3(7262),n3=s3(1263),o2=[];t4.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=o2,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=o2}registerHandler(e4,t5){this._handlers[e4]===void 0&&(this._handlers[e4]=[]);let s4=this._handlers[e4];return s4.push(t5),{dispose:()=>{let e5=s4.indexOf(t5);e5!==-1&&s4.splice(e5,1)}}}clearHandler(e4){this._handlers[e4]&&delete this._handlers[e4]}setHandlerFallback(e4){this._handlerFb=e4}reset(){if(this._active.length)for(let e4=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e4>=0;--e4)this._active[e4].unhook(!1);this._stack.paused=!1,this._active=o2,this._ident=0}hook(e4,t5){if(this.reset(),this._ident=e4,this._active=this._handlers[e4]||o2,this._active.length)for(let e5=this._active.length-1;e5>=0;e5--)this._active[e5].hook(t5);else this._handlerFb(this._ident,"HOOK",t5)}put(e4,t5,s4){if(this._active.length)for(let i4=this._active.length-1;i4>=0;i4--)this._active[i4].put(e4,t5,s4);else this._handlerFb(this._ident,"PUT",(0,i3.utf32ToString)(e4,t5,s4))}unhook(e4,t5=!0){if(this._active.length){let s4=!1,i4=this._active.length-1,r8=!1;if(this._stack.paused&&(i4=this._stack.loopPosition-1,s4=t5,r8=this._stack.fallThrough,this._stack.paused=!1),!r8&&s4===!1){for(;i4>=0&&(s4=this._active[i4].unhook(e4),s4!==!0);i4--)if(s4 instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=i4,this._stack.fallThrough=!1,s4;i4--}for(;i4>=0;i4--)if(s4=this._active[i4].unhook(!1),s4 instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=i4,this._stack.fallThrough=!0,s4}else this._handlerFb(this._ident,"UNHOOK",e4);this._active=o2,this._ident=0}};let a2=new r7.Params;a2.addParam(0),t4.DcsHandler=class{constructor(e4){this._handler=e4,this._data="",this._params=a2,this._hitLimit=!1}hook(e4){this._params=e4.length>1||e4.params[0]?e4.clone():a2,this._data="",this._hitLimit=!1}put(e4,t5,s4){this._hitLimit||(this._data+=(0,i3.utf32ToString)(e4,t5,s4),this._data.length>n3.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(e4){let t5=!1;if(this._hitLimit)t5=!1;else if(e4&&(t5=this._handler(this._data,this._params),t5 instanceof Promise))return t5.then((e5)=>(this._params=a2,this._data="",this._hitLimit=!1,e5));return this._params=a2,this._data="",this._hitLimit=!1,t5}}},6717:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.EscapeSequenceParser=t4.VT500_TRANSITION_TABLE=t4.TransitionTable=void 0;let i3=s3(7150),r7=s3(7262),n3=s3(1346),o2=s3(9823);class a2{constructor(e4){this.table=new Uint8Array(e4)}setDefault(e4,t5){this.table.fill(e4<<4|t5)}add(e4,t5,s4,i4){this.table[t5<<8|e4]=s4<<4|i4}addMany(e4,t5,s4,i4){for(let r8=0;r8<e4.length;r8++)this.table[t5<<8|e4[r8]]=s4<<4|i4}}t4.TransitionTable=a2;let h2=160;t4.VT500_TRANSITION_TABLE=function(){let e4=new a2(4095),t5=Array.apply(null,Array(256)).map((e5,t6)=>t6),s4=(e5,s5)=>t5.slice(e5,s5),i4=s4(32,127),r8=s4(0,24);r8.push(25),r8.push.apply(r8,s4(28,32));let n4=s4(0,14),o3;for(o3 in e4.setDefault(1,0),e4.addMany(i4,0,2,0),n4)e4.addMany([24,26,153,154],o3,3,0),e4.addMany(s4(128,144),o3,3,0),e4.addMany(s4(144,152),o3,3,0),e4.add(156,o3,0,0),e4.add(27,o3,11,1),e4.add(157,o3,4,8),e4.addMany([152,158,159],o3,0,7),e4.add(155,o3,11,3),e4.add(144,o3,11,9);return e4.addMany(r8,0,3,0),e4.addMany(r8,1,3,1),e4.add(127,1,0,1),e4.addMany(r8,8,0,8),e4.addMany(r8,3,3,3),e4.add(127,3,0,3),e4.addMany(r8,4,3,4),e4.add(127,4,0,4),e4.addMany(r8,6,3,6),e4.addMany(r8,5,3,5),e4.add(127,5,0,5),e4.addMany(r8,2,3,2),e4.add(127,2,0,2),e4.add(93,1,4,8),e4.addMany(i4,8,5,8),e4.add(127,8,5,8),e4.addMany([156,27,24,26,7],8,6,0),e4.addMany(s4(28,32),8,0,8),e4.addMany([88,94,95],1,0,7),e4.addMany(i4,7,0,7),e4.addMany(r8,7,0,7),e4.add(156,7,0,0),e4.add(127,7,0,7),e4.add(91,1,11,3),e4.addMany(s4(64,127),3,7,0),e4.addMany(s4(48,60),3,8,4),e4.addMany([60,61,62,63],3,9,4),e4.addMany(s4(48,60),4,8,4),e4.addMany(s4(64,127),4,7,0),e4.addMany([60,61,62,63],4,0,6),e4.addMany(s4(32,64),6,0,6),e4.add(127,6,0,6),e4.addMany(s4(64,127),6,0,0),e4.addMany(s4(32,48),3,9,5),e4.addMany(s4(32,48),5,9,5),e4.addMany(s4(48,64),5,0,6),e4.addMany(s4(64,127),5,7,0),e4.addMany(s4(32,48),4,9,5),e4.addMany(s4(32,48),1,9,2),e4.addMany(s4(32,48),2,9,2),e4.addMany(s4(48,127),2,10,0),e4.addMany(s4(48,80),1,10,0),e4.addMany(s4(81,88),1,10,0),e4.addMany([89,90,92],1,10,0),e4.addMany(s4(96,127),1,10,0),e4.add(80,1,11,9),e4.addMany(r8,9,0,9),e4.add(127,9,0,9),e4.addMany(s4(28,32),9,0,9),e4.addMany(s4(32,48),9,9,12),e4.addMany(s4(48,60),9,8,10),e4.addMany([60,61,62,63],9,9,10),e4.addMany(r8,11,0,11),e4.addMany(s4(32,128),11,0,11),e4.addMany(s4(28,32),11,0,11),e4.addMany(r8,10,0,10),e4.add(127,10,0,10),e4.addMany(s4(28,32),10,0,10),e4.addMany(s4(48,60),10,8,10),e4.addMany([60,61,62,63],10,0,11),e4.addMany(s4(32,48),10,9,12),e4.addMany(r8,12,0,12),e4.add(127,12,0,12),e4.addMany(s4(28,32),12,0,12),e4.addMany(s4(32,48),12,9,12),e4.addMany(s4(48,64),12,0,11),e4.addMany(s4(64,127),12,12,13),e4.addMany(s4(64,127),10,12,13),e4.addMany(s4(64,127),9,12,13),e4.addMany(r8,13,13,13),e4.addMany(i4,13,13,13),e4.add(127,13,0,13),e4.addMany([27,156,24,26],13,14,0),e4.add(h2,0,2,0),e4.add(h2,8,5,8),e4.add(h2,6,0,6),e4.add(h2,11,0,11),e4.add(h2,13,13,13),e4}();class c2 extends i3.Disposable{constructor(e4=t4.VT500_TRANSITION_TABLE){super(),this._transitions=e4,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new r7.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e5,t5,s4)=>{},this._executeHandlerFb=(e5)=>{},this._csiHandlerFb=(e5,t5)=>{},this._escHandlerFb=(e5)=>{},this._errorHandlerFb=(e5)=>e5,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register((0,i3.toDisposable)(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new n3.OscParser),this._dcsParser=this._register(new o2.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e4,t5=[64,126]){let s4=0;if(e4.prefix){if(e4.prefix.length>1)throw Error("only one byte as prefix supported");if(s4=e4.prefix.charCodeAt(0),s4&&60>s4||s4>63)throw Error("prefix must be in range 0x3c .. 0x3f")}if(e4.intermediates){if(e4.intermediates.length>2)throw Error("only two bytes as intermediates are supported");for(let t6=0;t6<e4.intermediates.length;++t6){let i5=e4.intermediates.charCodeAt(t6);if(32>i5||i5>47)throw Error("intermediate must be in range 0x20 .. 0x2f");s4<<=8,s4|=i5}}if(e4.final.length!==1)throw Error("final must be a single byte");let i4=e4.final.charCodeAt(0);if(t5[0]>i4||i4>t5[1])throw Error(`final must be in range ${t5[0]} .. ${t5[1]}`);return s4<<=8,s4|=i4,s4}identToString(e4){let t5=[];for(;e4;)t5.push(String.fromCharCode(255&e4)),e4>>=8;return t5.reverse().join("")}setPrintHandler(e4){this._printHandler=e4}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e4,t5){let s4=this._identifier(e4,[48,126]);this._escHandlers[s4]===void 0&&(this._escHandlers[s4]=[]);let i4=this._escHandlers[s4];return i4.push(t5),{dispose:()=>{let e5=i4.indexOf(t5);e5!==-1&&i4.splice(e5,1)}}}clearEscHandler(e4){this._escHandlers[this._identifier(e4,[48,126])]&&delete this._escHandlers[this._identifier(e4,[48,126])]}setEscHandlerFallback(e4){this._escHandlerFb=e4}setExecuteHandler(e4,t5){this._executeHandlers[e4.charCodeAt(0)]=t5}clearExecuteHandler(e4){this._executeHandlers[e4.charCodeAt(0)]&&delete this._executeHandlers[e4.charCodeAt(0)]}setExecuteHandlerFallback(e4){this._executeHandlerFb=e4}registerCsiHandler(e4,t5){let s4=this._identifier(e4);this._csiHandlers[s4]===void 0&&(this._csiHandlers[s4]=[]);let i4=this._csiHandlers[s4];return i4.push(t5),{dispose:()=>{let e5=i4.indexOf(t5);e5!==-1&&i4.splice(e5,1)}}}clearCsiHandler(e4){this._csiHandlers[this._identifier(e4)]&&delete this._csiHandlers[this._identifier(e4)]}setCsiHandlerFallback(e4){this._csiHandlerFb=e4}registerDcsHandler(e4,t5){return this._dcsParser.registerHandler(this._identifier(e4),t5)}clearDcsHandler(e4){this._dcsParser.clearHandler(this._identifier(e4))}setDcsHandlerFallback(e4){this._dcsParser.setHandlerFallback(e4)}registerOscHandler(e4,t5){return this._oscParser.registerHandler(e4,t5)}clearOscHandler(e4){this._oscParser.clearHandler(e4)}setOscHandlerFallback(e4){this._oscParser.setHandlerFallback(e4)}setErrorHandler(e4){this._errorHandler=e4}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e4,t5,s4,i4,r8){this._parseStack.state=e4,this._parseStack.handlers=t5,this._parseStack.handlerPos=s4,this._parseStack.transition=i4,this._parseStack.chunkPos=r8}parse(e4,t5,s4){let i4,r8=0,n4=0,o3=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o3=this._parseStack.chunkPos+1;else{if(s4===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error("improper continuation due to previous async handler, giving up parsing");let t6=this._parseStack.handlers,n5=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(s4===!1&&n5>-1){for(;n5>=0&&(i4=t6[n5](this._params),i4!==!0);n5--)if(i4 instanceof Promise)return this._parseStack.handlerPos=n5,i4}this._parseStack.handlers=[];break;case 4:if(s4===!1&&n5>-1){for(;n5>=0&&(i4=t6[n5](),i4!==!0);n5--)if(i4 instanceof Promise)return this._parseStack.handlerPos=n5,i4}this._parseStack.handlers=[];break;case 6:if(r8=e4[this._parseStack.chunkPos],i4=this._dcsParser.unhook(r8!==24&&r8!==26,s4),i4)return i4;r8===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r8=e4[this._parseStack.chunkPos],i4=this._oscParser.end(r8!==24&&r8!==26,s4),i4)return i4;r8===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,o3=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let s5=o3;s5<t5;++s5){switch(r8=e4[s5],n4=this._transitions.table[this.currentState<<8|(r8<160?r8:h2)],n4>>4){case 2:for(let i5=s5+1;;++i5){if(i5>=t5||(r8=e4[i5])<32||r8>126&&r8<h2){this._printHandler(e4,s5,i5),s5=i5-1;break}if(++i5>=t5||(r8=e4[i5])<32||r8>126&&r8<h2){this._printHandler(e4,s5,i5),s5=i5-1;break}if(++i5>=t5||(r8=e4[i5])<32||r8>126&&r8<h2){this._printHandler(e4,s5,i5),s5=i5-1;break}if(++i5>=t5||(r8=e4[i5])<32||r8>126&&r8<h2){this._printHandler(e4,s5,i5),s5=i5-1;break}}break;case 3:this._executeHandlers[r8]?this._executeHandlers[r8]():this._executeHandlerFb(r8),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:s5,code:r8,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let o4=this._csiHandlers[this._collect<<8|r8],a3=o4?o4.length-1:-1;for(;a3>=0&&(i4=o4[a3](this._params),i4!==!0);a3--)if(i4 instanceof Promise)return this._preserveStack(3,o4,a3,n4,s5),i4;a3<0&&this._csiHandlerFb(this._collect<<8|r8,this._params),this.precedingJoinState=0;break;case 8:do switch(r8){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r8-48)}while(++s5<t5&&(r8=e4[s5])>47&&r8<60);s5--;break;case 9:this._collect<<=8,this._collect|=r8;break;case 10:let c3=this._escHandlers[this._collect<<8|r8],l2=c3?c3.length-1:-1;for(;l2>=0&&(i4=c3[l2](),i4!==!0);l2--)if(i4 instanceof Promise)return this._preserveStack(4,c3,l2,n4,s5),i4;l2<0&&this._escHandlerFb(this._collect<<8|r8),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r8,this._params);break;case 13:for(let i5=s5+1;;++i5)if(i5>=t5||(r8=e4[i5])===24||r8===26||r8===27||r8>127&&r8<h2){this._dcsParser.put(e4,s5,i5),s5=i5-1;break}break;case 14:if(i4=this._dcsParser.unhook(r8!==24&&r8!==26),i4)return this._preserveStack(6,[],0,n4,s5),i4;r8===27&&(n4|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i5=s5+1;;i5++)if(i5>=t5||(r8=e4[i5])<32||r8>127&&r8<h2){this._oscParser.put(e4,s5,i5),s5=i5-1;break}break;case 6:if(i4=this._oscParser.end(r8!==24&&r8!==26),i4)return this._preserveStack(5,[],0,n4,s5),i4;r8===27&&(n4|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&n4}}}t4.EscapeSequenceParser=c2},1346:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.OscHandler=t4.OscParser=void 0;let i3=s3(1263),r7=s3(726),n3=[];t4.OscParser=class{constructor(){this._state=0,this._active=n3,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e4,t5){this._handlers[e4]===void 0&&(this._handlers[e4]=[]);let s4=this._handlers[e4];return s4.push(t5),{dispose:()=>{let e5=s4.indexOf(t5);e5!==-1&&s4.splice(e5,1)}}}clearHandler(e4){this._handlers[e4]&&delete this._handlers[e4]}setHandlerFallback(e4){this._handlerFb=e4}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=n3}reset(){if(this._state===2)for(let e4=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e4>=0;--e4)this._active[e4].end(!1);this._stack.paused=!1,this._active=n3,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||n3,this._active.length)for(let e4=this._active.length-1;e4>=0;e4--)this._active[e4].start();else this._handlerFb(this._id,"START")}_put(e4,t5,s4){if(this._active.length)for(let i4=this._active.length-1;i4>=0;i4--)this._active[i4].put(e4,t5,s4);else this._handlerFb(this._id,"PUT",(0,r7.utf32ToString)(e4,t5,s4))}start(){this.reset(),this._state=1}put(e4,t5,s4){if(this._state!==3){if(this._state===1)for(;t5<s4;){let s5=e4[t5++];if(s5===59){this._state=2,this._start();break}if(s5<48||57<s5)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+s5-48}this._state===2&&s4-t5>0&&this._put(e4,t5,s4)}}end(e4,t5=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let s4=!1,i4=this._active.length-1,r8=!1;if(this._stack.paused&&(i4=this._stack.loopPosition-1,s4=t5,r8=this._stack.fallThrough,this._stack.paused=!1),!r8&&s4===!1){for(;i4>=0&&(s4=this._active[i4].end(e4),s4!==!0);i4--)if(s4 instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=i4,this._stack.fallThrough=!1,s4;i4--}for(;i4>=0;i4--)if(s4=this._active[i4].end(!1),s4 instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=i4,this._stack.fallThrough=!0,s4}else this._handlerFb(this._id,"END",e4);this._active=n3,this._id=-1,this._state=0}}},t4.OscHandler=class{constructor(e4){this._handler=e4,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e4,t5,s4){this._hitLimit||(this._data+=(0,r7.utf32ToString)(e4,t5,s4),this._data.length>i3.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(e4){let t5=!1;if(this._hitLimit)t5=!1;else if(e4&&(t5=this._handler(this._data),t5 instanceof Promise))return t5.then((e5)=>(this._data="",this._hitLimit=!1,e5));return this._data="",this._hitLimit=!1,t5}}},7262:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.Params=void 0;let s3=2147483647;class i3{static fromArray(e4){let t5=new i3;if(!e4.length)return t5;for(let s4=Array.isArray(e4[0])?1:0;s4<e4.length;++s4){let i4=e4[s4];if(Array.isArray(i4))for(let e5=0;e5<i4.length;++e5)t5.addSubParam(i4[e5]);else t5.addParam(i4)}return t5}constructor(e4=32,t5=32){if(this.maxLength=e4,this.maxSubParamsLength=t5,t5>256)throw Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(e4),this.length=0,this._subParams=new Int32Array(t5),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e4),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){let e4=new i3(this.maxLength,this.maxSubParamsLength);return e4.params.set(this.params),e4.length=this.length,e4._subParams.set(this._subParams),e4._subParamsLength=this._subParamsLength,e4._subParamsIdx.set(this._subParamsIdx),e4._rejectDigits=this._rejectDigits,e4._rejectSubDigits=this._rejectSubDigits,e4._digitIsSub=this._digitIsSub,e4}toArray(){let e4=[];for(let t5=0;t5<this.length;++t5){e4.push(this.params[t5]);let s4=this._subParamsIdx[t5]>>8,i4=255&this._subParamsIdx[t5];i4-s4>0&&e4.push(Array.prototype.slice.call(this._subParams,s4,i4))}return e4}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e4){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e4<-1)throw Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e4>s3?s3:e4}}addSubParam(e4){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(e4<-1)throw Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=e4>s3?s3:e4,this._subParamsIdx[this.length-1]++}}hasSubParams(e4){return(255&this._subParamsIdx[e4])-(this._subParamsIdx[e4]>>8)>0}getSubParams(e4){let t5=this._subParamsIdx[e4]>>8,s4=255&this._subParamsIdx[e4];return s4-t5>0?this._subParams.subarray(t5,s4):null}getSubParamsAll(){let e4={};for(let t5=0;t5<this.length;++t5){let s4=this._subParamsIdx[t5]>>8,i4=255&this._subParamsIdx[t5];i4-s4>0&&(e4[t5]=this._subParams.slice(s4,i4))}return e4}addDigit(e4){let t5;if(this._rejectDigits||!(t5=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let i4=this._digitIsSub?this._subParams:this.params,r7=i4[t5-1];i4[t5-1]=~r7?Math.min(10*r7+e4,s3):e4}}t4.Params=i3},3027:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.AddonManager=void 0,t4.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let e4=this._addons.length-1;e4>=0;e4--)this._addons[e4].instance.dispose()}loadAddon(e4,t5){let s3={instance:t5,dispose:t5.dispose,isDisposed:!1};this._addons.push(s3),t5.dispose=()=>this._wrappedAddonDispose(s3),t5.activate(e4)}_wrappedAddonDispose(e4){if(e4.isDisposed)return;let t5=-1;for(let s3=0;s3<this._addons.length;s3++)if(this._addons[s3]===e4){t5=s3;break}if(t5===-1)throw Error("Could not dispose an addon that has not been loaded");e4.isDisposed=!0,e4.dispose.apply(e4.instance),this._addons.splice(t5,1)}}},3235:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.BufferApiView=void 0;let i3=s3(793),r7=s3(3055);t4.BufferApiView=class{constructor(e4,t5){this._buffer=e4,this.type=t5}init(e4){return this._buffer=e4,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e4){let t5=this._buffer.lines.get(e4);if(t5)return new i3.BufferLineApiView(t5)}getNullCell(){return new r7.CellData}}},793:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.BufferLineApiView=void 0;let i3=s3(3055);t4.BufferLineApiView=class{constructor(e4){this._line=e4}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e4,t5){if(!(e4<0||e4>=this._line.length))return t5?(this._line.loadCell(e4,t5),t5):this._line.loadCell(e4,new i3.CellData)}translateToString(e4,t5,s4){return this._line.translateToString(e4,t5,s4)}}},5101:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.BufferNamespaceApi=void 0;let i3=s3(3235),r7=s3(7150),n3=s3(802);class o2 extends r7.Disposable{constructor(e4){super(),this._core=e4,this._onBufferChange=this._register(new n3.Emitter),this.onBufferChange=this._onBufferChange.event,this._normal=new i3.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new i3.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}t4.BufferNamespaceApi=o2},6097:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.ParserApi=void 0,t4.ParserApi=class{constructor(e4){this._core=e4}registerCsiHandler(e4,t5){return this._core.registerCsiHandler(e4,(e5)=>t5(e5.toArray()))}addCsiHandler(e4,t5){return this.registerCsiHandler(e4,t5)}registerDcsHandler(e4,t5){return this._core.registerDcsHandler(e4,(e5,s3)=>t5(e5,s3.toArray()))}addDcsHandler(e4,t5){return this.registerDcsHandler(e4,t5)}registerEscHandler(e4,t5){return this._core.registerEscHandler(e4,t5)}addEscHandler(e4,t5){return this.registerEscHandler(e4,t5)}registerOscHandler(e4,t5){return this._core.registerOscHandler(e4,t5)}addOscHandler(e4,t5){return this.registerOscHandler(e4,t5)}}},4335:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.UnicodeApi=void 0,t4.UnicodeApi=class{constructor(e4){this._core=e4}register(e4){this._core.unicodeService.register(e4)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e4){this._core.unicodeService.activeVersion=e4}}},9640:function(e3,t4,s3){var i3=this&&this.__decorate||function(e4,t5,s4,i4){var r8,n4=arguments.length,o3=n4<3?t5:i4===null?i4=Object.getOwnPropertyDescriptor(t5,s4):i4;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o3=Reflect.decorate(e4,t5,s4,i4);else for(var a3=e4.length-1;a3>=0;a3--)(r8=e4[a3])&&(o3=(n4<3?r8(o3):n4>3?r8(t5,s4,o3):r8(t5,s4))||o3);return n4>3&&o3&&Object.defineProperty(t5,s4,o3),o3},r7=this&&this.__param||function(e4,t5){return function(s4,i4){t5(s4,i4,e4)}};Object.defineProperty(t4,"__esModule",{value:!0}),t4.BufferService=t4.MINIMUM_ROWS=t4.MINIMUM_COLS=void 0;let n3=s3(7150),o2=s3(4097),a2=s3(6501),h2=s3(802);t4.MINIMUM_COLS=2,t4.MINIMUM_ROWS=1;let c2=class extends n3.Disposable{get buffer(){return this.buffers.active}constructor(e4){super(),this.isUserScrolling=!1,this._onResize=this._register(new h2.Emitter),this.onResize=this._onResize.event,this._onScroll=this._register(new h2.Emitter),this.onScroll=this._onScroll.event,this.cols=Math.max(e4.rawOptions.cols||0,t4.MINIMUM_COLS),this.rows=Math.max(e4.rawOptions.rows||0,t4.MINIMUM_ROWS),this.buffers=this._register(new o2.BufferSet(e4,this)),this._register(this.buffers.onBufferActivate((e5)=>{this._onScroll.fire(e5.activeBuffer.ydisp)}))}resize(e4,t5){let s4=this.cols!==e4,i4=this.rows!==t5;this.cols=e4,this.rows=t5,this.buffers.resize(e4,t5),this._onResize.fire({cols:e4,rows:t5,colsChanged:s4,rowsChanged:i4})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e4,t5=!1){let s4=this.buffer,i4;i4=this._cachedBlankLine,i4&&i4.length===this.cols&&i4.getFg(0)===e4.fg&&i4.getBg(0)===e4.bg||(i4=s4.getBlankLine(e4,t5),this._cachedBlankLine=i4),i4.isWrapped=t5;let r8=s4.ybase+s4.scrollTop,n4=s4.ybase+s4.scrollBottom;if(s4.scrollTop===0){let e5=s4.lines.isFull;n4===s4.lines.length-1?e5?s4.lines.recycle().copyFrom(i4):s4.lines.push(i4.clone()):s4.lines.splice(n4+1,0,i4.clone()),e5?this.isUserScrolling&&(s4.ydisp=Math.max(s4.ydisp-1,0)):(s4.ybase++,this.isUserScrolling||s4.ydisp++)}else{let e5=n4-r8+1;s4.lines.shiftElements(r8+1,e5-1,-1),s4.lines.set(n4,i4.clone())}this.isUserScrolling||(s4.ydisp=s4.ybase),this._onScroll.fire(s4.ydisp)}scrollLines(e4,t5){let s4=this.buffer;if(e4<0){if(s4.ydisp===0)return;this.isUserScrolling=!0}else e4+s4.ydisp>=s4.ybase&&(this.isUserScrolling=!1);let i4=s4.ydisp;s4.ydisp=Math.max(Math.min(s4.ydisp+e4,s4.ybase),0),i4!==s4.ydisp&&(t5||this._onScroll.fire(s4.ydisp))}};t4.BufferService=c2,t4.BufferService=c2=i3([r7(0,a2.IOptionsService)],c2)},5746:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.CharsetService=void 0,t4.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e4){this.glevel=e4,this.charset=this._charsets[e4]}setgCharset(e4,t5){this._charsets[e4]=t5,this.glevel===e4&&(this.charset=t5)}}},7792:function(e3,t4,s3){var i3=this&&this.__decorate||function(e4,t5,s4,i4){var r8,n4=arguments.length,o3=n4<3?t5:i4===null?i4=Object.getOwnPropertyDescriptor(t5,s4):i4;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o3=Reflect.decorate(e4,t5,s4,i4);else for(var a3=e4.length-1;a3>=0;a3--)(r8=e4[a3])&&(o3=(n4<3?r8(o3):n4>3?r8(t5,s4,o3):r8(t5,s4))||o3);return n4>3&&o3&&Object.defineProperty(t5,s4,o3),o3},r7=this&&this.__param||function(e4,t5){return function(s4,i4){t5(s4,i4,e4)}};Object.defineProperty(t4,"__esModule",{value:!0}),t4.CoreMouseService=void 0;let n3=s3(6501),o2=s3(7150),a2=s3(802),h2={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:(e4)=>e4.button!==4&&e4.action===1&&(e4.ctrl=!1,e4.alt=!1,e4.shift=!1,!0)},VT200:{events:19,restrict:(e4)=>e4.action!==32},DRAG:{events:23,restrict:(e4)=>e4.action!==32||e4.button!==3},ANY:{events:31,restrict:(e4)=>!0}};function c2(e4,t5){let s4=(e4.ctrl?16:0)|(e4.shift?4:0)|(e4.alt?8:0);return e4.button===4?(s4|=64,s4|=e4.action):(s4|=3&e4.button,4&e4.button&&(s4|=64),8&e4.button&&(s4|=128),e4.action===32?s4|=32:e4.action!==0||t5||(s4|=3)),s4}let l2=String.fromCharCode,u2={DEFAULT:(e4)=>{let t5=[c2(e4,!1)+32,e4.col+32,e4.row+32];return t5[0]>255||t5[1]>255||t5[2]>255?"":`\x1B[M${l2(t5[0])}${l2(t5[1])}${l2(t5[2])}`},SGR:(e4)=>{let t5=e4.action===0&&e4.button!==4?"m":"M";return`\x1B[<${c2(e4,!0)};${e4.col};${e4.row}${t5}`},SGR_PIXELS:(e4)=>{let t5=e4.action===0&&e4.button!==4?"m":"M";return`\x1B[<${c2(e4,!0)};${e4.x};${e4.y}${t5}`}},d2=class extends o2.Disposable{constructor(e4,t5,s4){super(),this._bufferService=e4,this._coreService=t5,this._optionsService=s4,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new a2.Emitter),this.onProtocolChange=this._onProtocolChange.event;for(let e5 of Object.keys(h2))this.addProtocol(e5,h2[e5]);for(let e5 of Object.keys(u2))this.addEncoding(e5,u2[e5]);this.reset()}addProtocol(e4,t5){this._protocols[e4]=t5}addEncoding(e4,t5){this._encodings[e4]=t5}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e4){if(!this._protocols[e4])throw Error(`unknown protocol "${e4}"`);this._activeProtocol=e4,this._onProtocolChange.fire(this._protocols[e4].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e4){if(!this._encodings[e4])throw Error(`unknown encoding "${e4}"`);this._activeEncoding=e4}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e4,t5,s4){if(e4.deltaY===0||e4.shiftKey)return 0;if(t5===void 0||s4===void 0)return 0;let i4=t5/s4,r8=this._applyScrollModifier(e4.deltaY,e4);return e4.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(r8/=i4+0,Math.abs(e4.deltaY)<50&&(r8*=0.3),this._wheelPartialScroll+=r8,r8=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e4.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(r8*=this._bufferService.rows),r8}_applyScrollModifier(e4,t5){return t5.altKey||t5.ctrlKey||t5.shiftKey?e4*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e4*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e4){if(e4.col<0||e4.col>=this._bufferService.cols||e4.row<0||e4.row>=this._bufferService.rows)return!1;if(e4.button===4&&e4.action===32)return!1;if(e4.button===3&&e4.action!==32)return!1;if(e4.button!==4&&(e4.action===2||e4.action===3))return!1;if(e4.col++,e4.row++,e4.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e4,this._activeEncoding==="SGR_PIXELS"))return!1;if(!this._protocols[this._activeProtocol].restrict(e4))return!1;let t5=this._encodings[this._activeEncoding](e4);return t5&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t5):this._coreService.triggerDataEvent(t5,!0)),this._lastEvent=e4,!0}explainEvents(e4){return{down:!!(1&e4),up:!!(2&e4),drag:!!(4&e4),move:!!(8&e4),wheel:!!(16&e4)}}_equalEvents(e4,t5,s4){if(s4){if(e4.x!==t5.x)return!1;if(e4.y!==t5.y)return!1}else{if(e4.col!==t5.col)return!1;if(e4.row!==t5.row)return!1}return e4.button===t5.button&&e4.action===t5.action&&e4.ctrl===t5.ctrl&&e4.alt===t5.alt&&e4.shift===t5.shift}};t4.CoreMouseService=d2,t4.CoreMouseService=d2=i3([r7(0,n3.IBufferService),r7(1,n3.ICoreService),r7(2,n3.IOptionsService)],d2)},4071:function(e3,t4,s3){var i3=this&&this.__decorate||function(e4,t5,s4,i4){var r8,n4=arguments.length,o3=n4<3?t5:i4===null?i4=Object.getOwnPropertyDescriptor(t5,s4):i4;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o3=Reflect.decorate(e4,t5,s4,i4);else for(var a3=e4.length-1;a3>=0;a3--)(r8=e4[a3])&&(o3=(n4<3?r8(o3):n4>3?r8(t5,s4,o3):r8(t5,s4))||o3);return n4>3&&o3&&Object.defineProperty(t5,s4,o3),o3},r7=this&&this.__param||function(e4,t5){return function(s4,i4){t5(s4,i4,e4)}};Object.defineProperty(t4,"__esModule",{value:!0}),t4.CoreService=void 0;let n3=s3(7453),o2=s3(7150),a2=s3(6501),h2=s3(802),c2=Object.freeze({insertMode:!1}),l2=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),u2=class extends o2.Disposable{constructor(e4,t5,s4){super(),this._bufferService=e4,this._logService=t5,this._optionsService=s4,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new h2.Emitter),this.onData=this._onData.event,this._onUserInput=this._register(new h2.Emitter),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new h2.Emitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new h2.Emitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,n3.clone)(c2),this.decPrivateModes=(0,n3.clone)(l2)}reset(){this.modes=(0,n3.clone)(c2),this.decPrivateModes=(0,n3.clone)(l2)}triggerDataEvent(e4,t5=!1){if(this._optionsService.rawOptions.disableStdin)return;let s4=this._bufferService.buffer;t5&&this._optionsService.rawOptions.scrollOnUserInput&&s4.ybase!==s4.ydisp&&this._onRequestScrollToBottom.fire(),t5&&this._onUserInput.fire(),this._logService.debug(`sending data "${e4}"`),this._logService.trace("sending data (codes)",()=>e4.split("").map((e5)=>e5.charCodeAt(0))),this._onData.fire(e4)}triggerBinaryEvent(e4){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e4}"`),this._logService.trace("sending binary (codes)",()=>e4.split("").map((e5)=>e5.charCodeAt(0))),this._onBinary.fire(e4))}};t4.CoreService=u2,t4.CoreService=u2=i3([r7(0,a2.IBufferService),r7(1,a2.ILogService),r7(2,a2.IOptionsService)],u2)},6025:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.InstantiationService=t4.ServiceCollection=void 0;let i3=s3(6501),r7=s3(6201);class n3{constructor(...e4){this._entries=new Map;for(let[t5,s4]of e4)this.set(t5,s4)}set(e4,t5){let s4=this._entries.get(e4);return this._entries.set(e4,t5),s4}forEach(e4){for(let[t5,s4]of this._entries.entries())e4(t5,s4)}has(e4){return this._entries.has(e4)}get(e4){return this._entries.get(e4)}}t4.ServiceCollection=n3,t4.InstantiationService=class{constructor(){this._services=new n3,this._services.set(i3.IInstantiationService,this)}setService(e4,t5){this._services.set(e4,t5)}getService(e4){return this._services.get(e4)}createInstance(e4,...t5){let s4=(0,r7.getServiceDependencies)(e4).sort((e5,t6)=>e5.index-t6.index),i4=[];for(let t6 of s4){let s5=this._services.get(t6.id);if(!s5)throw Error(`[createInstance] ${e4.name} depends on UNKNOWN service ${t6.id._id}.`);i4.push(s5)}let n4=s4.length>0?s4[0].index:t5.length;if(t5.length!==n4)throw Error(`[createInstance] First service dependency of ${e4.name} at position ${n4+1} conflicts with ${t5.length} static arguments`);return new e4(...[...t5,...i4])}}},7276:function(e3,t4,s3){var i3=this&&this.__decorate||function(e4,t5,s4,i4){var r8,n4=arguments.length,o3=n4<3?t5:i4===null?i4=Object.getOwnPropertyDescriptor(t5,s4):i4;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o3=Reflect.decorate(e4,t5,s4,i4);else for(var a3=e4.length-1;a3>=0;a3--)(r8=e4[a3])&&(o3=(n4<3?r8(o3):n4>3?r8(t5,s4,o3):r8(t5,s4))||o3);return n4>3&&o3&&Object.defineProperty(t5,s4,o3),o3},r7=this&&this.__param||function(e4,t5){return function(s4,i4){t5(s4,i4,e4)}};Object.defineProperty(t4,"__esModule",{value:!0}),t4.LogService=void 0,t4.setTraceLogger=function(e4){h2=e4},t4.traceCall=function(e4,t5,s4){if(typeof s4.value!="function")throw Error("not supported");let i4=s4.value;s4.value=function(...e5){if(h2.logLevel!==o2.LogLevelEnum.TRACE)return i4.apply(this,e5);h2.trace(`GlyphRenderer#${i4.name}(${e5.map((e6)=>JSON.stringify(e6)).join(", ")})`);let t6=i4.apply(this,e5);return h2.trace(`GlyphRenderer#${i4.name} return`,t6),t6}};let n3=s3(7150),o2=s3(6501),a2={trace:o2.LogLevelEnum.TRACE,debug:o2.LogLevelEnum.DEBUG,info:o2.LogLevelEnum.INFO,warn:o2.LogLevelEnum.WARN,error:o2.LogLevelEnum.ERROR,off:o2.LogLevelEnum.OFF},h2,c2=class extends n3.Disposable{get logLevel(){return this._logLevel}constructor(e4){super(),this._optionsService=e4,this._logLevel=o2.LogLevelEnum.OFF,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),h2=this}_updateLogLevel(){this._logLevel=a2[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e4){for(let t5=0;t5<e4.length;t5++)typeof e4[t5]=="function"&&(e4[t5]=e4[t5]())}_log(e4,t5,s4){this._evalLazyOptionalParams(s4),e4.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+t5,...s4)}trace(e4,...t5){this._logLevel<=o2.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e4,t5)}debug(e4,...t5){this._logLevel<=o2.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e4,t5)}info(e4,...t5){this._logLevel<=o2.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e4,t5)}warn(e4,...t5){this._logLevel<=o2.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e4,t5)}error(e4,...t5){this._logLevel<=o2.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e4,t5)}};t4.LogService=c2,t4.LogService=c2=i3([r7(0,o2.IOptionsService)],c2)},56:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.OptionsService=t4.DEFAULT_OPTIONS=void 0;let i3=s3(7150),r7=s3(701),n3=s3(802);t4.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1000,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:r7.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}};let o2=["normal","bold","100","200","300","400","500","600","700","800","900"];class a2 extends i3.Disposable{constructor(e4){super(),this._onOptionChange=this._register(new n3.Emitter),this.onOptionChange=this._onOptionChange.event;let s4={...t4.DEFAULT_OPTIONS};for(let t5 in e4)if(t5 in s4)try{let i4=e4[t5];s4[t5]=this._sanitizeAndValidateOption(t5,i4)}catch(e5){console.error(e5)}this.rawOptions=s4,this.options={...s4},this._setupOptions(),this._register((0,i3.toDisposable)(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e4,t5){return this.onOptionChange((s4)=>{s4===e4&&t5(this.rawOptions[e4])})}onMultipleOptionChange(e4,t5){return this.onOptionChange((s4)=>{e4.indexOf(s4)!==-1&&t5()})}_setupOptions(){let e4=(e5)=>{if(!(e5 in t4.DEFAULT_OPTIONS))throw Error(`No option with key "${e5}"`);return this.rawOptions[e5]},s4=(e5,s5)=>{if(!(e5 in t4.DEFAULT_OPTIONS))throw Error(`No option with key "${e5}"`);s5=this._sanitizeAndValidateOption(e5,s5),this.rawOptions[e5]!==s5&&(this.rawOptions[e5]=s5,this._onOptionChange.fire(e5))};for(let t5 in this.rawOptions){let i4={get:e4.bind(this,t5),set:s4.bind(this,t5)};Object.defineProperty(this.options,t5,i4)}}_sanitizeAndValidateOption(e4,s4){switch(e4){case"cursorStyle":if(s4||(s4=t4.DEFAULT_OPTIONS[e4]),!function(e5){return e5==="block"||e5==="underline"||e5==="bar"}(s4))throw Error(`"${s4}" is not a valid value for ${e4}`);break;case"wordSeparator":s4||(s4=t4.DEFAULT_OPTIONS[e4]);break;case"fontWeight":case"fontWeightBold":if(typeof s4=="number"&&1<=s4&&s4<=1000)break;s4=o2.includes(s4)?s4:t4.DEFAULT_OPTIONS[e4];break;case"cursorWidth":s4=Math.floor(s4);case"lineHeight":case"tabStopWidth":if(s4<1)throw Error(`${e4} cannot be less than 1, value: ${s4}`);break;case"minimumContrastRatio":s4=Math.max(1,Math.min(21,Math.round(10*s4)/10));break;case"scrollback":if((s4=Math.min(s4,4294967295))<0)throw Error(`${e4} cannot be less than 0, value: ${s4}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(s4<=0)throw Error(`${e4} cannot be less than or equal to 0, value: ${s4}`);break;case"rows":case"cols":if(!s4&&s4!==0)throw Error(`${e4} must be numeric, value: ${s4}`);break;case"windowsPty":s4=s4??{}}return s4}}t4.OptionsService=a2},8811:function(e3,t4,s3){var i3=this&&this.__decorate||function(e4,t5,s4,i4){var r8,n4=arguments.length,o3=n4<3?t5:i4===null?i4=Object.getOwnPropertyDescriptor(t5,s4):i4;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o3=Reflect.decorate(e4,t5,s4,i4);else for(var a2=e4.length-1;a2>=0;a2--)(r8=e4[a2])&&(o3=(n4<3?r8(o3):n4>3?r8(t5,s4,o3):r8(t5,s4))||o3);return n4>3&&o3&&Object.defineProperty(t5,s4,o3),o3},r7=this&&this.__param||function(e4,t5){return function(s4,i4){t5(s4,i4,e4)}};Object.defineProperty(t4,"__esModule",{value:!0}),t4.OscLinkService=void 0;let n3=s3(6501),o2=class{constructor(e4){this._bufferService=e4,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e4){let t5=this._bufferService.buffer;if(e4.id===void 0){let s5=t5.addMarker(t5.ybase+t5.y),i5={data:e4,id:this._nextId++,lines:[s5]};return s5.onDispose(()=>this._removeMarkerFromLink(i5,s5)),this._dataByLinkId.set(i5.id,i5),i5.id}let s4=e4,i4=this._getEntryIdKey(s4),r8=this._entriesWithId.get(i4);if(r8)return this.addLineToLink(r8.id,t5.ybase+t5.y),r8.id;let n4=t5.addMarker(t5.ybase+t5.y),o3={id:this._nextId++,key:this._getEntryIdKey(s4),data:s4,lines:[n4]};return n4.onDispose(()=>this._removeMarkerFromLink(o3,n4)),this._entriesWithId.set(o3.key,o3),this._dataByLinkId.set(o3.id,o3),o3.id}addLineToLink(e4,t5){let s4=this._dataByLinkId.get(e4);if(s4&&s4.lines.every((e5)=>e5.line!==t5)){let e5=this._bufferService.buffer.addMarker(t5);s4.lines.push(e5),e5.onDispose(()=>this._removeMarkerFromLink(s4,e5))}}getLinkData(e4){return this._dataByLinkId.get(e4)?.data}_getEntryIdKey(e4){return`${e4.id};;${e4.uri}`}_removeMarkerFromLink(e4,t5){let s4=e4.lines.indexOf(t5);s4!==-1&&(e4.lines.splice(s4,1),e4.lines.length===0&&(e4.data.id!==void 0&&this._entriesWithId.delete(e4.key),this._dataByLinkId.delete(e4.id)))}};t4.OscLinkService=o2,t4.OscLinkService=o2=i3([r7(0,n3.IBufferService)],o2)},6201:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.serviceRegistry=void 0,t4.getServiceDependencies=function(e4){return e4[i3]||[]},t4.createDecorator=function(e4){if(t4.serviceRegistry.has(e4))return t4.serviceRegistry.get(e4);let r7=function(e5,t5,n3){if(arguments.length!==3)throw Error("@IServiceName-decorator can only be used to decorate a parameter");(function(e6,t6,r8){t6[s3]===t6?t6[i3].push({id:e6,index:r8}):(t6[i3]=[{id:e6,index:r8}],t6[s3]=t6)})(r7,e5,n3)};return r7._id=e4,t4.serviceRegistry.set(e4,r7),r7};let s3="di$target",i3="di$dependencies";t4.serviceRegistry=new Map},6501:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.IDecorationService=t4.IUnicodeService=t4.IOscLinkService=t4.IOptionsService=t4.ILogService=t4.LogLevelEnum=t4.IInstantiationService=t4.ICharsetService=t4.ICoreService=t4.ICoreMouseService=t4.IBufferService=void 0;let i3=s3(6201);var r7;t4.IBufferService=(0,i3.createDecorator)("BufferService"),t4.ICoreMouseService=(0,i3.createDecorator)("CoreMouseService"),t4.ICoreService=(0,i3.createDecorator)("CoreService"),t4.ICharsetService=(0,i3.createDecorator)("CharsetService"),t4.IInstantiationService=(0,i3.createDecorator)("InstantiationService"),function(e4){e4[e4.TRACE=0]="TRACE",e4[e4.DEBUG=1]="DEBUG",e4[e4.INFO=2]="INFO",e4[e4.WARN=3]="WARN",e4[e4.ERROR=4]="ERROR",e4[e4.OFF=5]="OFF"}(r7||(t4.LogLevelEnum=r7={})),t4.ILogService=(0,i3.createDecorator)("LogService"),t4.IOptionsService=(0,i3.createDecorator)("OptionsService"),t4.IOscLinkService=(0,i3.createDecorator)("OscLinkService"),t4.IUnicodeService=(0,i3.createDecorator)("UnicodeService"),t4.IDecorationService=(0,i3.createDecorator)("DecorationService")},6415:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.UnicodeService=void 0;let i3=s3(7428),r7=s3(802);class n3{static extractShouldJoin(e4){return!!(1&e4)}static extractWidth(e4){return e4>>1&3}static extractCharKind(e4){return e4>>3}static createPropertyValue(e4,t5,s4=!1){return(16777215&e4)<<3|(3&t5)<<1|(s4?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new r7.Emitter,this.onChange=this._onChange.event;let e4=new i3.UnicodeV6;this.register(e4),this._active=e4.version,this._activeProvider=e4}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e4){if(!this._providers[e4])throw Error(`unknown Unicode version "${e4}"`);this._active=e4,this._activeProvider=this._providers[e4],this._onChange.fire(e4)}register(e4){this._providers[e4.version]=e4}wcwidth(e4){return this._activeProvider.wcwidth(e4)}getStringCellWidth(e4){let t5=0,s4=0,i4=e4.length;for(let r8=0;r8<i4;++r8){let o2=e4.charCodeAt(r8);if(55296<=o2&&o2<=56319){if(++r8>=i4)return t5+this.wcwidth(o2);let s5=e4.charCodeAt(r8);56320<=s5&&s5<=57343?o2=1024*(o2-55296)+s5-56320+65536:t5+=this.wcwidth(s5)}let a2=this.charProperties(o2,s4),h2=n3.extractWidth(a2);n3.extractShouldJoin(a2)&&(h2-=n3.extractWidth(s4)),t5+=h2,s4=a2}return t5}charProperties(e4,t5){return this._activeProvider.charProperties(e4,t5)}}t4.UnicodeService=n3},5856:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.Terminal=void 0;let i3=s3(6107),r7=s3(5777),n3=s3(802);class o2 extends r7.CoreTerminal{constructor(e4={}){super(e4),this._onBell=this._register(new n3.Emitter),this.onBell=this._onBell.event,this._onCursorMove=this._register(new n3.Emitter),this.onCursorMove=this._onCursorMove.event,this._onTitleChange=this._register(new n3.Emitter),this.onTitleChange=this._onTitleChange.event,this._onA11yCharEmitter=this._register(new n3.Emitter),this.onA11yChar=this._onA11yCharEmitter.event,this._onA11yTabEmitter=this._register(new n3.Emitter),this.onA11yTab=this._onA11yTabEmitter.event,this._setup(),this._register(this._inputHandler.onRequestBell(()=>this.bell())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(n3.Event.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(n3.Event.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(n3.Event.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(n3.Event.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter))}get buffer(){return this.buffers.active}get markers(){return this.buffer.markers}addMarker(e4){if(this.buffer===this.buffers.normal)return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e4)}bell(){this._onBell.fire()}input(e4,t5=!0){this.coreService.triggerDataEvent(e4,t5)}resize(e4,t5){e4===this.cols&&t5===this.rows||super.resize(e4,t5)}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e4=1;e4<this.rows;e4++)this.buffer.lines.push(this.buffer.getBlankLine(i3.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp})}}reset(){this.options.rows=this.rows,this.options.cols=this.cols,this._setup(),super.reset()}}t4.Terminal=o2},3058:(e3,t4,s3)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.Permutation=t4.CallbackIterable=t4.ArrayQueue=t4.booleanComparator=t4.numberComparator=t4.CompareResult=void 0,t4.tail=function(e4,t5=0){return e4[e4.length-(1+t5)]},t4.tail2=function(e4){if(e4.length===0)throw Error("Invalid tail call");return[e4.slice(0,e4.length-1),e4[e4.length-1]]},t4.equals=function(e4,t5,s4=(e5,t6)=>e5===t6){if(e4===t5)return!0;if(!e4||!t5)return!1;if(e4.length!==t5.length)return!1;for(let i4=0,r8=e4.length;i4<r8;i4++)if(!s4(e4[i4],t5[i4]))return!1;return!0},t4.removeFastWithoutKeepingOrder=function(e4,t5){let s4=e4.length-1;t5<s4&&(e4[t5]=e4[s4]),e4.pop()},t4.binarySearch=function(e4,t5,s4){return n3(e4.length,(i4)=>s4(e4[i4],t5))},t4.binarySearch2=n3,t4.quickSelect=function e4(t5,s4,i4){if((t5|=0)>=s4.length)throw TypeError("invalid index");let r8=s4[Math.floor(s4.length*Math.random())],n4=[],o3=[],a3=[];for(let e5 of s4){let t6=i4(e5,r8);t6<0?n4.push(e5):t6>0?o3.push(e5):a3.push(e5)}return t5<n4.length?e4(t5,n4,i4):t5<n4.length+a3.length?a3[0]:e4(t5-(n4.length+a3.length),o3,i4)},t4.groupBy=function(e4,t5){let s4=[],i4;for(let r8 of e4.slice(0).sort(t5))i4&&t5(i4[0],r8)===0?i4.push(r8):(i4=[r8],s4.push(i4));return s4},t4.groupAdjacentBy=function*(e4,t5){let s4,i4;for(let r8 of e4)i4!==void 0&&t5(i4,r8)?s4.push(r8):(s4&&(yield s4),s4=[r8]),i4=r8;s4&&(yield s4)},t4.forEachAdjacent=function(e4,t5){for(let s4=0;s4<=e4.length;s4++)t5(s4===0?void 0:e4[s4-1],s4===e4.length?void 0:e4[s4])},t4.forEachWithNeighbors=function(e4,t5){for(let s4=0;s4<e4.length;s4++)t5(s4===0?void 0:e4[s4-1],e4[s4],s4+1===e4.length?void 0:e4[s4+1])},t4.sortedDiff=o2,t4.delta=function(e4,t5,s4){let i4=o2(e4,t5,s4),r8=[],n4=[];for(let t6 of i4)r8.push(...e4.slice(t6.start,t6.start+t6.deleteCount)),n4.push(...t6.toInsert);return{removed:r8,added:n4}},t4.top=function(e4,t5,s4){if(s4===0)return[];let i4=e4.slice(0,s4).sort(t5);return a2(e4,t5,i4,s4,e4.length),i4},t4.topAsync=function(e4,t5,s4,r8,n4){return s4===0?Promise.resolve([]):new Promise((o3,h3)=>{(async()=>{let o4=e4.length,h4=e4.slice(0,s4).sort(t5);for(let c3=s4,l3=Math.min(s4+r8,o4);c3<o4;c3=l3,l3=Math.min(l3+r8,o4)){if(c3>s4&&await new Promise((e5)=>setTimeout(e5)),n4&&n4.isCancellationRequested)throw new i3.CancellationError;a2(e4,t5,h4,c3,l3)}return h4})().then(o3,h3)})},t4.coalesce=function(e4){return e4.filter((e5)=>!!e5)},t4.coalesceInPlace=function(e4){let t5=0;for(let s4=0;s4<e4.length;s4++)e4[s4]&&(e4[t5]=e4[s4],t5+=1);e4.length=t5},t4.move=function(e4,t5,s4){e4.splice(s4,0,e4.splice(t5,1)[0])},t4.isFalsyOrEmpty=function(e4){return!Array.isArray(e4)||e4.length===0},t4.isNonEmptyArray=function(e4){return Array.isArray(e4)&&e4.length>0},t4.distinct=function(e4,t5=(e5)=>e5){let s4=new Set;return e4.filter((e5)=>{let i4=t5(e5);return!s4.has(i4)&&(s4.add(i4),!0)})},t4.uniqueFilter=function(e4){let t5=new Set;return(s4)=>{let i4=e4(s4);return!t5.has(i4)&&(t5.add(i4),!0)}},t4.firstOrDefault=function(e4,t5){return e4.length>0?e4[0]:t5},t4.lastOrDefault=function(e4,t5){return e4.length>0?e4[e4.length-1]:t5},t4.commonPrefixLength=function(e4,t5,s4=(e5,t6)=>e5===t6){let i4=0;for(let r8=0,n4=Math.min(e4.length,t5.length);r8<n4&&s4(e4[r8],t5[r8]);r8++)i4++;return i4},t4.range=function(e4,t5){let s4=typeof t5=="number"?e4:0;typeof t5=="number"?s4=e4:(s4=0,t5=e4);let i4=[];if(s4<=t5)for(let e5=s4;e5<t5;e5++)i4.push(e5);else for(let e5=s4;e5>t5;e5--)i4.push(e5);return i4},t4.index=function(e4,t5,s4){return e4.reduce((e5,i4)=>(e5[t5(i4)]=s4?s4(i4):i4,e5),Object.create(null))},t4.insert=function(e4,t5){return e4.push(t5),()=>h2(e4,t5)},t4.remove=h2,t4.arrayInsert=function(e4,t5,s4){let i4=e4.slice(0,t5),r8=e4.slice(t5);return i4.concat(s4,r8)},t4.shuffle=function(e4,t5){let s4;if(typeof t5=="number"){let e5=t5;s4=()=>{let t6=179426549*Math.sin(e5++);return t6-Math.floor(t6)}}else s4=Math.random;for(let t6=e4.length-1;t6>0;t6-=1){let i4=Math.floor(s4()*(t6+1)),r8=e4[t6];e4[t6]=e4[i4],e4[i4]=r8}},t4.pushToStart=function(e4,t5){let s4=e4.indexOf(t5);s4>-1&&(e4.splice(s4,1),e4.unshift(t5))},t4.pushToEnd=function(e4,t5){let s4=e4.indexOf(t5);s4>-1&&(e4.splice(s4,1),e4.push(t5))},t4.pushMany=function(e4,t5){for(let s4 of t5)e4.push(s4)},t4.mapArrayOrNot=function(e4,t5){return Array.isArray(e4)?e4.map(t5):t5(e4)},t4.asArray=function(e4){return Array.isArray(e4)?e4:[e4]},t4.getRandomElement=function(e4){return e4[Math.floor(Math.random()*e4.length)]},t4.insertInto=c2,t4.splice=function(e4,t5,s4,i4){let r8=l2(e4,t5),n4=e4.splice(r8,s4);return n4===void 0&&(n4=[]),c2(e4,r8,i4),n4},t4.compareBy=function(e4,t5){return(s4,i4)=>t5(e4(s4),e4(i4))},t4.tieBreakComparators=function(...e4){return(t5,s4)=>{for(let i4 of e4){let e5=i4(t5,s4);if(!u2.isNeitherLessOrGreaterThan(e5))return e5}return u2.neitherLessOrGreaterThan}},t4.reverseOrder=function(e4){return(t5,s4)=>-e4(t5,s4)};let i3=s3(9807),r7=s3(8297);function n3(e4,t5){let s4=0,i4=e4-1;for(;s4<=i4;){let e5=(s4+i4)/2|0,r8=t5(e5);if(r8<0)s4=e5+1;else{if(!(r8>0))return e5;i4=e5-1}}return-(s4+1)}function o2(e4,t5,s4){let i4=[];function r8(e5,t6,s5){if(t6===0&&s5.length===0)return;let r9=i4[i4.length-1];r9&&r9.start+r9.deleteCount===e5?(r9.deleteCount+=t6,r9.toInsert.push(...s5)):i4.push({start:e5,deleteCount:t6,toInsert:s5})}let n4=0,o3=0;for(;;){if(n4===e4.length){r8(n4,0,t5.slice(o3));break}if(o3===t5.length){r8(n4,e4.length-n4,[]);break}let i5=e4[n4],a3=t5[o3],h3=s4(i5,a3);h3===0?(n4+=1,o3+=1):h3<0?(r8(n4,1,[]),n4+=1):h3>0&&(r8(n4,0,[a3]),o3+=1)}return i4}function a2(e4,t5,s4,i4,n4){for(let o3=s4.length;i4<n4;i4++){let n5=e4[i4];if(t5(n5,s4[o3-1])<0){s4.pop();let e5=(0,r7.findFirstIdxMonotonousOrArrLen)(s4,(e6)=>t5(n5,e6)<0);s4.splice(e5,0,n5)}}}function h2(e4,t5){let s4=e4.indexOf(t5);if(s4>-1)return e4.splice(s4,1),t5}function c2(e4,t5,s4){let i4=l2(e4,t5),r8=e4.length,n4=s4.length;e4.length=r8+n4;for(let t6=r8-1;t6>=i4;t6--)e4[t6+n4]=e4[t6];for(let t6=0;t6<n4;t6++)e4[t6+i4]=s4[t6]}function l2(e4,t5){return t5<0?Math.max(t5+e4.length,0):Math.min(t5,e4.length)}var u2;(function(e4){e4.isLessThan=function(e5){return e5<0},e4.isLessThanOrEqual=function(e5){return e5<=0},e4.isGreaterThan=function(e5){return e5>0},e4.isNeitherLessOrGreaterThan=function(e5){return e5===0},e4.greaterThan=1,e4.lessThan=-1,e4.neitherLessOrGreaterThan=0})(u2||(t4.CompareResult=u2={})),t4.numberComparator=(e4,t5)=>e4-t5,t4.booleanComparator=(e4,s4)=>(0,t4.numberComparator)(e4?1:0,s4?1:0),t4.ArrayQueue=class{constructor(e4){this.items=e4,this.firstIdx=0,this.lastIdx=this.items.length-1}get length(){return this.lastIdx-this.firstIdx+1}takeWhile(e4){let t5=this.firstIdx;for(;t5<this.items.length&&e4(this.items[t5]);)t5++;let s4=t5===this.firstIdx?null:this.items.slice(this.firstIdx,t5);return this.firstIdx=t5,s4}takeFromEndWhile(e4){let t5=this.lastIdx;for(;t5>=0&&e4(this.items[t5]);)t5--;let s4=t5===this.lastIdx?null:this.items.slice(t5+1,this.lastIdx+1);return this.lastIdx=t5,s4}peek(){if(this.length!==0)return this.items[this.firstIdx]}peekLast(){if(this.length!==0)return this.items[this.lastIdx]}dequeue(){let e4=this.items[this.firstIdx];return this.firstIdx++,e4}removeLast(){let e4=this.items[this.lastIdx];return this.lastIdx--,e4}takeCount(e4){let t5=this.items.slice(this.firstIdx,this.firstIdx+e4);return this.firstIdx+=e4,t5}};class d2{static{this.empty=new d2((e4)=>{})}constructor(e4){this.iterate=e4}forEach(e4){this.iterate((t5)=>(e4(t5),!0))}toArray(){let e4=[];return this.iterate((t5)=>(e4.push(t5),!0)),e4}filter(e4){return new d2((t5)=>this.iterate((s4)=>!e4(s4)||t5(s4)))}map(e4){return new d2((t5)=>this.iterate((s4)=>t5(e4(s4))))}some(e4){let t5=!1;return this.iterate((s4)=>(t5=e4(s4),!t5)),t5}findFirst(e4){let t5;return this.iterate((s4)=>!e4(s4)||(t5=s4,!1)),t5}findLast(e4){let t5;return this.iterate((s4)=>(e4(s4)&&(t5=s4),!0)),t5}findLastMaxBy(e4){let t5,s4=!0;return this.iterate((i4)=>((s4||u2.isGreaterThan(e4(i4,t5)))&&(s4=!1,t5=i4),!0)),t5}}t4.CallbackIterable=d2;class f2{constructor(e4){this._indexMap=e4}static createSortPermutation(e4,t5){let s4=Array.from(e4.keys()).sort((s5,i4)=>t5(e4[s5],e4[i4]));return new f2(s4)}apply(e4){return e4.map((t5,s4)=>e4[this._indexMap[s4]])}inverse(){let e4=this._indexMap.slice();for(let t5=0;t5<this._indexMap.length;t5++)e4[this._indexMap[t5]]=t5;return new f2(e4)}}t4.Permutation=f2},8297:(e3,t4)=>{function s3(e4,t5,s4=e4.length-1){for(let i4=s4;i4>=0;i4--)if(t5(e4[i4]))return i4;return-1}function i3(e4,t5,s4=0,i4=e4.length){let r8=s4,n4=i4;for(;r8<n4;){let s5=Math.floor((r8+n4)/2);t5(e4[s5])?r8=s5+1:n4=s5}return r8-1}function r7(e4,t5,s4=0,i4=e4.length){let r8=s4,n4=i4;for(;r8<n4;){let s5=Math.floor((r8+n4)/2);t5(e4[s5])?n4=s5:r8=s5+1}return r8}Object.defineProperty(t4,"__esModule",{value:!0}),t4.MonotonousArray=void 0,t4.findLast=function(e4,t5){let i4=s3(e4,t5);if(i4!==-1)return e4[i4]},t4.findLastIdx=s3,t4.findLastMonotonous=function(e4,t5){let s4=i3(e4,t5);return s4===-1?void 0:e4[s4]},t4.findLastIdxMonotonous=i3,t4.findFirstMonotonous=function(e4,t5){let s4=r7(e4,t5);return s4===e4.length?void 0:e4[s4]},t4.findFirstIdxMonotonousOrArrLen=r7,t4.findFirstIdxMonotonous=function(e4,t5,s4=0,i4=e4.length){let n4=r7(e4,t5,s4,i4);return n4===e4.length?-1:n4},t4.findFirstMax=o2,t4.findLastMax=function(e4,t5){if(e4.length===0)return;let s4=e4[0];for(let i4=1;i4<e4.length;i4++){let r8=e4[i4];t5(r8,s4)>=0&&(s4=r8)}return s4},t4.findFirstMin=function(e4,t5){return o2(e4,(e5,s4)=>-t5(e5,s4))},t4.findMaxIdx=function(e4,t5){if(e4.length===0)return-1;let s4=0;for(let i4=1;i4<e4.length;i4++)t5(e4[i4],e4[s4])>0&&(s4=i4);return s4},t4.mapFindFirst=function(e4,t5){for(let s4 of e4){let e5=t5(s4);if(e5!==void 0)return e5}};class n3{static{this.assertInvariants=!1}constructor(e4){this._array=e4,this._findLastMonotonousLastIdx=0}findLastMonotonous(e4){if(n3.assertInvariants){if(this._prevFindLastPredicate){for(let t6 of this._array)if(this._prevFindLastPredicate(t6)&&!e4(t6))throw Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=e4}let t5=i3(this._array,e4,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=t5+1,t5===-1?void 0:this._array[t5]}}function o2(e4,t5){if(e4.length===0)return;let s4=e4[0];for(let i4=1;i4<e4.length;i4++){let r8=e4[i4];t5(r8,s4)>0&&(s4=r8)}return s4}t4.MonotonousArray=n3},9087:(e3,t4)=>{var s3;Object.defineProperty(t4,"__esModule",{value:!0}),t4.SetWithKey=void 0,t4.groupBy=function(e4,t5){let s4=Object.create(null);for(let i4 of e4){let e5=t5(i4),r7=s4[e5];r7||(r7=s4[e5]=[]),r7.push(i4)}return s4},t4.diffSets=function(e4,t5){let s4=[],i4=[];for(let i5 of e4)t5.has(i5)||s4.push(i5);for(let s5 of t5)e4.has(s5)||i4.push(s5);return{removed:s4,added:i4}},t4.diffMaps=function(e4,t5){let s4=[],i4=[];for(let[i5,r7]of e4)t5.has(i5)||s4.push(r7);for(let[s5,r7]of t5)e4.has(s5)||i4.push(r7);return{removed:s4,added:i4}},t4.intersection=function(e4,t5){let s4=new Set;for(let i4 of t5)e4.has(i4)&&s4.add(i4);return s4};class i3{static{s3=Symbol.toStringTag}constructor(e4,t5){this.toKey=t5,this._map=new Map,this[s3]="SetWithKey";for(let t6 of e4)this.add(t6)}get size(){return this._map.size}add(e4){let t5=this.toKey(e4);return this._map.set(t5,e4),this}delete(e4){return this._map.delete(this.toKey(e4))}has(e4){return this._map.has(this.toKey(e4))}*entries(){for(let e4 of this._map.values())yield[e4,e4]}keys(){return this.values()}*values(){for(let e4 of this._map.values())yield e4}clear(){this._map.clear()}forEach(e4,t5){this._map.forEach((s4)=>e4.call(t5,s4,s4,this))}[Symbol.iterator](){return this.values()}}t4.SetWithKey=i3},9807:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.BugIndicatingError=t4.ErrorNoTelemetry=t4.ExpectedError=t4.NotSupportedError=t4.NotImplementedError=t4.ReadonlyError=t4.CancellationError=t4.errorHandler=t4.ErrorHandler=void 0,t4.setUnexpectedErrorHandler=function(e4){t4.errorHandler.setUnexpectedErrorHandler(e4)},t4.isSigPipeError=function(e4){if(!e4||typeof e4!="object")return!1;let t5=e4;return t5.code==="EPIPE"&&t5.syscall?.toUpperCase()==="WRITE"},t4.onUnexpectedError=function(e4){r7(e4)||t4.errorHandler.onUnexpectedError(e4)},t4.onUnexpectedExternalError=function(e4){r7(e4)||t4.errorHandler.onUnexpectedExternalError(e4)},t4.transformErrorForSerialization=function(e4){if(e4 instanceof Error){let{name:t5,message:s4}=e4;return{$isError:!0,name:t5,message:s4,stack:e4.stacktrace||e4.stack,noTelemetry:l2.isErrorNoTelemetry(e4)}}return e4},t4.transformErrorFromSerialization=function(e4){let t5;return e4.noTelemetry?t5=new l2:(t5=Error(),t5.name=e4.name),t5.message=e4.message,t5.stack=e4.stack,t5},t4.isCancellationError=r7,t4.canceled=function(){let e4=Error(i3);return e4.name=e4.message,e4},t4.illegalArgument=function(e4){return e4?Error(`Illegal argument: ${e4}`):Error("Illegal argument")},t4.illegalState=function(e4){return e4?Error(`Illegal state: ${e4}`):Error("Illegal state")},t4.getErrorMessage=function(e4){return e4?e4.message?e4.message:e4.stack?e4.stack.split(`
4
4
  `)[0]:String(e4):"Error"};class s3{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e4){setTimeout(()=>{if(e4.stack){if(l2.isErrorNoTelemetry(e4))throw new l2(e4.message+`
5
5
 
@@ -26,7 +26,7 @@ ${i4.join(`
26
26
 
27
27
  `),{leaks:s4,details:h3}}}function l2(e4){return h2?.trackDisposable(e4),e4}function u2(e4){h2?.markAsDisposed(e4)}function d2(e4,t5){h2?.setParent(e4,t5)}function f2(e4){return typeof e4=="object"&&e4!==null&&typeof e4.dispose=="function"&&e4.dispose.length===0}function _4(e4){if(a2.Iterable.is(e4)){let t5=[];for(let s4 of e4)if(s4)try{s4.dispose()}catch(e5){t5.push(e5)}if(t5.length===1)throw t5[0];if(t5.length>1)throw AggregateError(t5,"Encountered errors while disposing of store");return Array.isArray(e4)?[]:e4}if(e4)return e4.dispose(),e4}function p3(e4){let t5=l2({dispose:(0,o2.createSingleCallFunction)(()=>{u2(t5),e4()})});return t5}t4.DisposableTracker=c2;class g3{static{this.DISABLE_DISPOSED_WARNING=!1}constructor(){this._toDispose=new Set,this._isDisposed=!1,l2(this)}dispose(){this._isDisposed||(u2(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{_4(this._toDispose)}finally{this._toDispose.clear()}}add(e4){if(!e4)return e4;if(e4===this)throw Error("Cannot register a disposable on itself!");return d2(e4,this),this._isDisposed?g3.DISABLE_DISPOSED_WARNING||console.warn(Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(e4),e4}delete(e4){if(e4){if(e4===this)throw Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e4),e4.dispose()}}deleteAndLeak(e4){e4&&this._toDispose.has(e4)&&(this._toDispose.delete(e4),d2(e4,null))}}t4.DisposableStore=g3;class v3{static{this.None=Object.freeze({dispose(){}})}constructor(){this._store=new g3,l2(this),d2(this._store,this)}dispose(){u2(this),this._store.dispose()}_register(e4){if(e4===this)throw Error("Cannot register a disposable on itself!");return this._store.add(e4)}}t4.Disposable=v3;class m3{constructor(){this._isDisposed=!1,l2(this)}get value(){return this._isDisposed?void 0:this._value}set value(e4){this._isDisposed||e4===this._value||(this._value?.dispose(),e4&&d2(e4,this),this._value=e4)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,u2(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e4=this._value;return this._value=void 0,e4&&d2(e4,null),e4}}t4.MutableDisposable=m3,t4.MandatoryMutableDisposable=class{constructor(e4){this._disposable=new m3,this._isDisposed=!1,this._disposable.value=e4}get value(){return this._disposable.value}set value(e4){this._isDisposed||e4===this._disposable.value||(this._disposable.value=e4)}dispose(){this._isDisposed=!0,this._disposable.dispose()}},t4.RefCountedDisposable=class{constructor(e4){this._disposable=e4,this._counter=1}acquire(){return this._counter++,this}release(){return--this._counter==0&&this._disposable.dispose(),this}},t4.SafeDisposable=class{constructor(){this.dispose=()=>{},this.unset=()=>{},this.isset=()=>!1,l2(this)}set(e4){let t5=e4;return this.unset=()=>t5=void 0,this.isset=()=>t5!==void 0,this.dispose=()=>{t5&&(t5(),t5=void 0,u2(this))},this}},t4.ReferenceCollection=class{constructor(){this.references=new Map}acquire(e4,...t5){let s4=this.references.get(e4);s4||(s4={counter:0,object:this.createReferencedObject(e4,...t5)},this.references.set(e4,s4));let{object:i4}=s4,r8=(0,o2.createSingleCallFunction)(()=>{--s4.counter==0&&(this.destroyReferencedObject(e4,s4.object),this.references.delete(e4))});return s4.counter++,{object:i4,dispose:r8}}},t4.AsyncReferenceCollection=class{constructor(e4){this.referenceCollection=e4}async acquire(e4,...t5){let s4=this.referenceCollection.acquire(e4,...t5);try{return{object:await s4.object,dispose:()=>s4.dispose()}}catch(e5){throw s4.dispose(),e5}}},t4.ImmortalReference=class{constructor(e4){this.object=e4}dispose(){}};class b3{constructor(){this._store=new Map,this._isDisposed=!1,l2(this)}dispose(){u2(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{_4(this._store.values())}finally{this._store.clear()}}has(e4){return this._store.has(e4)}get size(){return this._store.size}get(e4){return this._store.get(e4)}set(e4,t5,s4=!1){this._isDisposed&&console.warn(Error("Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!").stack),s4||this._store.get(e4)?.dispose(),this._store.set(e4,t5)}deleteAndDispose(e4){this._store.get(e4)?.dispose(),this._store.delete(e4)}deleteAndLeak(e4){let t5=this._store.get(e4);return this._store.delete(e4),t5}keys(){return this._store.keys()}values(){return this._store.values()}[Symbol.iterator](){return this._store[Symbol.iterator]()}}t4.DisposableMap=b3},6317:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.LinkedList=void 0;class s3{static{this.Undefined=new s3(void 0)}constructor(e4){this.element=e4,this.next=s3.Undefined,this.prev=s3.Undefined}}class i3{constructor(){this._first=s3.Undefined,this._last=s3.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===s3.Undefined}clear(){let e4=this._first;for(;e4!==s3.Undefined;){let t5=e4.next;e4.prev=s3.Undefined,e4.next=s3.Undefined,e4=t5}this._first=s3.Undefined,this._last=s3.Undefined,this._size=0}unshift(e4){return this._insert(e4,!1)}push(e4){return this._insert(e4,!0)}_insert(e4,t5){let i4=new s3(e4);if(this._first===s3.Undefined)this._first=i4,this._last=i4;else if(t5){let e5=this._last;this._last=i4,i4.prev=e5,e5.next=i4}else{let e5=this._first;this._first=i4,i4.next=e5,e5.prev=i4}this._size+=1;let r7=!1;return()=>{r7||(r7=!0,this._remove(i4))}}shift(){if(this._first!==s3.Undefined){let e4=this._first.element;return this._remove(this._first),e4}}pop(){if(this._last!==s3.Undefined){let e4=this._last.element;return this._remove(this._last),e4}}_remove(e4){if(e4.prev!==s3.Undefined&&e4.next!==s3.Undefined){let t5=e4.prev;t5.next=e4.next,e4.next.prev=t5}else e4.prev===s3.Undefined&&e4.next===s3.Undefined?(this._first=s3.Undefined,this._last=s3.Undefined):e4.next===s3.Undefined?(this._last=this._last.prev,this._last.next=s3.Undefined):e4.prev===s3.Undefined&&(this._first=this._first.next,this._first.prev=s3.Undefined);this._size-=1}*[Symbol.iterator](){let e4=this._first;for(;e4!==s3.Undefined;)yield e4.element,e4=e4.next}}t4.LinkedList=i3},2608:(e3,t4)=>{var s3;Object.defineProperty(t4,"__esModule",{value:!0}),t4.SetMap=t4.BidirectionalMap=t4.CounterSet=t4.Touch=void 0,t4.getOrSet=function(e4,t5,s4){let i3=e4.get(t5);return i3===void 0&&(i3=s4,e4.set(t5,i3)),i3},t4.mapToString=function(e4){let t5=[];return e4.forEach((e5,s4)=>{t5.push(`${s4} => ${e5}`)}),`Map(${e4.size}) {${t5.join(", ")}}`},t4.setToString=function(e4){let t5=[];return e4.forEach((e5)=>{t5.push(e5)}),`Set(${e4.size}) {${t5.join(", ")}}`},t4.mapsStrictEqualIgnoreOrder=function(e4,t5){if(e4===t5)return!0;if(e4.size!==t5.size)return!1;for(let[s4,i3]of e4)if(!t5.has(s4)||t5.get(s4)!==i3)return!1;for(let[s4]of t5)if(!e4.has(s4))return!1;return!0},function(e4){e4[e4.None=0]="None",e4[e4.AsOld=1]="AsOld",e4[e4.AsNew=2]="AsNew"}(s3||(t4.Touch=s3={})),t4.CounterSet=class{constructor(){this.map=new Map}add(e4){return this.map.set(e4,(this.map.get(e4)||0)+1),this}delete(e4){let t5=this.map.get(e4)||0;return t5!==0&&(t5--,t5===0?this.map.delete(e4):this.map.set(e4,t5),!0)}has(e4){return this.map.has(e4)}},t4.BidirectionalMap=class{constructor(e4){if(this._m1=new Map,this._m2=new Map,e4)for(let[t5,s4]of e4)this.set(t5,s4)}clear(){this._m1.clear(),this._m2.clear()}set(e4,t5){this._m1.set(e4,t5),this._m2.set(t5,e4)}get(e4){return this._m1.get(e4)}getKey(e4){return this._m2.get(e4)}delete(e4){let t5=this._m1.get(e4);return t5!==void 0&&(this._m1.delete(e4),this._m2.delete(t5),!0)}forEach(e4,t5){this._m1.forEach((s4,i3)=>{e4.call(t5,s4,i3,this)})}keys(){return this._m1.keys()}values(){return this._m1.values()}},t4.SetMap=class{constructor(){this.map=new Map}add(e4,t5){let s4=this.map.get(e4);s4||(s4=new Set,this.map.set(e4,s4)),s4.add(t5)}delete(e4,t5){let s4=this.map.get(e4);s4&&(s4.delete(t5),s4.size===0&&this.map.delete(e4))}forEach(e4,t5){let s4=this.map.get(e4);s4&&s4.forEach(t5)}get(e4){return this.map.get(e4)||new Set}}},9725:(e3,t4)=>{Object.defineProperty(t4,"__esModule",{value:!0}),t4.StopWatch=void 0;let s3=globalThis.performance&&typeof globalThis.performance.now=="function";class i3{static create(e4){return new i3(e4)}constructor(e4){this._now=s3&&e4===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}}t4.StopWatch=i3}},t3={};function s2(i3){var r7=t3[i3];if(r7!==void 0)return r7.exports;var n3=t3[i3]={exports:{}};return e2[i3].call(n3.exports,n3,n3.exports,s2),n3.exports}var i2={};(()=>{var e3=i2;Object.defineProperty(e3,"__esModule",{value:!0}),e3.Terminal=void 0;let t4=s2(5101),r7=s2(6097),n3=s2(4335),o2=s2(5856),a2=s2(3027),h2=s2(7150),c2=["cols","rows"];class l2 extends h2.Disposable{constructor(e4){super(),this._core=this._register(new o2.Terminal(e4)),this._addonManager=this._register(new a2.AddonManager),this._publicOptions={...this._core.options};let t5=(e5)=>this._core.options[e5],s3=(e5,t6)=>{this._checkReadonlyOptions(e5),this._core.options[e5]=t6};for(let e5 in this._core.options){Object.defineProperty(this._publicOptions,e5,{get:()=>this._core.options[e5],set:(t6)=>{this._checkReadonlyOptions(e5),this._core.options[e5]=t6}});let i3={get:t5.bind(this,e5),set:s3.bind(this,e5)};Object.defineProperty(this._publicOptions,e5,i3)}}_checkReadonlyOptions(e4){if(c2.includes(e4))throw Error(`Option "${e4}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.options.allowProposedApi)throw Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onLineFeed(){return this._core.onLineFeed}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get parser(){return this._checkProposedApi(),this._parser||(this._parser=new r7.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new n3.UnicodeApi(this._core)}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._checkProposedApi(),this._buffer||(this._buffer=this._register(new t4.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e4=this._core.coreService.decPrivateModes,t5="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t5="x10";break;case"VT200":t5="vt200";break;case"DRAG":t5="drag";break;case"ANY":t5="any"}return{applicationCursorKeysMode:e4.applicationCursorKeys,applicationKeypadMode:e4.applicationKeypad,bracketedPasteMode:e4.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t5,originMode:e4.origin,reverseWraparoundMode:e4.reverseWraparound,sendFocusMode:e4.sendFocus,synchronizedOutputMode:e4.synchronizedOutput,wraparoundMode:e4.wraparound}}get options(){return this._publicOptions}set options(e4){for(let t5 in e4)this._publicOptions[t5]=e4[t5]}input(e4,t5=!0){this._core.input(e4,t5)}resize(e4,t5){this._verifyIntegers(e4,t5),this._core.resize(e4,t5)}registerMarker(e4=0){return this._checkProposedApi(),this._verifyIntegers(e4),this._core.addMarker(e4)}addMarker(e4){return this.registerMarker(e4)}dispose(){super.dispose()}scrollLines(e4){this._verifyIntegers(e4),this._core.scrollLines(e4)}scrollPages(e4){this._verifyIntegers(e4),this._core.scrollPages(e4)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e4){this._verifyIntegers(e4),this._core.scrollToLine(e4)}clear(){this._core.clear()}write(e4,t5){this._core.write(e4,t5)}writeln(e4,t5){this._core.write(e4),this._core.write(`\r
28
28
  `,t5)}reset(){this._core.reset()}loadAddon(e4){this._addonManager.loadAddon(this,e4)}_verifyIntegers(...e4){for(let t5 of e4)if(t5===1/0||isNaN(t5)||t5%1!=0)throw Error("This API only accepts integers")}}e3.Terminal=l2})();var r6=exports;for(var n2 in i2)r6[n2]=i2[n2];i2.__esModule&&Object.defineProperty(r6,"__esModule",{value:!0})})()});var REPLY=/\x1b\[6;(\d+);(\d+)t/,DA1=/\x1b\[\?[\d;]*c/;function parseCellPixelReply(text){let match=REPLY.exec(text);if(!match)return null;let height=Number(match[1]),width=Number(match[2]);if(!(width>0&&height>0))return null;return{width,height}}async function queryCellPixelSize(opts){let{stdin,stdout}=opts,setRawMode=stdin.setRawMode;if(!stdin.isTTY||!stdout.isTTY||typeof setRawMode!=="function")return null;let wasRaw=stdin.isRaw===!0,wasPaused=stdin.isPaused();return await new Promise((resolve)=>{let seen="",settled=!1,onData=(chunk)=>{seen+=typeof chunk==="string"?chunk:chunk.toString("latin1");let parsed=parseCellPixelReply(seen);if(parsed||REPLY.test(seen)||DA1.test(seen))finish(parsed)},finish=(result)=>{if(settled)return;settled=!0,clearTimeout(timer),stdin.off("data",onData);try{setRawMode.call(stdin,wasRaw)}catch{}if(wasPaused)stdin.pause();resolve(result)},timer=setTimeout(()=>finish(null),opts.timeoutMs??120);if(typeof timer==="object"&&"unref"in timer)timer.unref();stdin.on("data",onData);try{setRawMode.call(stdin,!0)}catch{finish(null);return}stdin.resume(),stdout.write("\x1B[16t\x1B[c")})}function outerTerminalDrawsKittyPlaceholders(env){if(env.TMUX||env.STY||env.ZELLIJ)return!1;return env.TERM_PROGRAM==="ghostty"||env.TERM==="xterm-ghostty"||env.TERM==="xterm-kitty"||!!env.GHOSTTY_RESOURCES_DIR||!!env.KITTY_WINDOW_ID}function createTerminalGraphics(opts){let kitty=opts.stdoutIsTTY&&outerTerminalDrawsKittyPlaceholders(opts.env);return{cellPixelSize:opts.cellPixelSize,writeKitty:kitty?opts.write:null}}var current=null;function installTerminalGraphics(graphics){current=graphics}function terminalGraphics(){return current}function terminalDrawsKitty(){return current?.writeKitty!=null}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
29
- `,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 resolveSessionShell()}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 RoveDaemonClient(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}var machineClients=new Map;function getMachinePtyClient(machine){let cached=machineClients.get(machine);if(cached)return cached;let p3=(async()=>{let{machinePtySocket}=await import("./chunk-j9tsdn1d.js"),client=new RoveDaemonClient(await machinePtySocket(machine));return await client.connect(),installDispatch(client),client.onLifecycle("close",()=>{if(machineClients.get(machine)===p3)machineClients.delete(machine)}),client})();return p3.catch(()=>{if(machineClients.get(machine)===p3)machineClients.delete(machine)}),machineClients.set(machine,p3),p3}function peekSharedPtyClient(){return shared}function warmHostedShell(cwd,shell=defaultShell()){if((process.env.ROVE_TERMINAL_BACKEND??"hosted")!=="hosted")return;getSharedPtyClient().then((client)=>client.request("pty.warm",{cwd,shell})).catch(()=>{})}var ue=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],qe=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],A3;function He(r2,e2){let t3=0,n2=e2.length-1,o2;if(r2<e2[0][0]||r2>e2[n2][1])return!1;for(;n2>=t3;)if(o2=t3+n2>>1,r2>e2[o2][1])t3=o2+1;else if(r2<e2[o2][0])n2=o2-1;else return!0;return!1}var H2=class{constructor(){if(this.version="6",!A3){A3=new Uint8Array(65536),A3.fill(1),A3[0]=0,A3.fill(0,1,32),A3.fill(0,127,160),A3.fill(2,4352,4448),A3[9001]=2,A3[9002]=2,A3.fill(2,11904,42192),A3[12351]=1,A3.fill(2,44032,55204),A3.fill(2,63744,64256),A3.fill(2,65040,65050),A3.fill(2,65072,65136),A3.fill(2,65280,65377),A3.fill(2,65504,65511);for(let e2=0;e2<ue.length;++e2)A3.fill(0,ue[e2][0],ue[e2][1]+1)}}wcwidth(e2){return e2<32?0:e2<127?1:e2<65536?A3[e2]:He(e2,qe)?0:e2>=131072&&e2<=196605||e2>=196608&&e2<=262141?2:1}charProperties(e2,t3){let n2=this.wcwidth(e2),o2=n2===0&&t3!==0;if(o2){let d2=w3.extractWidth(t3);d2===0?o2=!1:d2>n2&&(n2=d2)}return w3.createPropertyValue(0,n2,o2)}},de=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e2){setTimeout(()=>{throw e2.stack?J2.isErrorNoTelemetry(e2)?new J2(e2.message+`
29
+ `,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 resolveSessionShell()}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 RoveDaemonClient(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}var machineClients=new Map;function getMachinePtyClient(machine){let cached=machineClients.get(machine);if(cached)return cached;let p3=(async()=>{let{machinePtySocket}=await import("./chunk-j30488hn.js"),client=new RoveDaemonClient(await machinePtySocket(machine));return await client.connect(),installDispatch(client),client.onLifecycle("close",()=>{if(machineClients.get(machine)===p3)machineClients.delete(machine)}),client})();return p3.catch(()=>{if(machineClients.get(machine)===p3)machineClients.delete(machine)}),machineClients.set(machine,p3),p3}function peekSharedPtyClient(){return shared}function warmHostedShell(cwd,shell=defaultShell()){if((process.env.ROVE_TERMINAL_BACKEND??"hosted")!=="hosted")return;getSharedPtyClient().then((client)=>client.request("pty.warm",{cwd,shell})).catch(()=>{})}var ue=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],qe=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],A3;function He(r2,e2){let t3=0,n2=e2.length-1,o2;if(r2<e2[0][0]||r2>e2[n2][1])return!1;for(;n2>=t3;)if(o2=t3+n2>>1,r2>e2[o2][1])t3=o2+1;else if(r2<e2[o2][0])n2=o2-1;else return!0;return!1}var H2=class{constructor(){if(this.version="6",!A3){A3=new Uint8Array(65536),A3.fill(1),A3[0]=0,A3.fill(0,1,32),A3.fill(0,127,160),A3.fill(2,4352,4448),A3[9001]=2,A3[9002]=2,A3.fill(2,11904,42192),A3[12351]=1,A3.fill(2,44032,55204),A3.fill(2,63744,64256),A3.fill(2,65040,65050),A3.fill(2,65072,65136),A3.fill(2,65280,65377),A3.fill(2,65504,65511);for(let e2=0;e2<ue.length;++e2)A3.fill(0,ue[e2][0],ue[e2][1]+1)}}wcwidth(e2){return e2<32?0:e2<127?1:e2<65536?A3[e2]:He(e2,qe)?0:e2>=131072&&e2<=196605||e2>=196608&&e2<=262141?2:1}charProperties(e2,t3){let n2=this.wcwidth(e2),o2=n2===0&&t3!==0;if(o2){let d2=w3.extractWidth(t3);d2===0?o2=!1:d2>n2&&(n2=d2)}return w3.createPropertyValue(0,n2,o2)}},de=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e2){setTimeout(()=>{throw e2.stack?J2.isErrorNoTelemetry(e2)?new J2(e2.message+`
30
30
 
31
31
  `+e2.stack):Error(e2.message+`
32
32
 
@@ -61,14 +61,14 @@ ${D3.join(`
61
61
  `);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:TextAttributes11.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(`
62
62
  `)})]},stream.label))]})}function RunHistory(props){let{theme}=useTheme(),t3=useT(),runs=props.runs;return $jsxs($Fragment,{children:[$jsx("text",{attributes:TextAttributes11.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)=>{let pending=routineRunResponseState(run,props.now),note=pending==="awaiting"?` \xB7 ${t3("automations.responseAwaiting")}`:pending==="missing"?` \xB7 ${t3("automations.responseMissing")}`:"";return $jsx("text",{fg:pending==="missing"?theme.warning:runToneColor(run.status,theme),children:`${triggerGlyph(run.trigger)} #${run.runNumber} ${formatRunStatus(run.status,t3)}${run.tabId?` \xB7 ${run.tabId}`:""}${run.error?` \u2014 ${run.error}`:""}${note} ${formatWhen(run.at,props.now)}`},run.id)}),$jsx(PrecheckDetail,{run:runs[0]})]})}function RunResponses(props){let{theme}=useTheme(),t3=useT(),answered=props.runs.filter((run)=>run.response);return $jsxs($Fragment,{children:[$jsx("text",{attributes:TextAttributes11.BOLD,fg:theme.text,flexShrink:0,children:t3("automations.responses")}),answered.length===0?$jsx("text",{fg:theme.textMuted,children:t3("automations.noResponses")}):$jsx("scrollbox",{flexGrow:1,flexShrink:1,flexBasis:0,children:answered.map((run)=>$jsxs("box",{flexDirection:"column",marginBottom:1,flexShrink:0,children:[$jsx("text",{fg:runToneColor(run.status,theme),wrapMode:"none",children:`#${run.runNumber} ${formatRunStatus(run.status,t3)} \xB7 ${formatWhen(run.response?.at,props.now)}`}),$jsx(MarkdownText,{content:run.response?.text??""})]},run.id))})]})}var POLL_MS2=5000;function repoLabel(repo){return pathSyntax(repo).basename(repo)||repo}function AutomationsPage(props){let{theme}=useTheme(),dialog=useDialog(),t3=useT(),dims=useTerminalSize(),notif=useNotifications();function notifyError(message){notif.notify({kind:"error",taskId:"",tabId:"",title:message})}let[automations,setAutomations]=import_react18.useState(null),[keepsDaemonAlive,setKeepsDaemonAlive]=import_react18.useState(!1),[lastRunStatus,setLastRunStatus]=import_react18.useState({}),[lastFailure,setLastFailure]=import_react18.useState({}),[runs,setRuns]=import_react18.useState([]),[reloadTick,setReloadTick]=import_react18.useState(0),[busyId,setBusyId]=import_react18.useState(null),[notice,setNotice]=import_react18.useState(null),refetch=()=>setReloadTick((tick)=>tick+1);import_react18.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??{}),setLastFailure(result.lastFailure??{})}).catch(()=>{if(!disposed)setAutomations((prev)=>prev??[])})};load();let timer=setInterval(load,POLL_MS2);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_react18.useState(0);import_react18.useEffect(()=>{setCursor((c2)=>clampCursor2(c2,rows.length))},[rows.length]);let selected=rows[cursor],follow=useCursorFollow3(cursor);import_react18.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_react18.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().filter((task)=>!isNoProjectTask(task)).map((task)=>task.repo)])].filter(Boolean),draft=await AutomationComposer.show(dialog,{repos,tasks:orch.listTasks().filter((task)=>!task.deletion),...props.focusRepo?{defaultRepo:props.focusRepo}:{}});if(!draft)return;setBusyId("new");try{let{repo,...rest}=draft;await orch.createAutomation(repo===null?rest:{...rest,repo}),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)=>clampCursor2(c2+1,rows.length))},{key:"down",cmd:()=>setCursor((c2)=>clampCursor2(c2+1,rows.length))},{key:"k",cmd:()=>setCursor((c2)=>clampCursor2(c2-1,rows.length))},{key:"up",cmd:()=>setCursor((c2)=>clampCursor2(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:TextAttributes12.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?TextAttributes12.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:`${automation.repo?repoLabel(automation.repo):t3("automations.noProject")} \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:"row",marginTop:1,...FRAME,borderColor:theme.border,padding:1,gap:2,...selected?{flexGrow:1,flexShrink:1,flexBasis:0}:{flexShrink:0},children:selected?$jsxs($Fragment,{children:[$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,flexBasis:0,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:TextAttributes12.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,lastFailure[selected.id]?$jsx("text",{fg:theme.warning,wrapMode:"word",children:t3("automations.lastFailed",{when:formatWhen(lastFailure[selected.id]?.at,now),reason:lastFailure[selected.id]?.reason??""})}):null,$jsx(RunHistory,{runs,now})]}),$jsx("box",{flexDirection:"column",flexGrow:1,flexShrink:1,flexBasis:0,children:$jsx(RunResponses,{runs,now})})]}):$jsx("text",{fg:theme.textMuted,children:t3("automations.noSelection")})}),notice?$jsx("text",{fg:theme.textMuted,children:notice}):null]})}function RoutinesRailPage(props){return $jsx(AutomationsPage,{orchestrator:props.orchestrator,focused:props.focused,...props.selectedTask?{focusRepo:props.selectedTask.repo}:{},onClose:props.onClose,onOpenTask:props.onOpenTask})}var CORE_PAGES=[{id:"automations",title:()=>t("tasks.nav.automations"),order:20,action:"automations.open",component:RoutinesRailPage}];function registerCorePages(){setPageSource("core",CORE_PAGES)}import{existsSync}from"fs";import{resolve,sep}from"path";import{pathToFileURL}from"url";var PAGE_ACTIONS=["kanban.open","automations.open","workItems.open"];function isPageAction(value){return PAGE_ACTIONS.includes(value)}function focusPaneForNav(nav){return nav==="terminal"?"sidebar":"workspace"}var runtimeReady=!1;async function ensureSharedRuntime(){if(runtimeReady)return;let{ensureRuntimePluginSupport}=await import("./chunk-r7tbzgt7.js");ensureRuntimePluginSupport(),runtimeReady=!0}async function importPage(root,entry2){let path=resolve(root,entry2);if(!path.startsWith(`${resolve(root)}${sep}`))throw Error(`entry \`${entry2}\` is outside the plugin`);if(!existsSync(path))throw Error(`entry \`${entry2}\` does not exist`);await ensureSharedRuntime();let mod=await import(pathToFileURL(path).href);if(typeof mod.default!=="function")throw Error("default export must be a page factory: (host) => Page");let made=mod.default(pageHost),component=typeof made==="function"?made:made?.component;if(typeof component!=="function")throw Error("the page factory returned no component");return component}async function loadPluginPages(homeDir){let byPlugin=new Map,failed=[],entries=[];try{entries=loadPluginRegistry(homeDir).plugins}catch{}for(let entry2 of entries){if(!entry2.enabled)continue;let pages;try{pages=readPluginManifest(entry2.root).manifest.pages}catch{continue}let loaded2=[];for(let page of pages)try{let component=await importPage(entry2.root,page.entry);if(page.action!==void 0&&!isPageAction(page.action))failed.push({pluginId:entry2.id,pageId:page.id,message:`action \`${page.action}\` is not a page-open action; opens from the rail only`});let action=page.action!==void 0&&isPageAction(page.action)?page.action:void 0;loaded2.push({id:`${entry2.id}.${page.id}`,title:()=>page.title,order:page.order,...action?{action}:{},component,pluginId:entry2.id})}catch(err){failed.push({pluginId:entry2.id,pageId:page.id,message:errorMessage(err)})}byPlugin.set(entry2.id,loaded2)}replacePageSources("plugin:",byPlugin),pluginPageErrorState.set(failed)}var import_react19=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes13}from"@opentui/core";function modControls(panes){let out=[],walk=(node,plugin,pane)=>{if(node.type==="button"||node.type==="input")out.push({kind:node.type,plugin,pane,key:node.key});else if(node.type==="box")for(let child of node.children)walk(child,plugin,pane)};for(let pane of panes)walk(pane.tree,pane.plugin,pane.id);return out}function sameModControl(a2,b3){return a2!==null&&b3!==null&&a2.plugin===b3.plugin&&a2.pane===b3.pane&&a2.key===b3.key}function resolveModCursor(controls,cursor){return controls.find((c2)=>sameModControl(c2,cursor))??controls[0]??null}function moveModCursor(controls,cursor,delta){if(controls.length===0)return null;let at2=controls.findIndex((c2)=>sameModControl(c2,cursor));if(at2<0)return controls[0]??null;return controls[(at2+delta+controls.length)%controls.length]??null}function toneColor(tone,theme){switch(tone){case"info":return theme.info;case"success":return theme.success;case"warning":return theme.warning;case"error":return theme.error;case"muted":return theme.textMuted;default:return theme.text}}function draftKey(ref){return`${ref.plugin}/${ref.pane}/${ref.key}`}function ModTree(props){let{node,theme}=props;if(node.type==="text")return $jsx("text",{fg:toneColor(node.tone,theme),attributes:node.bold?TextAttributes13.BOLD:void 0,children:node.text});if(node.type==="input"){let ref={kind:"input",plugin:props.pane.plugin,pane:props.pane.id,key:node.key},focused=sameModControl(ref,props.cursor);return $jsx("box",{flexShrink:0,flexGrow:1,minWidth:12,backgroundColor:theme.backgroundElement,children:$jsx("input",{value:props.drafts.get(draftKey(ref))??node.value??"",placeholder:node.placeholder??"",focused:props.focused&&focused,onMouseUp:()=>props.onFocusControl(ref),onInput:(value)=>props.drafts.set(draftKey(ref),value),onSubmit:()=>props.onSubmit(ref,props.drafts.get(draftKey(ref))??node.value??"")},`${node.value??""}#${props.epoch}`)})}if(node.type==="button"){let ref={kind:"button",plugin:props.pane.plugin,pane:props.pane.id,key:node.key},focused=sameModControl(ref,props.cursor);return $jsx("text",{flexShrink:0,wrapMode:"none",fg:toneColor(node.tone??"info",theme),attributes:focused?TextAttributes13.BOLD|TextAttributes13.UNDERLINE:TextAttributes13.BOLD,onMouseUp:(e2)=>{e2.stopPropagation(),props.onPress(ref)},children:`[ ${node.label} ]`})}return $jsx("box",{flexDirection:node.direction??"column",gap:node.gap??0,padding:node.padding??0,flexShrink:0,...node.border?{...FRAME,borderColor:theme.border}:{},children:node.children.map((child,i2)=>$jsx(ModTree,{...props,node:child},i2))})}function ModsPage(props){let{theme}=useTheme(),t3=useT(),dims=useTerminalSize(),notif=useNotifications(),panes=useAccessor(props.orchestrator.modPanesSignal()),controls=modControls(panes),[rawCursor,setCursor]=import_react19.useState(null),cursor=resolveModCursor(controls,rawCursor),drafts=import_react19.useRef(new Map).current,[epoch,setEpoch]=import_react19.useState(0),report=(ref,sent)=>{sent.then((res)=>{let reason=res?.ok===!1?res.reason:null;if(reason)notif.notify({kind:"error",taskId:"",tabId:"",title:t3("mods.pressFailed",{plugin:ref.plugin,reason})})}).catch((err)=>notif.notify({kind:"error",taskId:"",tabId:"",title:t3("mods.pressFailed",{plugin:ref.plugin,reason:String(err)})}))},press=(ref)=>{setCursor(ref),report(ref,props.orchestrator.pressMod(ref.plugin,ref.pane,ref.key))},submit=(ref,value)=>{setCursor(ref),drafts.delete(draftKey(ref)),setEpoch((n2)=>n2+1),report(ref,props.orchestrator.submitMod(ref.plugin,ref.pane,ref.key,value))},inField=cursor?.kind==="input";return useBindings(()=>({enabled:props.focused,bindings:[...inField?[{key:"escape",cmd:props.onClose}]:pageCloseBindings(props.onClose),{key:"down",cmd:()=>setCursor(moveModCursor(controls,cursor,1))},{key:"tab",cmd:()=>setCursor(moveModCursor(controls,cursor,1))},{key:"up",cmd:()=>setCursor(moveModCursor(controls,cursor,-1))},{key:"shift+tab",cmd:()=>setCursor(moveModCursor(controls,cursor,-1))},...inField?[]:[{key:"return",cmd:()=>cursor&&press(cursor)}]]})),$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("mods.title")}),$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:0,children:t3("mods.keys")})]}),panes.length===0?$jsxs("box",{flexDirection:"column",paddingTop:1,children:[$jsx("text",{fg:theme.text,children:t3("mods.empty")}),$jsx("text",{fg:theme.textMuted,children:t3("mods.emptyHint")})]}):$jsx("scrollbox",{flexGrow:1,paddingTop:1,children:panes.map((pane)=>$jsxs("box",{flexDirection:"column",flexShrink:0,marginBottom:1,paddingLeft:1,paddingRight:1,...FRAME,borderColor:theme.border,children:[$jsxs("box",{flexDirection:"row",gap:1,flexShrink:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes13.BOLD,wrapMode:"none",children:pane.title}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:`\xB7 ${pane.plugin}`})]}),$jsx(ModTree,{node:pane.tree,pane,cursor,focused:props.focused,theme,onPress:press,onSubmit:submit,onFocusControl:setCursor,drafts,epoch})]},`${pane.plugin}/${pane.id}`))})]})}function ModsRailPage(props){return $jsx(ModsPage,{orchestrator:props.orchestrator,focused:props.focused,onClose:props.onClose})}var MODS_PAGE={id:"mods",title:()=>t("mods.title"),order:90,component:ModsRailPage};function registerModsPage(orchestrator){let panes=orchestrator.modPanesSignal(),shown=null,apply=()=>{let next=panes.get().length>0;if(next===shown)return;shown=next,setPageSource("mods",next?[MODS_PAGE]:[])};return apply(),panes.subscribe(apply)}var import_react134=__toESM(require_react_production(),1);var FLOW_CELLS_PER_TICK=2.5,WAVES=3,PARTNER_HUE_DEG=-160,TASK_PARTNER_HUE_DEG=-40,LEVELS=48;function perimeter(width,height){if(width<2||height<2)return[];let cells=[];for(let x2=0;x2<width;x2++)cells.push([x2,0]);for(let y3=1;y3<height;y3++)cells.push([width-1,y3]);for(let x2=width-2;x2>=0;x2--)cells.push([x2,height-1]);for(let y3=height-2;y3>0;y3--)cells.push([0,y3]);return cells}function flowPhase(index,loop,tick){if(loop===0)return 0;return((index-tick*FLOW_CELLS_PER_TICK)*WAVES/loop%1+1)%1}function flowPalette(accent,partnerDeg=PARTNER_HUE_DEG){let key=`${accent.toInts().join()}|${partnerDeg}`,hit=paletteCache.get(key);if(hit)return hit;let steps=Array.from({length:LEVELS},(_4,i2)=>{let away=0.5-0.5*Math.cos(2*Math.PI*i2/LEVELS);return turnHue(accent,partnerDeg*away,1.18-0.28*away,1.3)});return paletteCache.set(key,steps),steps}var paletteCache=new Map;function flowInk(palette,phase){return palette[Math.round(phase*palette.length)%palette.length]}var import_react22=__toESM(require_react_production(),1);function capOf(row){return row.hint?.keys??row.keys[0]}function legendCap(id){let row=findBinding(id);if(!row)return null;let cap=capOf(row);return cap&&cap.length>0?cap:null}function directCap(row){if(row.keys.length>0)return row.hint?.keys??row.keys[0]??null;return row.prefixKeys?.length?null:row.hint?.keys??null}function availableOn(row,surface){if(row.scope==="global")return!0;if(surface===null)return!1;if(row.scope===surface)return!0;return surface==="terminal"&&row.scope==="workspace"}function grammarHelpSections(keymap,surface,prefixKey,reachability){let here=[],direct=[],prefix=[],other=new Map;for(let binding of keymap){let cap=directCap(binding),staticallyAvailable=availableOn(binding,surface),directAvailable=reachability?reachability.direct.has(binding.id):staticallyAvailable,prefixAvailable=reachability?reachability.prefix.has(binding.id):staticallyAvailable;if(cap){let row={binding,primary:cap,aliases:binding.keys.filter((key)=>key!==cap)};if(directAvailable&&(staticallyAvailable||binding.presentation==="onePress"))if(binding.presentation==="onePress")direct.push(row);else here.push(row);else if(!staticallyAvailable&&binding.scope!=="global"){let rows=other.get(binding.scope);if(rows)rows.push(row);else other.set(binding.scope,[row])}}if(prefixKey&&prefixAvailable&&binding.prefixKeys?.length)prefix.push({binding,primary:`${prefixKey} + ${binding.prefixKeys[0]}`,aliases:binding.prefixKeys.slice(1).map((key)=>`${prefixKey} + ${key}`)})}let sections=[];if(here.length)sections.push({kind:"here",scope:surface??void 0,rows:here});if(direct.length)sections.push({kind:"direct",rows:direct});if(prefix.length)sections.push({kind:"prefix",rows:prefix});for(let[scope,rows]of other)sections.push({kind:"other",scope,rows});return sections}var SCOPE_CATEGORY={global:"Global",sidebar:"Sidebar",workspace:"Workspace",files:"Files",inbox:"Inbox",terminal:"Terminal"};function scopeCategory(scope){return scope?SCOPE_CATEGORY[scope]:"Global"}function guideCategory(action){if(["kanban.open","automations.open","workItems.open"].includes(action))return"Views";if(action.startsWith("focus."))return"Navigation";if(action.startsWith("inbox.")||action.startsWith("attention."))return"Attention";if(action.startsWith("chat.tab.")||action.startsWith("chat.session."))return"Sessions";if(action.startsWith("chat.fork.")||action.startsWith("task."))return"Tasks";if(action.startsWith("settings.")||action==="workspace.zenToggle")return"Tools";return findBinding(action)?.category??"Global"}function matchesHelpAction(query,name,chord){let trimmed=query.trim();return fuzzyMatch(trimmed,name)||fuzzyMatch(trimmed,chord)}var import_react21=__toESM(require_react_production(),1);var import_react20=__toESM(require_react_production(),1);function useKeymapVersion(){return import_react20.useSyncExternalStore(subscribeKeymapVersion,keymapVersion,keymapVersion)}var DEFAULT_PRESENTATION={mode:"local",activeSurface:null},ShortcutRevealContext=import_react21.createContext(DEFAULT_PRESENTATION);function useShortcutRevealPresentation(){return import_react21.useContext(ShortcutRevealContext)}function ShortcutRevealProvider(props){let kv=useOptionalKV(),hud=useAccessor(prefixHudState),mode=normalizePrefixTapPresentation(kv?.get(PREFIX_TAP_PRESENTATION_KEY)),value=import_react21.useMemo(()=>({mode,activeSurface:hud.guide?.kind==="prefix"?mode:null}),[mode,hud.guide?.kind]);return $jsx(ShortcutRevealContext.Provider,{value,children:props.children})}function ShortcutRevealBadge(props){let{activeSurface}=useShortcutRevealPresentation();if(activeSurface!=="local")return null;return $jsx(ActiveShortcutRevealBadge,{bindingId:props.bindingId,cover:props.cover})}function ActiveShortcutRevealBadge(props){let{theme}=useTheme();useKeymapVersion(),useBindingStackVersion();let caption=shortcutCaption({bindingId:props.bindingId,reachability:currentBindingReachability(),prefixKey:currentPrefixConfiguration().key});if(!caption)return null;return $jsx("box",{position:"absolute",left:props.cover?0:void 0,right:0,top:0,zIndex:20,paddingLeft:1,paddingRight:1,backgroundColor:theme.backgroundElement,justifyContent:"flex-end",children:$jsx("text",{fg:theme.primary,wrapMode:"none",children:caption})})}var BOTTOM_MARGIN=1;function actionLabel(action,translate){if(action===DIRECT_GUIDE_PREFIX_ACTION_ID)return translate("help.moreCommandsPrefix");if(!findBinding(action))return action;let label=tKeys("desc",action),dash=label.search(/\s\u2014\s|\u2014\u2014/);return dash>0?label.slice(0,dash):label}function groupPrefixGuideOptions(options){let order=new Map(RoveKeymap.map((binding,index)=>[binding.id,index])),byAction=new Map;for(let option of options){let current2=byAction.get(option.action);if(current2)current2.strokes.push(option.stroke);else byAction.set(option.action,{action:option.action,strokes:[option.stroke]})}let groups=new Map,actions=[...byAction.values()].sort((a2,b3)=>(order.get(a2.action)??Number.MAX_SAFE_INTEGER)-(order.get(b3.action)??Number.MAX_SAFE_INTEGER));for(let action of actions){let category=guideCategory(action.action),rows=groups.get(category);if(rows)rows.push(action);else groups.set(category,[action])}return[...groups].map(([category,rows])=>({category,actions:rows}))}function PrefixHud(props){let{theme}=useTheme(),t3=useT(),dims=useTerminalSize(),hud=useAccessor(prefixHudState),guide=hud.guide,{activeSurface}=useShortcutRevealPresentation(),showPrefixGuide=guide?.kind==="prefix"&&activeSurface!==null,showCommandGuide=guide?.kind==="direct"||showPrefixGuide,[,setFlushTick]=import_react22.useState(0),clock=prefixHudClock(),now=clock.now(),fresh=hud.entries.filter((entry2)=>now-entry2.at<PREFIX_HUD_TTL_MS),oldestAt=fresh[0]?.at;import_react22.useEffect(()=>{if(oldestAt===void 0)return;return clock.schedule(()=>setFlushTick((tick)=>tick+1),Math.max(30,oldestAt+PREFIX_HUD_TTL_MS-clock.now()))},[oldestAt,clock]),import_react22.useEffect(()=>{if(!showPrefixGuide||guide?.kind!=="prefix")return;let remaining=guide.armedAt+PREFIX_GUIDE_DELAY_MS-clock.now();if(remaining<=0)return;return clock.schedule(()=>setFlushTick((tick)=>tick+1),remaining)},[showPrefixGuide,guide,clock]);let lineCount=fresh.length+(showCommandGuide?1:0);if(lineCount===0)return null;let prefixKey=currentPrefixConfiguration().key??"",showGuide=guide?.kind==="direct"||showPrefixGuide&&guide?.kind==="prefix"&&now-guide.armedAt>=PREFIX_GUIDE_DELAY_MS,groups=showGuide&&guide?groupPrefixGuideOptions(guide.options):[];if(showGuide){let narrow2=dims.width<88,columns=narrow2?1:Math.min(dims.width<140?2:3,Math.max(1,groups.length)),guideWidth=Math.max(20,dims.width-4),groupWidth=narrow2?guideWidth-4:Math.max(18,Math.floor((guideWidth-4)/columns)),groupKeyWidth=(group)=>Math.min(9,Math.max(3,...group.actions.map((action)=>displayWidth(action.strokes.join("/"))))),actionHeight=(group,action)=>{let strokes=action.strokes.join("/"),keyWidth=groupKeyWidth(group),labelWidth=Math.max(1,groupWidth-keyWidth-1),keyLines=Math.ceil(displayWidth(strokes)/keyWidth),labelLines=Math.ceil(displayWidth(actionLabel(action.action,t3))/labelWidth);return Math.max(1,keyLines,labelLines)},groupHeight=(group)=>1+group.actions.reduce((sum,action)=>sum+actionHeight(group,action),0),heights=groups.map(groupHeight),chunkHeight=(from,to)=>heights.slice(from,to).reduce((sum,h2)=>sum+h2,0)+Math.max(0,to-from-1),bounds=((count)=>{let best=[groups.length],bestMax=Number.POSITIVE_INFINITY,walk=(start,left2,cuts,tallest)=>{if(left2===1){let max=Math.max(tallest,chunkHeight(start,groups.length));if(max<bestMax)bestMax=max,best=[...cuts,groups.length];return}for(let end=start+1;end<=groups.length-left2+1;end++)walk(end,left2-1,[...cuts,end],Math.max(tallest,chunkHeight(start,end)))};return walk(0,Math.max(1,count),[],0),best})(Math.min(columns,groups.length)),columnChunks=[],chunkStart=0;for(let bound3 of bounds){if(bound3>chunkStart)columnChunks.push(groups.slice(chunkStart,bound3));chunkStart=bound3}let contentHeight=3+columnChunks.reduce((tallest,chunk)=>Math.max(tallest,chunk.reduce((sum,group)=>sum+groupHeight(group),0)+(chunk.length-1)),0),maxGuideHeight=Math.max(3,dims.height-BOTTOM_MARGIN),clipped=contentHeight>maxGuideHeight,guideHeight=Math.min(contentHeight+(clipped?1:0),maxGuideHeight),top2=Math.max(0,dims.height-BOTTOM_MARGIN-guideHeight);return $jsxs("box",{position:"absolute",zIndex:2400,left:2,top:top2,width:guideWidth,height:guideHeight,overflow:"hidden",...FRAME,borderColor:theme.borderActive,backgroundColor:theme.backgroundDialog,paddingLeft:1,paddingRight:1,flexDirection:"column",children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",children:[$jsx("text",{fg:theme.primary,children:guide?.kind==="direct"?t3("help.directLayer"):t3("help.commandLayer",{prefix:prefixKey})}),$jsx("text",{fg:theme.textMuted,children:guide?.kind==="direct"?t3("help.releaseCtrl"):t3("help.escCancel")})]}),$jsx("box",{flexDirection:"row",gap:narrow2?0:1,alignItems:"flex-start",flexGrow:1,flexShrink:1,overflow:"hidden",children:columnChunks.map((chunk)=>$jsx("box",{flexDirection:"column",flexGrow:1,flexBasis:0,children:chunk.map((group,groupIndex)=>$jsxs("box",{flexDirection:"column",marginTop:groupIndex===0?0:1,children:[$jsx("text",{fg:theme.accent,children:tKeys("category",group.category)}),group.actions.map((action)=>{let strokes=action.strokes.join("/");return $jsxs("box",{flexDirection:"row",gap:1,onMouseUp:(event)=>{if(event.stopPropagation(),guide?.kind!=="prefix")return;let stroke=action.strokes[0];if(stroke)invokeArmedPrefixActionFromCurrentStack(action.action,stroke)},children:[$jsx("box",{width:groupKeyWidth(group),children:$jsx("text",{fg:theme.primary,wrapMode:"char",children:strokes})}),$jsx("text",{fg:theme.text,wrapMode:"word",flexGrow:1,flexShrink:1,children:actionLabel(action.action,t3)})]},action.action)})]},group.category))},chunk.map((group)=>group.category).join("-")))}),clipped?$jsx("text",{fg:theme.textMuted,children:t3("help.overflow")}):null]})}let narrow=isNarrowWidth(dims.width),left=narrow?0:props.left,width=narrow?dims.width:props.width,top=Math.max(0,dims.height-BOTTOM_MARGIN-lineCount);return $jsxs("box",{position:"absolute",zIndex:2400,left,top,width,flexDirection:"column",children:[fresh.map((entry2)=>$jsx("box",{paddingLeft:1,paddingRight:1,backgroundColor:theme.backgroundDialog,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:truncateEndCells(`${entry2.prefixKey?`${entry2.prefixKey} + `:""}${entry2.stroke} ${entry2.action?`\u2192 ${actionLabel(entry2.action,t3)}`:"\u2205"}`,width-2,charWidth)})},entry2.id)),showCommandGuide?$jsx("box",{paddingLeft:1,paddingRight:1,backgroundColor:theme.backgroundDialog,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:`${prefixKey} \u22EF`})}):null]})}import{TextAttributes as TextAttributes14}from"@opentui/core";var MAX_VISIBLE=3,CARD_WIDTH=44,RIGHT_MARGIN=2,BOTTOM_MARGIN2=2;function cardRows(toast,hintRows){return(toast.body?2:1)+1+(toast.kind==="error"?hintRows:0)}function ToastOverlay(){let{theme}=useTheme(),t3=useT(),dims=useTerminalSize(),notif=useNotifications();if(notif.toasts.length===0)return null;let visibleToasts=notif.toasts.slice(-MAX_VISIBLE),cardWidth=Math.min(CARD_WIDTH,Math.max(12,dims.width-RIGHT_MARGIN*2)),hint=t3("common.toastFailureHint"),hintRows=Math.ceil(displayWidth(hint)/Math.max(1,cardWidth-3)),stackRows=visibleToasts.reduce((rows,toast)=>rows+cardRows(toast,hintRows),0),left=Math.max(0,dims.width-cardWidth-RIGHT_MARGIN),top=Math.max(0,dims.height-BOTTOM_MARGIN2-stackRows),textBudget=cardWidth-5;return $jsx("box",{position:"absolute",zIndex:2500,left,top,width:cardWidth,flexDirection:"column",gap:1,children:visibleToasts.map((toast)=>{let accent=toast.kind==="needs_input"?theme.warning:toast.kind==="error"?theme.error:theme.success,glyph=toast.kind==="needs_input"?"?":toast.kind==="error"?"\u2715":"\u2713";return $jsxs("box",{flexDirection:"row",backgroundColor:theme.backgroundElement,onMouseUp:()=>notif.dismiss(toast.id),children:[$jsxs("box",{flexDirection:"column",flexShrink:0,children:[$jsx("text",{fg:accent,wrapMode:"none",children:"\u258C"}),toast.body?$jsx("text",{fg:accent,wrapMode:"none",children:"\u258C"}):null]}),$jsxs("box",{flexDirection:"column",flexBasis:0,flexGrow:1,flexShrink:1,paddingLeft:1,paddingRight:1,children:[$jsxs("box",{flexDirection:"row",children:[$jsx("text",{fg:accent,attributes:TextAttributes14.BOLD,wrapMode:"none",flexShrink:0,children:`${glyph} `}),$jsx("text",{fg:theme.text,attributes:TextAttributes14.BOLD,wrapMode:"none",flexBasis:0,flexGrow:1,flexShrink:1,children:truncateEndCells(toast.title,textBudget,charWidth)})]}),toast.body?$jsx("box",{flexDirection:"row",paddingLeft:2,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexBasis:0,flexGrow:1,flexShrink:1,children:truncateEndCells(toast.body,textBudget,charWidth)})}):null,toast.kind==="error"?$jsx("text",{fg:theme.warning,wrapMode:"char",height:hintRows,flexShrink:0,children:hint}):null]})]},toast.id)})})}var import_react23=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes15}from"@opentui/core";function WhatsNewDialogView(props){let{theme}=useTheme(),t3=useT(),padX=useDialogPaddingX(),[notes,setNotes]=import_react23.useState([]),[loading,setLoading]=import_react23.useState(!0);import_react23.useEffect(()=>{let live=!0;return(props.fetchNotes??fetchReleaseNotesRange)({current:props.from,latest:CURRENT_VERSION,locale:currentLang()}).then((fetched)=>{if(!live)return;setNotes(fetched),setLoading(!1)}),()=>{live=!1}},[props.from,props.fetchNotes]);let scrollRef=import_react23.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})};useBindings(()=>({bindings:[{key:"q",cmd:props.onClose},{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")}]}));let url=notes[0]?.url??releasePageUrl(CURRENT_VERSION);return $jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:1,flexShrink:1,children:[$jsxs("box",{flexDirection:"column",gap:0,flexShrink:0,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",children:[$jsx("text",{attributes:TextAttributes15.BOLD,fg:theme.text,wrapMode:"none",children:t3("update.whatsNew.title")}),$jsxs("box",{flexDirection:"row",gap:2,flexShrink:0,children:[$jsx("text",{fg:theme.textMuted,attributes:TextAttributes15.DIM,wrapMode:"none",children:t3("help.scrollKeys")}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",onMouseUp:props.onClose,children:t3("update.whatsNew.closeHint")})]})]}),$jsx("text",{fg:theme.accent,wrapMode:"word",children:t3("update.whatsNew.upgraded",{from:props.from,to:CURRENT_VERSION})})]}),$jsx("scrollbox",{ref:(r6)=>{scrollRef.current=r6},flexShrink:1,flexGrow:1,stickyScroll:!1,verticalScrollbarOptions:{trackOptions:{backgroundColor:theme.backgroundDialog,foregroundColor:theme.borderActive}},children:$jsxs("box",{flexDirection:"column",paddingRight:1,paddingBottom:1,gap:1,children:[loading?$jsx("text",{fg:theme.textMuted,children:t3("update.loadingNotes")}):null,!loading&&notes.length===0?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("update.whatsNew.notesUnavailable")}):null,notes.map((release)=>$jsxs("box",{flexDirection:"column",gap:0,children:[$jsxs("text",{fg:theme.text,attributes:TextAttributes15.BOLD,wrapMode:"none",children:["v",release.version]}),$jsx(ReleaseNotesBody,{body:release.body})]},release.version))]})}),$jsx("box",{paddingBottom:1,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes15.DIM,wrapMode:"none",children:t3("update.whatsNew.sourceHint",{url})})})]})}function show2(dialog,opts){dialog.replace(()=>$jsx(WhatsNewDialogView,{from:opts.from,onClose:()=>dialog.clear(),...opts.fetchNotes?{fetchNotes:opts.fetchNotes}:{}}),opts.onClosed),dialog.setSize("medium")}var WhatsNewDialog={show:show2};function useWhatsNewDialog(from,onClosed,fetchNotes){let dialog=useDialog(),opened=import_react23.useRef(!1);import_react23.useEffect(()=>{if(from===null||opened.current)return;opened.current=!0,WhatsNewDialog.show(dialog,{from,onClosed,...fetchNotes?{fetchNotes}:{}})},[from,dialog,onClosed,fetchNotes])}var import_react42=__toESM(require_react_production(),1);var import_react24=__toESM(require_react_production(),1);function RenameTaskDialogView(props){let dialog=useDialog(),t3=useT(),padX=useDialogPaddingX(),[value,setValue]=import_react24.useState(props.currentTitle);function commit(){let v3=value.trim();if(isBlankText(v3)&&!props.allowEmpty)return;props.onSubmit(v3),dialog.clear()}return $jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:1,children:[$jsx(DialogHeader2,{title:props.dialogTitle??t3("common.rename.defaultTitle"),onClose:()=>props.onCancel()}),$jsx(DialogSection2,{label:props.fieldLabel??t3("common.rename.defaultFieldLabel"),focused:!0,children:$jsx(DialogField2,{focused:!0,children:$jsx("input",{value,placeholder:props.placeholder??props.currentTitle,focused:!0,onInput:(v3)=>setValue(stripNewlines2(v3)),onSubmit:()=>commit()})})}),$jsx(DialogFooter2,{children:t3("common.rename.footerHint",{submitLabel:props.submitLabel??t3("common.rename.defaultSubmitLabel")})})]})}function show3(dialog,currentTitle,opts={}){return showDialog(dialog,(resolve2)=>$jsx(RenameTaskDialogView,{currentTitle,dialogTitle:opts.dialogTitle,fieldLabel:opts.fieldLabel,submitLabel:opts.submitLabel,placeholder:opts.placeholder,allowEmpty:opts.allowEmpty,onSubmit:(v3)=>resolve2(v3),onCancel:()=>resolve2(void 0)}))}var RenameTaskDialog={show:show3};function savedTabs(taskId){let saved=loadStateFile()[terminalTabsKey(taskId)];return saved&&Array.isArray(saved.tabs)?saved:null}function addTaskTab(kv,taskId,tab){if(requestTabAdd(taskId,tab),!takeUnclaimedTabAdd())return;let known=knownTabsState(kv,taskId),state=known??savedTabs(taskId);if(!state)return;let next=absorbTab(state,tab);if(next===state&&known)return;setTaskTabs2(taskId,next),reportTabsDelta(taskId,state.tabs,next.tabs)}var closedAt=new Map;function tabKeyOf(key){return key.split("::").slice(0,2).join("::")}function noteClosedPtyKey(key,now=Date.now()){closedAt.set(tabKeyOf(key),now)}function isRecentlyClosedPtyKey(key,now=Date.now()){let tabKey=tabKeyOf(key),at2=closedAt.get(tabKey);if(at2===void 0)return!1;if(now-at2>15000)return closedAt.delete(tabKey),!1;return!0}var import_react41=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes16}from"@opentui/core";var RAIL_CHARS={topLeft:"\u258E",topRight:"\u258E",bottomLeft:"\u258E",bottomRight:"\u258E",horizontal:" ",vertical:"\u258E",topT:"\u258E",bottomT:"\u258E",leftT:"\u258E",rightT:"\u258E",cross:"\u258E"};function paneChrome(style,divider){switch(style){case"box":return{border:!0,borderStyle:"rounded",nameOnRule:!1};case"line":return{border:divider?[divider]:!1,nameOnRule:!1};case"rail":return{border:["left"],customBorderChars:RAIL_CHARS,marginTop:divider==="top"?1:0,nameOnRule:!1};case"rule":return{border:["top"],marginLeft:divider==="left"?1:0,nameOnRule:!0}}}function groupChrome(style,divider){if(style==="line")return paneChrome(style,divider);let{marginLeft,marginTop}=paneChrome(style,divider);return{border:!1,marginLeft,marginTop,nameOnRule:!1}}function paneBoxProps(chrome,ink){let{nameOnRule,...frame}=chrome;return{...frame,...frame.border===!1?{}:{borderColor:ink.edge},...nameOnRule?{title:` ${ink.name??""} `,titleAlignment:"right",titleColor:ink.nameInk}:{}}}function leafOnEdge(node,orientation,end,id){if(node.kind==="leaf")return node.id===id;if(node.orientation!==orientation)return node.children.some((c2)=>leafOnEdge(c2,orientation,end,id));let edge=end?node.children[node.children.length-1]:node.children[0];return edge!==void 0&&leafOnEdge(edge,orientation,end,id)}var import_react39=__toESM(require_react_production(),1);class PtyCoordinateRetention{ptyIdentity=null;coordinate=null;update(ptyIdentity,coordinate){if(ptyIdentity!==this.ptyIdentity)this.ptyIdentity=ptyIdentity,this.coordinate=null;if(ptyIdentity===null)return this.coordinate=null,null;if(coordinate)this.coordinate={x:coordinate.x,y:coordinate.y};return this.coordinate}current(){return this.coordinate}}class ImeCursorRetention extends PtyCoordinateRetention{}class ImeScreenAnchorRetention extends PtyCoordinateRetention{}function isShellMissing(message){let m3=message.toLowerCase();return m3.includes("enoent")||m3.includes("not found")}function cellWidth(ch){return charWidth(ch.codePointAt(0))}function cloneChunk(c2,text,attrs=c2.attributes??0){return{text,...c2.fg?{fg:c2.fg}:{},...c2.bg?{bg:c2.bg}:{},...attrs!==0?{attributes:attrs}:{}}}function chunkCells(chars){let w4=0;for(let ch of chars)w4+=cellWidth(ch);return w4}function cursorChunk(source,text,colors){let attributes=(source.attributes??0)&~ATTR.INVERSE;return{text,fg:source.bg??colors.background,bg:source.fg??colors.foreground,...attributes!==0?{attributes}:{}}}function overlayCursorRow(row,x2,colors){let out=[],col=0,inserted=!1;for(let chunk of row){if(inserted){out.push(chunk);continue}let chars=Array.from(chunk.text),localCol=col,hit=-1;for(let idx=0;idx<chars.length;idx++){let w4=cellWidth(chars[idx]);if(x2>=localCol&&x2<localCol+w4){hit=idx;break}localCol+=w4}if(hit>=0){let before=chars.slice(0,hit).join(""),after=chars.slice(hit+1).join("");if(before)out.push(cloneChunk(chunk,before));if(out.push(cursorChunk(chunk,chars[hit]||" ",colors)),after)out.push(cloneChunk(chunk,after));inserted=!0}else out.push(chunk),col+=chunkCells(chars)}if(!inserted){if(x2>col)out.push({text:" ".repeat(x2-col)});out.push(cursorChunk({text:" "}," ",colors))}return out}function overlayCursor(rows,cursor,colors){if(!cursor)return rows;return rows.map((row,y3)=>y3===cursor.y?overlayCursorRow(row,cursor.x,colors):row)}function resolveInverseAttributes(rows,defaultFg,defaultBg){return rows.map((row)=>{let out=null;for(let i2=0;i2<row.length;i2++){let chunk=row[i2],attributes=chunk.attributes??0;if((attributes&ATTR.INVERSE)===0){if(out)out.push(chunk);continue}out??=row.slice(0,i2);let resolvedAttributes=attributes&~ATTR.INVERSE;out.push({text:chunk.text,fg:chunk.bg??defaultBg,bg:chunk.fg??defaultFg,...resolvedAttributes!==0?{attributes:resolvedAttributes}:{}})}return out??row})}function sealRowEndAttributes(rows,cols,defaultFg,defaultBg){if(cols<=0)return rows;let lastColumn=cols-1;return rows.map((row)=>{let col=0;for(let i2=0;i2<row.length;i2++){let chunk=row[i2],chars=Array.from(chunk.text);for(let j2=0;j2<chars.length;j2++){let ch=chars[j2],w4=cellWidth(ch);if(col+w4<=lastColumn){col+=w4;continue}let attrs=chunk.attributes??0;if(attrs===0)return row;let fg=chunk.fg??defaultFg,bg=chunk.bg??defaultBg,sealed=(attrs&ATTR.INVERSE)!==0?{text:ch,fg:bg,bg:fg}:{text:ch,fg,bg},head=chars.slice(0,j2).join(""),tail=chars.slice(j2+1).join(""),rebuilt=row.slice(0,i2);if(head)rebuilt.push(cloneChunk(chunk,head));if(rebuilt.push(sealed),tail)rebuilt.push(cloneChunk(chunk,tail));return[...rebuilt,...row.slice(i2+1)]}}return row})}var TEXT_PRESENTATION={"\u23F8":"\u2016","\u23F9":"\u25A0","\u23FA":"\u25CF"},EMOJI_PRONE=/[\u23F8\u23F9\u23FA]/u;function textPresentationRow(row,platform=process.platform){if(platform==="darwin"||!row.some((c2)=>EMOJI_PRONE.test(c2.text)))return row;return row.map((c2)=>EMOJI_PRONE.test(c2.text)?{...c2,text:c2.text.replace(/[\u23F8\u23F9\u23FA]/gu,(g3)=>TEXT_PRESENTATION[g3]??g3)}:c2)}var FOLLOW_VIEWPORT={fallbackOffset:0,anchor:null};function computeViewport(total,height,offset){let h2=Math.max(1,height),end=Math.max(0,total-Math.max(0,offset));return{start:Math.max(0,end-h2),end}}function resolveViewportScrollOffset(total,height,state,window2){let max=Math.max(0,total-Math.max(1,height)),fallback=Math.min(max,Math.max(0,state.fallbackOffset));if(!state.anchor||!window2||state.anchor.epoch!==window2.epoch)return fallback;let top=state.anchor.topLine-window2.startLine;if(top<=0)return max;return Math.min(max,Math.max(0,total-(top+Math.max(1,height))))}function moveViewportScroll(state,total,height,lines,window2){let current2=resolveViewportScrollOffset(total,height,state,window2),max=Math.max(0,total-Math.max(1,height)),next=Math.min(max,Math.max(0,current2-lines));if(next===0)return FOLLOW_VIEWPORT;let range2=computeViewport(total,height,next),anchor=window2?{epoch:window2.epoch,topLine:window2.startLine+range2.start}:null;return{fallbackOffset:next,anchor}}function viewportCursor(cursor,offset,range2){if(!cursor||offset!==0)return null;if(cursor.y<range2.start||cursor.y>=range2.end)return null;return{x:cursor.x,y:cursor.y-range2.start}}function Action(props){let{theme}=useTheme();useKeymapVersion(),useBindingStackVersion();let caption=props.bindingId?shortcutCaption({bindingId:props.bindingId,reachability:currentBindingReachability(),prefixKey:currentPrefixConfiguration().key}):null;return $jsxs("box",{flexDirection:"row",flexShrink:0,columnGap:1,children:[$jsx("text",{fg:theme.info,wrapMode:"none",onMouseUp:(event)=>{if(event.stopPropagation(),event.button!==0)return;props.onPress(),props.onRequestFocus?.()},children:`[${props.label}]`}),caption?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:caption}):null]})}function EngineExitBanner(props){let{theme}=useTheme(),t3=useT();return $jsxs("box",{flexDirection:"row",flexWrap:"wrap",flexShrink:0,columnGap:2,paddingLeft:1,paddingRight:1,onMouseDown:(event)=>event.stopPropagation(),onMouseUp:(event)=>event.stopPropagation(),children:[$jsx("text",{fg:theme.error,wrapMode:"none",children:props.code===null?t3("terminal.engineExit.title"):t3("terminal.engineExit.titleCode",{code:props.code})}),$jsx(Action,{label:t3("terminal.engineExit.retry"),bindingId:"terminal.reset",onPress:props.onRetry,onRequestFocus:props.onRequestFocus}),props.onSettings?$jsx(Action,{label:t3("terminal.engineExit.settings"),bindingId:"settings.open",onPress:props.onSettings}):null,$jsx(Action,{label:t3("terminal.engineExit.another"),bindingId:"chat.tab.chooseEngine",onPress:props.onAnotherEngine}),$jsx(Action,{label:t3("terminal.engineExit.continueIn"),bindingId:"chat.tab.fork",onPress:props.onContinueInEngine})]})}function UsageLimitBanner(props){let{theme}=useTheme(),t3=useT();return $jsxs("box",{flexDirection:"row",flexWrap:"wrap",flexShrink:0,columnGap:2,paddingLeft:1,paddingRight:1,onMouseDown:(event)=>event.stopPropagation(),onMouseUp:(event)=>event.stopPropagation(),children:[$jsx("text",{fg:theme.warning,wrapMode:"none",children:t3("terminal.usageLimit.title")}),$jsx(Action,{label:t3("terminal.engineExit.continueIn"),bindingId:"chat.tab.fork",onPress:props.onContinueInEngine,onRequestFocus:props.onRequestFocus}),$jsx(Action,{label:t3("terminal.usageLimit.dismiss"),onPress:props.onDismiss,onRequestFocus:props.onRequestFocus})]})}import{decodePasteBytes}from"@opentui/core";var import_react26=__toESM(require_react_production(),1);function useTerminalBindings(opts){let pageSize=opts.pageSize??DEFAULT_PAGE_SIZE,optsRef=useLatest(opts),pageSizeRef=useLatest(pageSize),bindings=import_react26.useMemo(()=>{let table=[];table.push(...bindByIds({"terminal.scroll-up":()=>optsRef.current.scroll(-pageSizeRef.current),"terminal.scroll-down":()=>optsRef.current.scroll(pageSizeRef.current),"terminal.reset":()=>optsRef.current.reset()}));for(let chord of COPY_CHORDS)table.push({key:chord,cmd:()=>{optsRef.current.copySelection()}});let forward=(evt)=>{let bytes=keyEventToShellBytes(evt,optsRef.current.inputModes?.()??NORMAL_TERMINAL_INPUT_MODES);if(bytes!=null)optsRef.current.write(bytes)};for(let chord of PASSTHROUGH_CHORDS)table.push({key:chord,cmd:forward,passthrough:!0});return table},[]);useBindings(()=>({enabled:optsRef.current.focused,bindings}));let renderer=useRenderer();import_react26.useEffect(()=>{if(!renderer)return;let forwardUnhandled=(evt)=>{if(!optsRef.current.focused)return;if(evt.defaultPrevented||modalActive())return;let bytes=keyEventToShellBytes(evt,optsRef.current.inputModes?.()??NORMAL_TERMINAL_INPUT_MODES);if(bytes==null)return;optsRef.current.write(bytes),evt.preventDefault()},forwardPaste=(evt)=>{if(evt.defaultPrevented||modalActive())return;let text=decodePasteBytes(evt.bytes);if(text.length===0)return;if(!optsRef.current.focused&&(!optsRef.current.unfocusedAttachmentTarget||!asAttachmentPaths(text)))return;optsRef.current.paste(text),evt.preventDefault()};return renderer.keyInput.on("keypress",forwardUnhandled),renderer.keyInput.on("paste",forwardPaste),()=>{renderer.keyInput.off("keypress",forwardUnhandled),renderer.keyInput.off("paste",forwardPaste)}},[renderer])}var import_react27=__toESM(require_react_production(),1);function useTerminalGeometry(){let[bodyEl,setBodyElState]=import_react27.useState(null),bodyElRef=import_react27.useRef(null),[bodyRows,setBodyRows]=import_react27.useState(4),[bodyGeometry,setBodyGeometry]=import_react27.useState(null),dims=useTerminalSize(),shownElRef=import_react27.useRef(null),setBodyEl=import_react27.useCallback((el)=>{if(bodyElRef.current=el,el){if(el===shownElRef.current)return;shownElRef.current=el,setBodyElState(el);return}queueMicrotask(()=>{if(bodyElRef.current||!shownElRef.current)return;shownElRef.current=null,setBodyElState(null)})},[]),measure=import_react27.useCallback((el)=>{if(el.width<=0||el.height<=0)return;let cols=Math.max(20,el.width),rows=Math.max(4,el.height);setBodyRows(rows),setBodyGeometry((cur)=>cur&&cur.cols===cols&&cur.rows===rows?cur:{cols,rows})},[]),[geomTick,setGeomTick]=import_react27.useState(0),bumpGeomTick=import_react27.useCallback(()=>{if(setGeomTick((n2)=>n2+1&255),bodyElRef.current)measure(bodyElRef.current)},[measure]);return import_react27.useEffect(()=>{if(bodyEl)measure(bodyEl)},[bodyEl,dims,geomTick,measure]),{bodyEl,setBodyEl,bodyRows,bodyGeometry,bumpGeomTick,dims,geomTick}}var import_react29=__toESM(require_react_production(),1);function useTerminalHostCursor(opts){let{pty,bodyEl,bodyGeometry,visibleImeCursor,imeAnchorActive,dims,geomTick}=opts,renderer=useRenderer(),imeAnchorOwner=import_react29.useRef(Symbol("terminal-ime-anchor")).current,[imeScreenAnchorRetention]=import_react29.useState(()=>new ImeScreenAnchorRetention),lastResizeRef=import_react29.useRef(null);import_react29.useEffect(()=>{if(!pty||!bodyGeometry)return;let{cols,rows}=bodyGeometry,last=lastResizeRef.current;if(last?.pty===pty&&last.cols===cols&&last.rows===rows)return;lastResizeRef.current={pty,cols,rows};try{pty.resize(cols,rows)}catch{}},[pty,bodyGeometry]),import_react29.useEffect(()=>{if(!renderer)return;if(!imeAnchorActive){if(imeScreenAnchorRetention.update(null,null),imeAnchorController.release(imeAnchorOwner))renderer.setCursorPosition(0,0,!1);return}let currentScreenAnchor=null;if(bodyEl&&visibleImeCursor&&bodyEl.width>0)currentScreenAnchor={x:bodyEl.screenX+visibleImeCursor.x,y:bodyEl.screenY+visibleImeCursor.y};let retainedAnchor=imeScreenAnchorRetention.update(pty,currentScreenAnchor);if(retainedAnchor){imeAnchorController.claim(imeAnchorOwner,retainedAnchor),renderer.setCursorPosition(retainedAnchor.x,retainedAnchor.y,!1);return}imeAnchorController.claim(imeAnchorOwner,{x:0,y:0}),renderer.setCursorPosition(0,0,!1)},[renderer,imeAnchorActive,bodyEl,visibleImeCursor,dims,geomTick,imeAnchorOwner,imeScreenAnchorRetention,pty]),import_react29.useEffect(()=>{return()=>{try{if(imeAnchorController.release(imeAnchorOwner))renderer?.setCursorPosition(0,0,!1)}catch{}}},[renderer,imeAnchorOwner])}var import_react31=__toESM(require_react_production(),1);function isWrapContinuation(wrapped,row){return row>0&&wrapped?.[row]===!0}function pointerCell(viewCol,viewRow,grid,visibleStart,snapshotLength){let col=Math.min(grid.cols-1,Math.max(0,viewCol)),row=Math.min(Math.max(0,snapshotLength-1),Math.max(0,visibleStart+viewRow)),lastRow=grid.rows-1,edgePull=viewRow<=0?viewRow-1:viewRow>=lastRow?viewRow-lastRow+1:0;return{cell:{row,col},edgePull}}function orderRange(range2){let{anchor,head}=range2;return head.row<anchor.row||head.row===anchor.row&&head.col<anchor.col?{start:head,end:anchor}:{start:anchor,end:head}}function rowSpan(range2,row,width){let{start,end}=orderRange(range2);if(row<start.row||row>end.row)return null;let from=row===start.row?start.col:0,to=row===end.row?end.col+1:width;return from<to?[from,to]:null}function rowText(row){let s2="";for(let chunk of row)s2+=chunk.text;return s2}function textCells(text){let cells=0;for(let ch of text)cells+=charWidth(ch.codePointAt(0));return cells}function sliceTextByCells(text,from,to){let before="",selected="",after="",col=0,lastPart="before";for(let ch of text){let width=charWidth(ch.codePointAt(0));if(width===0){if(lastPart==="selected")selected+=ch;else if(lastPart==="after")after+=ch;else before+=ch;continue}let end=col+width;if(end<=from)before+=ch,lastPart="before";else if(col>=to)after+=ch,lastPart="after";else selected+=ch,lastPart="selected";col=end}return{before,selected,after}}function extractSelection(rows,range2,wrapped){let{start,end}=orderRange(range2),first=Math.max(0,start.row),lines=[],walls=[];for(let r6=first;r6<=Math.min(rows.length-1,end.row);r6++){let text=rowText(rows[r6]??[]),span=rowSpan(range2,r6,Math.max(textCells(text),1)),parts=span?sliceTextByCells(text,span[0],span[1]):{before:"",selected:""},slice=parts.selected,trimmed=slice.trimEnd();if(walls.push({glyph:trimmed.slice(-1),column:textCells(parts.before)+textCells(trimmed)-1}),r6>first&&isWrapContinuation(wrapped,r6)&&lines.length>0)lines[lines.length-1]+=slice;else lines.push(slice)}let precedingWalls=walls.slice(0,-1),wall=precedingWalls[0],framed=!wrapped?.slice(first,first+walls.length).some(Boolean)&&precedingWalls.length>=2&&wall!==void 0&&/^[\u2502\u2503\u2551\u254E\u2506\u250A]$/.test(wall.glyph)&&precedingWalls.every((candidate)=>candidate.glyph===wall.glyph&&candidate.column===wall.column);return lines.map((line,index)=>{let trimmed=line.trimEnd();return framed&&index<lines.length-1?trimmed.slice(0,-1).trimEnd():trimmed}).join(`
63
63
  `)}function paintChunk(chunk,text,paint){if(paint==="inverse")return{...chunk,text,attributes:(chunk.attributes??0)^ATTR.INVERSE};return{...chunk,text,fg:paint.fg,bg:paint.bg}}function overlayRowSpan(row,from,to,paint){let out=[],col=0;for(let chunk of row){let start=col,end=start+textCells(chunk.text);if(col=end,end<=from||start>=to){out.push(chunk);continue}let{before,selected,after}=sliceTextByCells(chunk.text,from-start,to-start);if(before)out.push({...chunk,text:before});if(out.push(paintChunk(chunk,selected,paint)),after)out.push({...chunk,text:after})}if(col<to){let gap=from-col;if(gap>0)out.push({text:" ".repeat(gap)});out.push(paintChunk({text:""}," ".repeat(to-Math.max(col,from)),paint))}return out}var EMPTY_SHADOW={above:[],below:[]},SHADOW_ROW_CAP=2000;function snapshotShift(prev,next){if(prev===next||prev.length===0||next.length===0)return 0;let prevText=prev.map(rowText),nextText=next.map(rowText),maxShift=Math.min(prev.length,next.length)-1,best=0,bestScore=-1,bestOverlap=0;for(let k3=-maxShift;k3<=maxShift;k3++){let score=0,overlap=0;for(let i2=0;i2<prevText.length;i2++){let j2=i2+k3;if(j2<0||j2>=nextText.length)continue;let t3=prevText[i2];if(t3.trim()==="")continue;if(overlap++,t3===nextText[j2])score++}if(score>bestScore||score===bestScore&&Math.abs(k3)<Math.abs(best))best=k3,bestScore=score,bestOverlap=overlap}return bestScore>1&&bestScore*2>bestOverlap?best:0}function shiftShadow(shadow,previous,shift,cap=SHADOW_ROW_CAP){if(shift===0)return shadow;let{above,below}=shadow;if(shift>0)below=[...previous.slice(Math.max(0,previous.length-shift)),...below],above=above.slice(0,Math.max(0,above.length-shift));else above=[...above,...previous.slice(0,Math.min(previous.length,-shift))],below=below.slice(Math.min(below.length,-shift));if(above.length>cap)above=above.slice(above.length-cap);if(below.length>cap)below=below.slice(0,cap);return{above,below}}function clampRowToShadow(row,snapshotLength,shadow){return Math.min(snapshotLength-1+shadow.below.length,Math.max(0-shadow.above.length,row))}function followContentShift(state,prev,next,dragging){if(!state.anchor)return state;let shift=snapshotShift(prev,next);if(shift===0)return state;let shadow=shiftShadow(state.shadow,prev,shift),follow=(cell)=>cell?{row:clampRowToShadow(cell.row+shift,next.length,shadow),col:cell.col}:cell;return{anchor:follow(state.anchor),head:dragging?state.head:follow(state.head),shadow}}function extractShadowedSelection(snapshot,shadow,range2,wrapped){if(shadow.above.length===0&&shadow.below.length===0)return extractSelection(snapshot,range2,wrapped);let offset=shadow.above.length,rows=[...shadow.above,...snapshot,...shadow.below],shifted=wrapped?[...Array(offset).fill(!1),...wrapped,...Array(shadow.below.length).fill(!1)]:void 0;return extractSelection(rows,{anchor:{row:range2.anchor.row+offset,col:range2.anchor.col},head:{row:range2.head.row+offset,col:range2.head.col}},shifted)}function appTookMouse(previouslyOwned,ownedNow){return ownedNow&&!previouslyOwned}function overlaySelection(rows,range2,firstRow,width,paint="inverse"){if(!range2)return rows;return rows.map((row,i2)=>{let span=rowSpan(range2,firstRow+i2,width);return span?overlayRowSpan(row,span[0],span[1],paint):row})}function followWindowShift(state,prev,next,snapshotLength,dragging){if(!state.anchor||!prev||!next)return state;if(prev.epoch!==next.epoch)return null;let delta=next.startLine-prev.startLine;if(delta===0)return state;let follow=(cell)=>({row:clampRowToShadow(cell.row-delta,snapshotLength,state.shadow),col:cell.col});return{shadow:state.shadow,anchor:follow(state.anchor),head:dragging||!state.head?state.head:follow(state.head)}}import{RGBA as RGBA2,StyledText,TextRenderable}from"@opentui/core";import{RGBA}from"@opentui/core";function toRGBA(rgb){if(!rgb)return;return RGBA.fromInts(rgb[0],rgb[1],rgb[2])}function toTextChunk(c2){return{__isChunk:!0,text:c2.text,...c2.fg?{fg:toRGBA(c2.fg)}:{},...c2.bg?{bg:toRGBA(c2.bg)}:{},...c2.attributes!==void 0?{attributes:c2.attributes}:{}}}function rowsToStyledText(rows){let chunks=[];for(let i2=0;i2<rows.length;i2++){if(i2>0)chunks.push({__isChunk:!0,text:`
64
- `});let row=rows[i2];if(!row)continue;for(let c2 of row)chunks.push(toTextChunk(c2))}return chunks}class TerminalRowPainter{parent;context;rows=[];cols=0;colors=null;constructor(parent,context){this.parent=parent;this.context=context}paint(source,cols,colors){if(this.parent.isDestroyed)return;let invalidate=this.cols!==cols||this.colors!==colors;this.cols=cols,this.colors=colors;for(let y3=0;y3<source.length;y3++){let row=source[y3];if(!row)continue;let painted=this.rows[y3];if(painted&&painted.source===row&&!invalidate)continue;if(!painted&&row.length===0)continue;let content=profileSpan("styled",()=>{let resolved=resolveInverseAttributes([textPresentationRow(row)],colors.foreground,colors.background),sealed=sealRowEndAttributes(resolved,cols,colors.foreground,colors.background);return new StyledText(rowsToStyledText(sealed))});if(!painted){let text=new TextRenderable(this.context,{id:`${this.parent.id}-row-${y3}`,position:"absolute",top:y3,left:0,right:0,height:1,wrapMode:"none",selectable:!1,fg:RGBA2.fromInts(...colors.foreground),content});painted={source:row,text},this.parent.add(text),this.rows[y3]=painted}else{if(invalidate)painted.text.fg=RGBA2.fromInts(...colors.foreground);painted.text.content=content,painted.source=row}profileTick("paintRow")}for(let y3=source.length;y3<this.rows.length;y3++){let row=this.rows[y3];if(row&&!row.text.isDestroyed)this.parent.remove(row.text),row.text.destroy()}if(this.rows.length>source.length)this.rows.length=source.length}dispose(){for(let row of this.rows){if(!row||row.text.isDestroyed)continue;if(!this.parent.isDestroyed)this.parent.remove(row.text);row.text.destroy()}this.rows=[]}}function useTerminalPaint(opts){let{visibleRows,firstRow,cols,selection,cursor,focused,colors}=opts,renderer=useRenderer(),cursorRows=import_react31.useMemo(()=>profileSpan("overlay",()=>{let withSelection=overlaySelection(visibleRows,selection,firstRow,cols);return overlayCursor(withSelection,focused&&!selection?cursor:null,colors)}),[visibleRows,selection,firstRow,cols,cursor,focused,colors]),[grid,setGrid]=import_react31.useState(null),painter=import_react31.useMemo(()=>grid?new TerminalRowPainter(grid,renderer):null,[grid,renderer]);return import_react31.useLayoutEffect(()=>()=>painter?.dispose(),[painter]),import_react31.useLayoutEffect(()=>{painter?.paint(cursorRows,cols,colors)},[painter,cursorRows,cols,colors]),setGrid}var import_react32=__toESM(require_react_production(),1);function useTerminalPointerForward(opts){let{pty,bodyEl,scrollBy}=opts,mouseOwnedByApp=import_react32.useRef(!1),paneCell=(screenX,screenY,body)=>({col:Math.max(1,screenX-body.screenX+1),row:Math.max(1,screenY-body.screenY+1)}),scrollFromPointer=(lines,screenX,screenY,shift=!1)=>{if(lines===0)return!1;let direction=lines<0?"up":"down";if(pty&&!pty.killed&&bodyEl){let{col,row}=paneCell(screenX,screenY,bodyEl);if(pty.wheel(direction,col,row,shift)){for(let i2=1;i2<Math.abs(lines);i2++)pty.wheel(direction,col,row,shift);return!0}}return scrollBy(lines),!1},forwardMouse=(kind,evt)=>{if(kind==="down")mouseOwnedByApp.current=!1;if(!pty||pty.killed||!bodyEl)return!1;if(kind!=="down"&&!mouseOwnedByApp.current)return!1;if(evt.modifiers?.shift)return!1;if(evt.button!==0&&evt.button!==1&&evt.button!==2)return kind!=="down"&&mouseOwnedByApp.current;let{col,row}=paneCell(evt.x,evt.y,bodyEl),forwarded=pty.click(kind,evt.button,col,row,evt.modifiers);if(kind==="down")mouseOwnedByApp.current=forwarded;return forwarded||mouseOwnedByApp.current},lastHoverCell=import_react32.useRef("");return{scrollFromPointer,forwardMouse,forwardHover:(evt)=>{if(!pty||pty.killed||!bodyEl||evt.modifiers?.shift)return;let{col,row}=paneCell(evt.x,evt.y,bodyEl),cell=`${col},${row}`;if(cell===lastHoverCell.current)return;lastHoverCell.current=cell,pty.click("move",0,col,row,evt.modifiers)}}}var import_react35=__toESM(require_react_production(),1);var schedulers=new WeakMap;function terminalFrameScheduler(renderer){let existing=schedulers.get(renderer);if(existing)return existing;let pending=new Set,flush=async()=>{renderer.removeFrameCallback(flush);let batch=[...pending];pending.clear();let requestRender=renderer.requestRender;renderer.requestRender=()=>{};try{flushSync(()=>{for(let refresh of batch)refresh()})}finally{if(renderer.requestRender=requestRender,pending.size>0)renderer.requestRender()}},schedule=(refresh)=>{if(pending.size===0)renderer.setFrameCallback(flush);return pending.add(refresh),renderer.requestRender(),()=>{if(pending.delete(refresh),pending.size===0)renderer.removeFrameCallback(flush)}};return schedulers.set(renderer,schedule),schedule}var NO_WRAP=[];function useTerminalPty(opts){let scheduleRefreshRef=useLatest(terminalFrameScheduler(useRenderer())),[pty,setPty]=import_react35.useState(null),[acquireError,setAcquireError]=import_react35.useState(null),[snapshot,setSnapshot]=import_react35.useState([]),snapshotWindowRef=import_react35.useRef(null),wrappedRef=import_react35.useRef(NO_WRAP),[cursor,setCursor]=import_react35.useState(null),[exited,setExited]=import_react35.useState(!1),commandRef=useLatest(opts.command),machineRef=useLatest(opts.machine),initialInputRef=useLatest(opts.initialInput),firstMessageRef=useLatest(opts.firstMessage),engineBinRef=useLatest(opts.engineBin),defaultColorsRef=useLatest(opts.defaultColors),alternateScreenStyleRewritesRef=useLatest(opts.alternateScreenStyleRewrites),bodyGeometryRef=useLatest(opts.bodyGeometry),registryRef=useLatest(opts.registry),onExitRef=useLatest(opts.onExit),onFreshPtyRef=useLatest(opts.onFreshPty),cwdRef=useLatest(opts.cwd),taskIdRef=useLatest(opts.taskId),geometryReady=opts.bodyGeometry!==null,cwd=opts.cwd,taskId=opts.taskId;import_react35.useEffect(()=>{if(!cwd||!taskId||!geometryReady){setPty(null),setSnapshot([]),snapshotWindowRef.current=null,wrappedRef.current=NO_WRAP,setCursor(null),setAcquireError(null);return}let geometry=bodyGeometryRef.current;if(!geometry)return;let handle;try{handle=registryRef.current.acquire(taskId,cwd,{...geometry,command:commandRef.current,initialInput:initialInputRef.current,firstMessage:firstMessageRef.current,engineBin:engineBinRef.current,defaultColors:defaultColorsRef.current,alternateScreenStyleRewrites:alternateScreenStyleRewritesRef.current,scheduleRefresh:scheduleRefreshRef.current,...machineRef.current?{machine:machineRef.current}:{}})}catch(err){let message=errorMessage(err);setAcquireError(message),setPty(null),setSnapshot([]),snapshotWindowRef.current=null,wrappedRef.current=NO_WRAP,setCursor(null);return}setAcquireError(null),setSnapshot([]),snapshotWindowRef.current=null,wrappedRef.current=NO_WRAP,setCursor(null),setExited(handle.killed),setPty(handle),onFreshPtyRef.current()},[cwd,taskId,geometryReady]),import_react35.useEffect(()=>{let killed=pty?pty.killed:!1;if(setExited(killed),!pty)return;if(killed){onExitRef.current?.({deadOnAttach:pty.deadOnAttach===!0});return}let unsubscribeExit=pty.onExit(()=>{setExited(!0),onExitRef.current?.({deadOnAttach:pty.deadOnAttach===!0})}),unsubscribe=pty.onData((snap,c2,window2,wrapped)=>{snapshotWindowRef.current=window2,wrappedRef.current=wrapped??NO_WRAP,setSnapshot(snap),setCursor(c2)});try{let initial=pty.capture();if(snapshotWindowRef.current=pty.captureWindow(),wrappedRef.current=pty.captureWrapped?.()??NO_WRAP,initial.length>0)setSnapshot(initial);setCursor(pty.captureCursor())}catch{}return()=>{unsubscribeExit(),unsubscribe()}},[pty]);let forceReacquire=import_react35.useCallback((nextCwd,nextTaskId,geometry,expected)=>{try{let opts2={...geometry,command:commandRef.current,initialInput:initialInputRef.current,firstMessage:firstMessageRef.current,engineBin:engineBinRef.current,defaultColors:defaultColorsRef.current,alternateScreenStyleRewrites:alternateScreenStyleRewritesRef.current,scheduleRefresh:scheduleRefreshRef.current},fresh=expected?registryRef.current.resetIfCurrent(nextTaskId,expected,nextCwd,opts2):registryRef.current.reset(nextTaskId,nextCwd,opts2);if(!fresh)return;setPty(fresh),setSnapshot([]),snapshotWindowRef.current=null,wrappedRef.current=NO_WRAP,setCursor(null),onFreshPtyRef.current()}catch(err){let message=errorMessage(err);setAcquireError(message),setPty(null),setSnapshot([]),snapshotWindowRef.current=null,wrappedRef.current=NO_WRAP,setCursor(null)}},[]),resetMountedRef=import_react35.useRef(!1);return import_react35.useEffect(()=>{if(opts.resetToken,!resetMountedRef.current){resetMountedRef.current=!0;return}let nextCwd=cwdRef.current,nextTaskId=taskIdRef.current,geometry=bodyGeometryRef.current;if(nextCwd&&nextTaskId&&geometry)forceReacquire(nextCwd,nextTaskId,geometry)},[opts.resetToken,forceReacquire]),{pty,snapshot,snapshotWindow:snapshotWindowRef.current,wrapped:wrappedRef.current,cursor,exited,acquireError,forceReacquire}}var import_react36=__toESM(require_react_production(),1);function useTerminalReset(args){let t3=useT(),resetTaskIdRef=useLatest(args.taskId),resetCwdRef=useLatest(args.cwd),mountedRef=import_react36.useRef(!0);return import_react36.useLayoutEffect(()=>{return mountedRef.current=!0,()=>{mountedRef.current=!1}},[]),()=>{if(!args.pty&&!args.acquireError)return;let{pty:ptyAtClick,cwd:cwdAtClick,taskId:taskIdAtClick,bodyGeometry:geometryAtClick}=args;if(!cwdAtClick||!taskIdAtClick||!geometryAtClick)return;if(!ptyAtClick){args.forceReacquire(cwdAtClick,taskIdAtClick,geometryAtClick);return}DialogConfirm.show(args.dialog,t3("terminal.reset.title"),t3("terminal.reset.body"),"cancel").then((ok)=>{if(ok!==!0||!mountedRef.current)return;if(resetTaskIdRef.current!==taskIdAtClick||resetCwdRef.current!==cwdAtClick)return;args.forceReacquire(cwdAtClick,taskIdAtClick,geometryAtClick,ptyAtClick)})}}var import_react38=__toESM(require_react_production(),1);import{spawn as spawn2}from"child_process";import{spawnSync}from"child_process";var CLIPBOARD_CANDIDATES={darwin:[["pbcopy"]],linux:[["wl-copy"],["xclip","-selection","clipboard","-in"],["xsel","--clipboard","--input"]],win32:[["clip"],["powershell","-NoProfile","-Command","Set-Clipboard"]]};function resolveClipboardCopyCommand(platform,hasCommand){for(let candidate of CLIPBOARD_CANDIDATES[platform]??[])if(hasCommand(candidate[0]))return candidate;return null}var clipboardBinaryOnPath=(binary)=>{try{let command=process.platform==="win32"?"where":"which";return spawnSync(command,[binary],{encoding:"utf8"}).status===0}catch{return!1}};var resolvedCommand;function clipboardCommand(){if(resolvedCommand===void 0)resolvedCommand=resolveClipboardCopyCommand(process.platform,clipboardBinaryOnPath);return resolvedCommand}function pipeToClipboardCommand(text,cmd){if(!cmd||cmd.length===0)return Promise.resolve(!1);return new Promise((resolve2)=>{try{let proc=spawn2(cmd[0],cmd.slice(1),{stdio:["pipe","ignore","ignore"]}),settled=!1,done=(ok)=>{if(settled)return;settled=!0,resolve2(ok)};proc.on("error",()=>done(!1)),proc.stdin.on("error",()=>done(!1)),proc.on("close",(code)=>done(code===0)),proc.stdin.end(text)}catch{resolve2(!1)}})}async function copyTextToSystemClipboard(text,osc52){let piped=await pipeToClipboardCommand(text,clipboardCommand()),escaped=!1;try{escaped=osc52(text)===!0}catch{}return piped||escaped}var AUTO_SCROLL_MS=50,AUTO_SCROLL_MAX_LINES=5;function useTerminalSelection(opts){let[selAnchor,setSelAnchor]=import_react38.useState(null),[selHead,setSelHead]=import_react38.useState(null),draggingRef=import_react38.useRef(!1),anchorRef=import_react38.useRef(null),renderer=useRenderer(),notifications=useOptionalNotifications(),t3=useT(),selection=import_react38.useMemo(()=>{if(!selAnchor||!selHead)return null;if(selAnchor.row===selHead.row&&selAnchor.col===selHead.col)return null;return{anchor:selAnchor,head:selHead}},[selAnchor,selHead]),resolvePointer=(evt)=>{let{bodyEl:body,bodyGeometry:geometry,bodyRows,visibleRangeStart,snapshot}=opts;if(!body||!geometry)return null;return pointerCell((evt.x??0)-body.screenX,(evt.y??0)-body.screenY,{cols:geometry.cols,rows:bodyRows},visibleRangeStart,snapshot.length)},cellFromEvent=(evt)=>resolvePointer(evt)?.cell??null,captureDrag=(el)=>{renderer?.setCapturedRenderable?.(el??void 0)},beginSelection=(cell)=>{draggingRef.current=!0,captureDrag(opts.bodyEl),appScrolledRef.current=!1,shadowRef.current=EMPTY_SHADOW,lastSnapshotRef.current=opts.snapshot,lastWindowRef.current=opts.snapshotWindow,anchorRef.current=cell,setSelAnchor(cell),setSelHead(cell)},dragPointRef=import_react38.useRef(null),appScrolledRef=import_react38.useRef(!1),shadowRef=import_react38.useRef(EMPTY_SHADOW),lastSnapshotRef=import_react38.useRef(opts.snapshot),lastWindowRef=import_react38.useRef(opts.snapshotWindow),autoScrollRef=import_react38.useRef(null),tickRef=import_react38.useRef(()=>{}),clearSelectionState=()=>{anchorRef.current=null,appScrolledRef.current=!1,shadowRef.current=EMPTY_SHADOW,setSelAnchor(null),setSelHead(null)},stopAutoScroll=()=>{if(!autoScrollRef.current)return;clearInterval(autoScrollRef.current),autoScrollRef.current=null},stopDragging=()=>{draggingRef.current=!1,captureDrag(null),dragPointRef.current=null,stopAutoScroll()},pullFor=(at2,anchor)=>{if(at2.edgePull===0||!anchor)return 0;if(at2.edgePull<0)return at2.cell.row<anchor.row?at2.edgePull:0;return at2.cell.row>anchor.row?at2.edgePull:0},dragTo=(evt)=>{if(!draggingRef.current)return;let at2=resolvePointer(evt);if(!at2)return;if(dragPointRef.current={x:evt.x??0,y:evt.y??0},setSelHead(at2.cell),pullFor(at2,anchorRef.current)===0)stopAutoScroll();else if(!autoScrollRef.current)autoScrollRef.current=setInterval(()=>tickRef.current(),AUTO_SCROLL_MS)};import_react38.useEffect(()=>{tickRef.current=()=>{let point=dragPointRef.current,at2=point&&draggingRef.current?resolvePointer(point):null,pull=at2?pullFor(at2,anchorRef.current):0;if(pull===0||!point){stopAutoScroll();return}let capped=Math.max(-AUTO_SCROLL_MAX_LINES,Math.min(AUTO_SCROLL_MAX_LINES,pull));if(opts.scrollBy(capped,point.x,point.y))appScrolledRef.current=!0}}),import_react38.useEffect(()=>{if(!draggingRef.current)return;let point=dragPointRef.current,at2=point?resolvePointer(point):null;if(at2)setSelHead(at2.cell)},[opts.visibleRangeStart]);let applyShift=(rolled)=>{shadowRef.current=rolled.shadow,anchorRef.current=rolled.anchor,setSelAnchor(rolled.anchor),setSelHead(rolled.head)};import_react38.useEffect(()=>{let prevSnapshot=lastSnapshotRef.current,prevWindow=lastWindowRef.current;if(lastSnapshotRef.current=opts.snapshot,lastWindowRef.current=opts.snapshotWindow,!anchorRef.current)return;let state={anchor:anchorRef.current,head:selHead,shadow:shadowRef.current},windowed=followWindowShift(state,prevWindow,opts.snapshotWindow,opts.snapshot.length,draggingRef.current);if(!windowed){clearSelectionState();return}if(windowed!==state){applyShift(windowed);return}if(!appScrolledRef.current||prevSnapshot===opts.snapshot)return;applyShift(followContentShift(state,prevSnapshot,opts.snapshot,draggingRef.current))},[opts.snapshot,opts.snapshotWindow]);let appOwnedMouseRef=import_react38.useRef(opts.appOwnsMouse);return import_react38.useEffect(()=>{let took=appTookMouse(appOwnedMouseRef.current,opts.appOwnsMouse);if(appOwnedMouseRef.current=opts.appOwnsMouse,!took)return;stopDragging(),clearSelectionState()},[opts.appOwnsMouse]),import_react38.useEffect(()=>()=>{if(autoScrollRef.current)clearInterval(autoScrollRef.current)},[]),{selection,cellFromEvent,beginSelection,dragTo,isDragging:()=>draggingRef.current,endDragging:stopDragging,clearSelection:clearSelectionState,copySelection:()=>{if(!selection)return;let text=extractShadowedSelection(opts.snapshot,shadowRef.current,selection,opts.wrapped);if(text.trim().length===0)return;copyTextToSystemClipboard(text,(payload)=>renderer?.copyToClipboardOSC52(payload)).then((copied)=>{if(!copied)notifications?.notify({kind:"error",taskId:"",tabId:"",title:t3("tasks.toast.copyFailed")})})},noteAppScroll:()=>{if(anchorRef.current)appScrolledRef.current=!0}}}var NO_ROWS=[];function Terminal(props){return $jsx(TerminalSession,{...props},props.taskId)}function TerminalSession(props){let{theme}=useTheme(),t3=useT(),registry=props.registry??getDefaultPtyRegistry(),[focusedLocal,setFocusedLocal]=import_react39.useState(!1),focused=props.focused??focusedLocal,[scrollState,setScrollState]=import_react39.useState(FOLLOW_VIEWPORT),{bodyEl,setBodyEl,bodyRows,bodyGeometry,bumpGeomTick,dims,geomTick}=useTerminalGeometry(),defaultColors=import_react39.useMemo(()=>{let[foregroundR,foregroundG,foregroundB]=theme.text.toInts(),[backgroundR,backgroundG,backgroundB]=theme.background.toInts(),hex=(r6,g3,b3)=>`#${[r6,g3,b3].map((component)=>component.toString(16).padStart(2,"0")).join("")}`;return{foreground:hex(foregroundR,foregroundG,foregroundB),background:hex(backgroundR,backgroundG,backgroundB)}},[theme]),alternateScreenStyleRewrites=import_react39.useMemo(()=>props.terminalPresentation?.alternateScreenStyleRewrites(defaultColors),[props.terminalPresentation,defaultColors]),{pty,snapshot,snapshotWindow,wrapped,cursor,exited,acquireError,forceReacquire}=useTerminalPty({cwd:props.cwd,taskId:props.taskId,machine:props.machine,command:props.command,initialInput:props.initialInput,firstMessage:props.firstMessage,engineBin:props.engineBin,defaultColors,alternateScreenStyleRewrites,resetToken:props.resetToken,onExit:props.onExit,registry,bodyGeometry,onFreshPty:()=>setScrollState(FOLLOW_VIEWPORT)}),scrollOffset=resolveViewportScrollOffset(snapshot.length,bodyRows,scrollState,snapshotWindow),scrollBy=(lines)=>{setScrollState((current2)=>moveViewportScroll(current2,snapshot.length,bodyRows,lines,snapshotWindow))},{scrollFromPointer,forwardMouse,forwardHover}=useTerminalPointerForward({pty,bodyEl,scrollBy}),visibleRange=import_react39.useMemo(()=>computeViewport(snapshot.length,bodyRows,scrollOffset),[snapshot.length,bodyRows,scrollOffset]),visibleRows=import_react39.useMemo(()=>{let rows=snapshot.slice(visibleRange.start,visibleRange.end);return rows.length===0?NO_ROWS:rows},[snapshot,visibleRange]),visibleCursor=import_react39.useMemo(()=>viewportCursor(cursor,scrollOffset,visibleRange),[cursor,scrollOffset,visibleRange]),[imeCursorRetention]=import_react39.useState(()=>new ImeCursorRetention),imeCursor=imeCursorRetention.update(pty,cursor),visibleImeCursor=import_react39.useMemo(()=>viewportCursor(imeCursor,scrollOffset,visibleRange),[imeCursor,scrollOffset,visibleRange]),selection=useTerminalSelection({bodyEl,bodyGeometry,bodyRows,visibleRangeStart:visibleRange.start,snapshot,snapshotWindow,wrapped,scrollBy:scrollFromPointer,appOwnsMouse:pty?.appOwnsMouse??!1}),terminalColors=import_react39.useMemo(()=>{let foreground=theme.text.toInts(),background=theme.background.toInts();return{foreground:[foreground[0],foreground[1],foreground[2]],background:[background[0],background[1],background[2]]}},[theme]),setSnapshotGrid=useTerminalPaint({visibleRows,firstRow:visibleRange.start,cols:bodyGeometry?.cols??80,selection:selection.selection,cursor:visibleCursor,focused,colors:terminalColors}),dialog=useDialog(),imeAnchorActive=(props.imeAnchorActive??!0)&&dialog.stack.length===0,unfocusedAttachmentTarget=props.imeAnchorActive===!0&&dialog.stack.length===0,requestReset=useTerminalReset({pty,acquireError,cwd:props.cwd,taskId:props.taskId,bodyGeometry,forceReacquire,dialog}),copySelectionIfAny=()=>{if(!selection.selection)return!1;return selection.copySelection(),selection.endDragging(),selection.clearSelection(),!0};useTerminalBindings({focused,unfocusedAttachmentTarget,inputModes:()=>pty?.inputModes()??{applicationCursorKeys:!1,applicationKeypad:!1},copySelection:copySelectionIfAny,write:(data)=>{if(data==="\x03"&&copySelectionIfAny())return;if(!pty||pty.killed)return;pty.write(data),props.onUserInput?.(data)},paste:(text)=>{if(!pty||pty.killed)return;pty.paste(text)},scroll:scrollBy,reset:props.engineExit?.onRetry??requestReset}),useTerminalHostCursor({pty,bodyEl,bodyGeometry,visibleImeCursor,imeAnchorActive,dims,geomTick});let[recovery,setRecovery]=import_react39.useState(null);return import_react39.useEffect(()=>{return setRecovery(null),pty?.onRecovery?.(setRecovery)},[pty]),$jsxs("box",{flexDirection:"column",flexGrow:1,overflow:"hidden",backgroundColor:theme.background,onMouseDown:(evt)=>{if(!focused)props.onRequestFocus?.();if(forwardMouse("down",evt))return;if(evt.button!==0)return;let cell=selection.cellFromEvent(evt);if(!cell)return;selection.beginSelection(cell)},onMouseDrag:(evt)=>{if(forwardMouse("drag",evt))return;selection.dragTo(evt)},onMouseMove:forwardHover,onMouseUp:(evt)=>{if(setFocusedLocal(!0),forwardMouse("up",evt))return;if(!selection.isDragging())return;if(selection.endDragging(),selection.selection)selection.copySelection();else selection.clearSelection()},onMouseScroll:(evt)=>{let scroll=evt.scroll;if(!scroll||scroll.direction!=="up"&&scroll.direction!=="down")return;let step=Math.max(1,scroll.delta||1),lines=scroll.direction==="up"?-step:step;if(scrollFromPointer(lines,evt.x,evt.y,evt.modifiers?.shift===!0))selection.noteAppScroll()},children:[recovery!==null&&(!exited||recovery==="restored")?$jsx("box",{flexShrink:0,paddingLeft:1,paddingRight:1,children:$jsx("text",{fg:recovery==="live"?theme.textMuted:theme.warning,wrapMode:"word",children:t3(`terminal.recovery.${recovery}`)})}):null,props.engineExit?$jsx(EngineExitBanner,{...props.engineExit,onRequestFocus:props.onRequestFocus}):props.usageLimit?$jsx(UsageLimitBanner,{...props.usageLimit,onRequestFocus:props.onRequestFocus}):exited?$jsx("box",{flexDirection:"row",flexShrink:0,paddingLeft:1,paddingRight:1,children:$jsx("text",{fg:theme.error,wrapMode:"none",onMouseUp:(event)=>{if(event.stopPropagation(),event.button===0)requestReset()},children:t3("terminal.exited")})}):null,scrollOffset>0?$jsxs("box",{position:"absolute",zIndex:10,left:0,right:0,bottom:0,flexDirection:"row",paddingLeft:1,paddingRight:1,gap:1,onMouseDown:(event)=>event.stopPropagation(),onMouseUp:(event)=>event.stopPropagation(),backgroundColor:theme.backgroundElement,children:[$jsx("text",{fg:theme.warning,wrapMode:"none",children:t3("terminal.scrolledBack",{lines:scrollOffset})}),$jsx("text",{fg:theme.info,wrapMode:"none",onMouseUp:(event)=>{if(event.stopPropagation(),event.button!==0)return;selection.clearSelection(),scrollBy(-snapshot.length),props.onRequestFocus?.()},children:t3("terminal.scrollFirst")}),$jsx("text",{fg:theme.info,wrapMode:"none",onMouseUp:(event)=>{if(event.stopPropagation(),event.button!==0)return;selection.clearSelection(),setScrollState(FOLLOW_VIEWPORT),props.onRequestFocus?.()},children:t3("terminal.scrollLatest")})]}):null,$jsx("box",{ref:bodyGeometry?setBodyEl:(r6)=>setBodyEl(r6),onSizeChange:bumpGeomTick,flexGrow:1,overflow:"hidden",children:pty?$jsx("box",{flexGrow:1,overflow:"hidden",ref:setSnapshotGrid}):$jsx("box",{paddingLeft:1,paddingTop:1,flexDirection:"column",gap:0,children:acquireError?$jsxs($Fragment,{children:[$jsx("text",{fg:theme.error,wrapMode:"word",children:isShellMissing(acquireError)?t3("terminal.unavailable.shellMissing"):t3("terminal.unavailable.spawnFailed")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:acquireError}),$jsx("text",{fg:theme.info,wrapMode:"none",onMouseUp:(event)=>{if(event.stopPropagation(),event.button===0)requestReset()},children:t3("terminal.unavailable.retry")})]}):$jsx("text",{fg:theme.textMuted,children:t3("terminal.noTask")})})})]})}var import_react40=__toESM(require_react_production(),1);function createLiveEngines(opts={}){let entries=opts.entries??(()=>getDefaultPtyRegistry().entries()),snapshot=opts.snapshot??psSnapshot,releaseAfterMisses=Math.max(1,opts.releaseAfterMisses??2),maxQuietSkipMs=opts.maxQuietSkipMs??1e4,now=opts.now??Date.now,vendors=new Map,misses=new Map,answered=new Set,auxPids=new Map,listeners=new Set,disposed=!1,lastWalk=null,emit=()=>{for(let l2 of listeners)l2()},outputStamps=()=>{let out=new Map;for(let[key,pty]of entries())out.set(key,pty.lastOutputAtMs?pty.lastOutputAtMs():null);return out},collectPids=()=>{let pids=new Map,live=new Set;for(let[key,pid]of auxPids)live.add(key),pids.set(key,pid);for(let[key,pty]of entries()){live.add(key);let pid=pty.shellPid??null;if(pid!==null)pids.set(key,pid)}return{pids,live}},walkIsCurrent=()=>{if(!lastWalk||misses.size>0||now()-lastWalk.at>=maxQuietSkipMs)return!1;let{pids}=collectPids();if(pids.size!==lastWalk.pids.size)return!1;for(let[key,pid]of pids)if(lastWalk.pids.get(key)!==pid)return!1;let registry=new Map(entries());for(let key of pids.keys()){let pty=registry.get(key);if(!pty?.lastOutputAtMs||pty.lastOutputAtMs()!==lastWalk.out.get(key))return!1}return!0},store={async probe(){if(disposed)return;let{pids,live}=collectPids(),changed=!1;for(let key of[...vendors.keys()]){if(live.has(key)&&pids.has(key))continue;vendors.delete(key),misses.delete(key),changed=!0}for(let key of[...answered]){if(live.has(key)&&pids.has(key))continue;answered.delete(key)}let out=outputStamps();if(pids.size>0){let rows;try{rows=parsePsSnapshot(await snapshot([...pids.values()]))}catch{if(lastWalk=null,changed)emit();return}if(disposed)return;lastWalk={at:now(),pids,out};for(let[key,pid]of pids){let vendor=foregroundEngineIn(rows,pid)?.vendor??null;answered.add(key);let prev=vendors.get(key)??null;if(vendor){if(misses.delete(key),prev===vendor)continue;vendors.set(key,vendor),changed=!0;continue}if(prev===null)continue;let count=(misses.get(key)??0)+1;if(count<releaseAfterMisses){misses.set(key,count);continue}misses.delete(key),vendors.delete(key),changed=!0}}if(changed)emit()},get(key){return vendors.get(key)??null},resolve(key){let vendor=vendors.get(key);if(vendor)return vendor;return answered.has(key)?null:void 0},setAuxPids(pids){auxPids=pids},subscribe(listener){return listeners.add(listener),()=>{listeners.delete(listener)}},dispose(){disposed=!0,listeners.clear(),vendors.clear(),misses.clear(),answered.clear(),clearInterval(handle)}},handle=setInterval(()=>{if(!walkIsCurrent())store.probe()},opts.intervalMs??2000);return handle.unref?.(),store}var defaultStore=null;function getDefaultLiveEngines(){if(!defaultStore)defaultStore=createLiveEngines();return defaultStore}function createTitleSubscriptions(lookup=getDefaultPtyRegistry().get.bind(getDefaultPtyRegistry())){let subs=new Map,listeners=new Set,emit=()=>{for(let l2 of listeners)l2()};return{reconcile(ptyKeys){let wanted=new Set(ptyKeys),changed=!1;for(let[key,sub]of subs){if((wanted.has(key)?lookup(key):null)===sub.pty)continue;sub.unsub(),subs.delete(key),changed=!0}for(let key of wanted){if(subs.has(key))continue;let pty=lookup(key);if(!pty)continue;let entry2={pty,unsub:()=>{},title:void 0};entry2.unsub=pty.onTitleChange((raw)=>{if(entry2.title===raw)return;entry2.title=raw,emit()}),subs.set(key,entry2),changed=!0}return changed},get(key){return subs.get(key)?.title},subscribe(listener){return listeners.add(listener),()=>{listeners.delete(listener)}},dispose(){for(let sub of subs.values())sub.unsub();subs.clear(),listeners.clear()}}}var TITLE_ATTACH_MS=2000;function useTitleSubscriptions(ptyKeys){let storeRef=import_react40.useRef(null);if(storeRef.current===null)storeRef.current=createTitleSubscriptions();let store=storeRef.current,[titles,setTitles]=import_react40.useState(new Map),ptyKeysRef=useLatest(ptyKeys),reconcile=import_react40.useCallback(()=>{let keys=ptyKeysRef.current;store.reconcile(keys.values());let liveEngines=getDefaultLiveEngines();setTitles((prev)=>{let next=new Map;for(let[id,key]of keys){let title=store.get(key);if(title===void 0)continue;next.set(id,stripEngineStatusPrefix(title,liveEngines.resolve(key)))}if(next.size===prev.size&&[...next].every(([id,v3])=>prev.get(id)===v3))return prev;return next})},[store]);return import_react40.useEffect(()=>{let timer=setInterval(reconcile,TITLE_ATTACH_MS);return()=>clearInterval(timer)},[reconcile]),import_react40.useEffect(()=>{reconcile()},[ptyKeys,reconcile]),import_react40.useEffect(()=>{let active=!0,scheduled=!1,unsub=store.subscribe(()=>{if(scheduled)return;scheduled=!0,queueMicrotask(()=>{if(scheduled=!1,active)reconcile()})});return()=>{active=!1,unsub()}},[store,reconcile]),import_react40.useEffect(()=>()=>store.dispose(),[store]),titles}var UNSPLIT=initialSplit(null);function releaseSplitLeaves(tabKey,tree){if(!tree)return;for(let leaf of leaves(tree.root))if(leaf.id!=="leaf-1")getDefaultPtyRegistry().release(splitLeafPtyKey(tabKey,leaf.id))}function TerminalSplit(props){let{theme,transparentBackground}=useTheme(),inactiveBorder=transparentBackground?theme.border:theme.borderSubtle,t3=useT(),kv=useKV(),state=props.splitTree??UNSPLIT,[activeLeaf,setActiveLeaf]=import_react41.useState(state.activeLeafId);import_react41.useEffect(()=>{setActiveLeaf((props.splitTree??UNSPLIT).activeLeafId)},[props.splitTree]);let fullState=()=>({...state,activeLeafId:activeLeaf}),update=(next)=>{if(next===state)return;props.onSplitChange(collapseSplit(next))},isSplit=isTabSplit(state),splitStyle=isSplit?normalizeSplitStyle(kv.get(SPLIT_STYLE_KEY)):"line",renderViaTree=collapseSplit(state)!==null;function removeAndRelease(id){let cur=fullState(),next=removeLeaf(cur,id);if(next===null)return!1;if(next!==cur)update(next),getDefaultPtyRegistry().release(splitLeafPtyKey(props.tabKey,id));return!0}function onLeafExit(id){if(removeAndRelease(id))return;releaseSplitLeaves(props.tabKey,state),props.onSplitChange(null),props.onExit?.()}let activeLeafSize=()=>getDefaultPtyRegistry().get(splitLeafPtyKey(props.tabKey,activeLeaf))?.size??null;useBindings(()=>({enabled:props.focused,bindings:bindByIds({"workspace.split.right":()=>update(splitActive(fullState(),"row",[defaultShell()],activeLeafSize())),"workspace.split.down":()=>update(splitActive(fullState(),"column",[defaultShell()],activeLeafSize())),"workspace.split.focus-next":()=>setActiveLeaf(cycleLeaf(fullState(),1).activeLeafId)})}));let dialog=useDialog();useBindings(()=>({enabled:props.focused&&isSplit,bindings:bindByIds({"workspace.split.close":prefixAction(()=>removeAndRelease(activeLeaf)),"workspace.split.rename":()=>{let id=activeLeaf;RenameTaskDialog.show(dialog,leafNames.get(id)??"",{dialogTitle:t3("terminal.split.renameTitle"),fieldLabel:t3("terminal.split.renameField"),submitLabel:t3("terminal.tab.renameSubmit"),allowEmpty:!0}).then((title)=>{if(title===void 0)return;update(renameLeaf(fullState(),id,title))})}})}));let leafFocused=(id)=>props.focused&&activeLeaf===id,leafPtyKeys=import_react41.useMemo(()=>{let map=new Map;for(let leaf of leaves(state.root))map.set(leaf.id,splitLeafPtyKey(props.tabKey,leaf.id));return map},[props.tabKey,state]),liveTitles=useTitleSubscriptions(leafPtyKeys),leafNames=splitLeafNames(leaves(state.root),props.command,props.engineTitle,liveTitles),focusedLeaf=props.focused?activeLeaf:null,renderLeaf=(leaf,divider,dividerLit=!1)=>{let focusThis=()=>setActiveLeaf(leaf.id),imeAnchorActive=activeLeaf===leaf.id,focused=leafFocused(leaf.id),name=leafNames.get(leaf.id)??"",chrome=paneChrome(splitStyle,divider),body=$jsxs($Fragment,{children:[$jsx(Terminal,{cwd:props.cwd,taskId:splitLeafPtyKey(props.tabKey,leaf.id),command:leaf.content??props.command,initialInput:leaf.content===null?props.initialInput:void 0,firstMessage:leaf.content===null?props.firstMessage:void 0,engineBin:leaf.content===null?props.engineBin:void 0,terminalPresentation:leaf.content===null?props.terminalPresentation:void 0,engineExit:leaf.content===null?props.engineExit:void 0,usageLimit:leaf.content===null?props.usageLimit:void 0,onUserInput:leaf.content===null?props.onUserInput:void 0,onExit:()=>onLeafExit(leaf.id),resetToken:leaf.id==="leaf-1"?props.resetToken:void 0,focused,imeAnchorActive,onRequestFocus:()=>{props.onRequestFocus?.(),focusThis()}}),isSplit&&!chrome.nameOnRule?$jsx("box",{position:"absolute",right:0,top:0,zIndex:10,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:focused?theme.focusAccent:theme.textMuted,attributes:focused?TextAttributes16.BOLD:TextAttributes16.DIM,wrapMode:"none",children:` ${name} `})}):null]});return $jsx("box",{flexGrow:1,flexShrink:1,flexBasis:0,...paneBoxProps(chrome,{edge:(splitStyle==="line"?dividerLit:focused)?theme.focusAccent:inactiveBorder,name,nameInk:focused?theme.focusAccent:theme.textMuted}),onMouseUp:focusThis,children:body},leaf.id)},renderNode=(node,groupKey,divider,dividerLit=!1)=>node.kind==="leaf"?renderLeaf(node,divider,dividerLit):$jsx("box",{flexDirection:node.orientation,flexGrow:1,flexShrink:1,flexBasis:0,...paneBoxProps(groupChrome(splitStyle,divider),{edge:dividerLit?theme.focusAccent:inactiveBorder}),children:node.children.map((child,i2)=>{let prev=node.children[i2-1],lit=prev!==void 0&&focusedLeaf!==null&&(leafOnEdge(prev,node.orientation,!0,focusedLeaf)||leafOnEdge(child,node.orientation,!1,focusedLeaf));return renderNode(child,child.kind==="leaf"?child.id:`${groupKey}.${i2}`,i2>0?node.orientation==="row"?"left":"top":void 0,lit)})},groupKey);if(renderViaTree)return $jsx("box",{flexDirection:"column",flexGrow:1,overflow:"hidden",children:renderNode(state.root,"root")});return $jsx(Terminal,{cwd:props.cwd,taskId:props.tabKey,command:props.command,initialInput:props.initialInput,firstMessage:props.firstMessage,engineBin:props.engineBin,terminalPresentation:props.terminalPresentation,engineExit:props.engineExit,usageLimit:props.usageLimit,onUserInput:props.onUserInput,onExit:props.onExit,resetToken:props.resetToken,focused:props.focused,imeAnchorActive:!0,onRequestFocus:props.onRequestFocus})}function releaseClosedTabPtys(taskId,closing,closedId){let key=closing?tabPtyKeyFor(taskId,closing):tabPtyKey(taskId,closedId);if(releaseSplitLeaves(key,closing?.splitTree??null),closing?.kind==="engine"&&closing.ptyTask&&closing.ptyTask.tabId===void 0)return;noteClosedPtyKey(key);let registry=getDefaultPtyRegistry(),local=registry.get(key);if(registry.release(key),!local)killHostedSession(key)}function killHostedSession(key){let client=peekSharedPtyClient();if(!client){logClientError("pty",Error(`pty.kill skipped for ${key}: no shared pty client in this process`));return}client.then((c2)=>c2.request("pty.kill",{key})).catch((err)=>{logClientError("pty",Error(`pty.kill failed for ${key}: ${err instanceof Error?err.message:String(err)}`))})}function closeTaskTab(kv,taskId,tabId){let state=knownTabsState(kv,taskId);if(!state||!state.tabs.some((tab)=>tab.id===tabId))return!1;if(requestTabClose(taskId,tabId),!takeUnclaimedTabClose())return!0;let closing=state.tabs.find((tab)=>tab.id===tabId),{state:next,closedId}=closeTab(state,tabId,{allowEmpty:!0});if(!closedId)return!1;return setTaskTabs2(taskId,next),reportTabsDelta(taskId,state.tabs,next.tabs),releaseClosedTabPtys(taskId,closing,closedId),!0}function closeOtherTaskTabs(kv,taskId,keepId){let state=knownTabsState(kv,taskId);if(!state||!state.tabs.some((tab)=>tab.id===keepId))return 0;let closed=0;for(let tab of state.tabs)if(tab.id!==keepId&&closeTaskTab(kv,taskId,tab.id))closed++;return closed}function closeAllTaskTabs(kv,taskId){let state=knownTabsState(kv,taskId);if(!state)return 0;let closed=0;for(let tab of state.tabs)if(closeTaskTab(kv,taskId,tab.id))closed++;return closed}function renameTaskTab(kv,taskId,tabId,title){let state=knownTabsState(kv,taskId);if(!state||!state.tabs.some((tab)=>tab.id===tabId))return!1;if(requestTabRename(taskId,tabId,title),!takeUnclaimedTabRename())return!0;let next=setTabTitle(state,tabId,title);if(next===state)return!0;return setTaskTabs2(taskId,next),!0}var STALE_NOTICE_MS=1e4,NO_NOTICES=createStateCell(null),NO_TAB_OPENS=createStateCell(null),NO_TAB_CLOSES=createStateCell(null),NO_TAB_RENAMES=createStateCell(null),NO_TAB_ADDS=createStateCell(null),NO_PROMPTS=createStateCell(null);function useDaemonTabOpens(orch){let request=useAccessor(orch?orch.tabOpenStore():NO_TAB_OPENS),seenAt=import_react42.useRef(null);import_react42.useEffect(()=>{if(!request||request.at===seenAt.current)return;if(seenAt.current=request.at,Date.now()-request.at>STALE_NOTICE_MS)return;requestTabOpen(request.taskId,request.argv,request.title,request.placement,request.direction,request.tabId)},[request])}function useDaemonTabCloses(orch){let kv=useKV(),request=useAccessor(orch?orch.tabCloseStore():NO_TAB_CLOSES),seenAt=import_react42.useRef(null);import_react42.useEffect(()=>{if(!request||request.at===seenAt.current)return;if(seenAt.current=request.at,Date.now()-request.at>STALE_NOTICE_MS)return;if("requestId"in request){let closed=closeTaskTab(kv,request.taskId,request.tabId);orch?.replyTerminalTabClose(request.requestId,closed);return}requestPaneClose(request.taskId,request.title,request.tabId)},[request,kv,orch])}function useDaemonTabRenames(orch){let kv=useKV(),request=useAccessor(orch?orch.tabRenameStore():NO_TAB_RENAMES),seenAt=import_react42.useRef(null);import_react42.useEffect(()=>{if(!request||request.at===seenAt.current)return;if(seenAt.current=request.at,Date.now()-request.at>STALE_NOTICE_MS)return;renameTaskTab(kv,request.taskId,request.tabId,request.title)},[request,kv])}function useDaemonTabAdds(orch){let kv=useKV(),request=useAccessor(orch?orch.tabAddStore():NO_TAB_ADDS),seenAt=import_react42.useRef(null);import_react42.useEffect(()=>{if(!request||request.at===seenAt.current)return;if(seenAt.current=request.at,Date.now()-request.at>STALE_NOTICE_MS)return;addTaskTab(kv,request.taskId,request.tab)},[request,kv])}function useDaemonPrompts(orch,dialog){let request=useAccessor(orch?orch.uiPromptStore():NO_PROMPTS),seenAt=import_react42.useRef(null),dialogRef=import_react42.useRef(dialog);dialogRef.current=dialog,import_react42.useEffect(()=>{if(!orch||!request||request.at===seenAt.current)return;if(seenAt.current=request.at,Date.now()-request.at>STALE_NOTICE_MS)return;RenameTaskDialog.show(dialogRef.current,request.initial??"",{dialogTitle:request.title,fieldLabel:t("common.prompt.fieldLabel"),submitLabel:t("common.prompt.submitLabel"),placeholder:request.placeholder??"",allowEmpty:!0}).then((value)=>orch.replyPrompt(request.promptId,value))},[request,orch])}function useDaemonNotices(orch,notify,dialog){useDaemonTabOpens(orch),useDaemonTabCloses(orch),useDaemonTabRenames(orch),useDaemonTabAdds(orch),useDaemonPrompts(orch,dialog);let notice=useAccessor(orch?orch.noticeStore():NO_NOTICES),seenAt=import_react42.useRef(null),notifyRef=import_react42.useRef(notify);notifyRef.current=notify,import_react42.useEffect(()=>{if(!notice||notice.at===seenAt.current)return;if(seenAt.current=notice.at,Date.now()-notice.at>STALE_NOTICE_MS)return;let kind=notice.kind==="needs_input"||notice.kind==="error"?notice.kind:"done";notifyRef.current({kind,taskId:notice.taskId??"",tabId:"",title:notice.title,...notice.body?{body:notice.body}:{}})},[notice])}function useTaskColor(taskId){let{theme}=useTheme(),kv=useOptionalKV();if(!taskId||normalizeTaskColors(kv?.get(TASK_COLORS_KEY,DEFAULT_TASK_COLORS))==="off")return;return taskColor(taskId,theme)}var import_react47=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes18}from"@opentui/core";var KEY_HINTS_ENABLED_KEY="hints.keyboard.enabled",PANE_HINT_USED_KEYS={sidebar:"hints.sidebar.used",files:"hints.files.used"};function keyHintsEnabled(raw){return raw!==!1}function keyHintsToggleOn(kv){return keyHintsEnabled(kv.get(KEY_HINTS_ENABLED_KEY,!0))}function toggleKeyHints(kv){let next=!keyHintsToggleOn(kv);if(kv.set(KEY_HINTS_ENABLED_KEY,next),next)for(let key of Object.values(PANE_HINT_USED_KEYS))kv.set(key,!1)}function paneHintVisible(enabledRaw,usedRaw){return keyHintsEnabled(enabledRaw)&&usedRaw!==!0}function statusHintTokens(reach,prefixKey){let tokens=[];if(prefixKey!==null&&reach.prefix.size>0)tokens.push({chord:prefixKey,msg:"commands"});else if(reach.inputPassthrough){let cap=reach.direct.has("focus.sidebar")?legendCap("focus.sidebar"):null;if(cap)tokens.push({chord:cap,msg:"sidebar"})}if(reach.direct.has("help.open")){let cap=legendCap("help.open");if(cap)tokens.push({chord:cap,msg:"help"})}return tokens}var PANE_HINT_ROWS={sidebar:[{id:"sidebar.nav",msg:"move"},{id:"sidebar.select",msg:"open"}],files:[{id:"files.nav",msg:"move"},{id:"files.hierarchy",msg:"collapse"},{id:"files.open",msg:"open",always:!0},{id:"files.diff",msg:"diff",always:!0}]};function paneHintTokens(pane,mode){return PANE_HINT_ROWS[pane].flatMap((row)=>{if(mode==="always"&&row.always!==!0)return[];let cap=legendCap(row.id);return cap?[{cap,msg:row.msg}]:[]})}function wizardKeyLines(prefixKey){let lines=[],nav=legendCap("sidebar.nav"),open=legendCap("sidebar.select");if(nav&&open)lines.push({msg:"keysBare",params:{nav:formatChord(nav),open:formatChord(open)}});let newTab=legendCap("chat.tab.new"),focusNext=legendCap("focus.next");if(newTab&&focusNext)lines.push({msg:"keysOnePress",params:{newTab:formatChord(newTab),focusNext:formatChord(focusNext)}});if(prefixKey!==null)lines.push({msg:"keysPrefix",params:{prefix:formatChord(prefixKey)}});let help=legendCap("help.open");if(help)lines.push({msg:"keysHelp",params:{help:formatChord(help)}});return lines}var import_react46=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes17}from"@opentui/core";function DoctorSuggestions({fixes}){let{theme}=useTheme(),t3=useT();return $jsxs("box",{gap:1,children:[fixes.map((fix)=>$jsxs("box",{children:[$jsx("text",{fg:theme.warning,wrapMode:"word",children:fix.label}),$jsx("text",{fg:theme.primary,wrapMode:"word",children:fix.kind==="manual"?fix.action:fix.command.join(" ")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:fix.why})]},fix.id)),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("common.failureHint",{command:"rove doctor"})})]})}var import_react45=__toESM(require_react_production(),1);var import_react44=__toESM(require_react_production(),1);function quickTaskBindings(field,h2){return[{key:"tab",cmd:()=>h2.cycleField(1)},{key:"shift+tab",cmd:()=>h2.cycleField(-1)},{key:"ctrl+e",cmd:()=>h2.stepEngine(1)},{key:"ctrl+v",cmd:()=>h2.pasteAttachment()},{key:"ctrl+x",cmd:()=>h2.removeLastAttachment()},...field==="attempts"?[{key:"left",cmd:()=>h2.stepAttempts(-1)},{key:"right",cmd:()=>h2.stepAttempts(1)},{key:"h",cmd:()=>h2.stepAttempts(-1)},{key:"l",cmd:()=>h2.stepAttempts(1)},{key:"return",cmd:()=>h2.commit()}]:[],...field==="engine"?[{key:"left",cmd:()=>h2.stepEngine(-1)},{key:"right",cmd:()=>h2.stepEngine(1)},{key:"h",cmd:()=>h2.stepEngine(-1)},{key:"l",cmd:()=>h2.stepEngine(1)},{key:"return",cmd:()=>h2.commit()}]:[]]}var ATTEMPT_CHOICES=["1","2","3","4","5"],FIELDS=["prompt","attempts","engine","branch"];function QuickTaskComposerView(props){let dialog=useDialog(),{theme}=useTheme(),t3=useT(),padX=useDialogPaddingX(),[field,setField]=import_react44.useState("prompt"),[prompt,setPrompt]=import_react44.useState(""),[attempts,setAttempts]=import_react44.useState(1),[vendor,setVendor]=import_react44.useState(props.defaultVendor),[baseRef,setBaseRef]=import_react44.useState(props.defaultBaseRef),[attachments,setAttachments]=import_react44.useState([]);usePaste((event)=>{let paths=asAttachmentPaths(new TextDecoder().decode(event.bytes));if(!paths)return;event.preventDefault(),setAttachments((prev)=>[...prev,...paths.filter((p3)=>!prev.includes(p3))])});function pasteAttachment(){captureClipboardAttachment().then((path)=>{if(path)setAttachments((prev)=>prev.includes(path)?prev:[...prev,path])})}function cycleField(dir){setField((f2)=>{let i2=FIELDS.indexOf(f2);return FIELDS[(i2+dir+FIELDS.length)%FIELDS.length]??"prompt"})}function stepAttempts(dir){setAttempts((n2)=>Math.min(ATTEMPT_CHOICES.length,Math.max(1,n2+dir)))}function stepEngine(dir){let list=props.engines;if(list.length===0)return;if(dir>0){setVendor((v3)=>nextVendorWithin(list,v3));return}setVendor((v3)=>{let i2=Math.max(0,list.indexOf(v3));return list[(i2-1+list.length)%list.length]??v3})}function commit(){if(isBlankText(prompt)){setField("prompt");return}props.onSubmit({prompt:prompt.trim(),vendor,baseRef:baseRef.trim()||props.defaultBaseRef,attachments,attempts}),dialog.clear()}return useBindings(()=>({enabled:!0,bindings:quickTaskBindings(field,{cycleField,stepAttempts,stepEngine,commit,pasteAttachment,removeLastAttachment:()=>setAttachments((prev)=>prev.slice(0,-1))})})),$jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:0,children:[$jsx(DialogHeader2,{title:t3("quickTask.title",{repoLabel:props.repoLabel}),onClose:()=>props.onCancel()}),props.intent?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:props.intent}):null,$jsxs("box",{gap:1,paddingTop:1,children:[$jsx(DialogSection2,{label:t3("quickTask.promptLabel"),focused:field==="prompt",onPress:()=>setField("prompt"),children:$jsx(DialogField2,{focused:field==="prompt",children:$jsx("input",{value:prompt,placeholder:t3("quickTask.promptPlaceholder"),focused:field==="prompt",onInput:(v3)=>setPrompt(stripNewlines2(v3)),onSubmit:()=>commit(),onMouseUp:()=>setField("prompt")})})}),attachments.length>0?$jsx("box",{flexDirection:"row",gap:2,flexWrap:"wrap",children:attachments.map((path,i2)=>$jsx("text",{fg:theme.primary,wrapMode:"none",flexShrink:0,onMouseUp:()=>setAttachments((prev)=>prev.filter((p3)=>p3!==path)),children:attachmentLabel(path,i2)},path))}):null,$jsx(DialogSection2,{label:t3("quickTask.attemptsLabel"),focused:field==="attempts",hint:"\u2190/\u2192",onPress:()=>setField("attempts"),children:$jsx(ChipRow2,{choices:ATTEMPT_CHOICES,selected:String(attempts),onPick:(v3)=>{setAttempts(Number(v3)),setField("attempts")}})}),$jsx(DialogSection2,{label:t3("quickTask.engineLabel"),focused:field==="engine",hint:"\u2190/\u2192",onPress:()=>setField("engine"),children:$jsx(ChipRow2,{choices:props.engines,selected:vendor,display:(v3)=>props.engineLabel(v3),onPick:(v3)=>{setVendor(v3),setField("engine")}})}),$jsx(DialogSection2,{label:t3("quickTask.branchLabel"),focused:field==="branch",onPress:()=>setField("branch"),children:$jsx(DialogField2,{focused:field==="branch",children:$jsx("input",{value:baseRef,placeholder:props.defaultBaseRef,focused:field==="branch",onInput:(v3)=>setBaseRef(stripNewlines2(v3)),onSubmit:()=>commit(),onMouseUp:()=>setField("branch")})})}),$jsx(DialogFooter2,{children:t3("quickTask.legend")})]})]})}function show4(dialog,opts){return showDialog(dialog,(resolve2)=>$jsx(QuickTaskComposerView,{...opts,onSubmit:(r6)=>resolve2(r6),onCancel:()=>resolve2(void 0)}),{size:"medium"})}var QuickTaskComposer={show:show4};function firstTaskRepo(cwd){try{return validateRepoPath(cwd)===null?resolveMainRepoRoot(cwd):null}catch{return null}}function FirstTaskStart(props){let{theme}=useTheme(),t3=useT(),dialog=useDialog(),[repo]=import_react45.useState(()=>firstTaskRepo(process.cwd())),[opening,setOpening]=import_react45.useState(!1);if(repo===null||!props.env.git||props.env.engines.length===0)return null;let start=async()=>{if(opening)return;setOpening(!0);try{let engines=props.env.engines,result=await QuickTaskComposer.show(dialog,{...quickForkComposerOptions(repo,engines,quickForkDefaultVendor2(repo,engines),process.cwd()),intent:t3("onboarding.quickIntent",{key:formatChord(legendCap("task.new")??"n")})});if(result)props.onCreate(repo,result)}finally{setOpening(!1)}};return $jsxs("box",{paddingTop:1,flexDirection:"column",children:[$jsx("box",{onMouseUp:()=>void start(),children:$jsx("text",{fg:theme.primary,children:t3("onboarding.quickStart")})}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("onboarding.quickIntent",{key:formatChord(legendCap("task.new")??"n")})})]})}async function probeWelcomeEnv(){let{usable,signedOut}=await probeableEngineIds().then(detectEngineStatuses).then(summarizeEngines).catch(()=>({usable:[],signedOut:[]})),git=globalThis.Bun?.which?globalThis.Bun.which("git")!==null:!0;return{engines:usable,signedOut,git}}function stepLines(){let lines=[],newTask=legendCap("task.new");if(newTask)lines.push({cap:formatChord(newTask),msg:"stepNew"});let help=legendCap("help.open");if(help)lines.push({cap:formatChord(help),msg:"stepHelp"});let prefix=currentPrefixConfiguration().key;if(prefix!==null)lines.push({cap:formatChord(prefix),msg:"stepPrefix"});return lines}function WelcomePane(props){let{theme}=useTheme(),t3=useT(),[env,setEnv]=import_react46.useState(null),probe=props.probe??probeWelcomeEnv;import_react46.useEffect(()=>{let alive=!0;return probe().then((result)=>{if(alive)setEnv(result)}),()=>{alive=!1}},[]);let steps=stepLines(),capWidth=Math.max(...steps.map((s2)=>displayWidth(s2.cap)),0),broken=env!==null&&(env.engines.length===0||!env.git),engineLine=env===null?null:env.engines.length>0?{key:"enginesFound",fg:theme.textMuted,list:env.engines.map(engineDisplayName).join(" \xB7 ")}:env.signedOut.length>0?{key:"enginesSignedOut",fg:theme.warning,list:env.signedOut.map(engineDisplayName).join(" \xB7 ")}:{key:"enginesMissing",fg:theme.warning,list:""};return $jsx("scrollbox",{flexGrow:1,contentOptions:{alignItems:"center"},children:$jsxs("box",{flexDirection:"column",flexShrink:0,maxWidth:72,paddingLeft:2,paddingRight:2,children:[$jsx("text",{fg:theme.primary,attributes:TextAttributes17.BOLD,wrapMode:"none",children:t3("workspace.welcome.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("workspace.welcome.tagline")}),$jsx("box",{flexDirection:"column",paddingTop:1,children:steps.map((step)=>$jsxs("box",{flexDirection:"row",gap:2,children:[$jsx("text",{fg:theme.primary,wrapMode:"none",children:padEndCells(step.cap,capWidth)}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3(`workspace.welcome.${step.msg}`)})]},step.msg))}),$jsx("box",{paddingTop:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("workspace.welcome.worktreeExplain")})}),env!==null&&engineLine!==null?$jsxs("box",{flexDirection:"column",paddingTop:1,children:[$jsx("text",{fg:engineLine.fg,wrapMode:"word",children:t3(`workspace.welcome.${engineLine.key}`,{list:engineLine.list})}),env.git?null:$jsx("text",{fg:theme.warning,wrapMode:"word",children:t3("workspace.welcome.gitMissing")}),broken?$jsx(DoctorSuggestions,{fixes:[...!env.git?[humanOnlyFix("git")]:[],...env.engines.length===0?[noEngineFix(env.signedOut)]:[]]}):null]}):null,env&&props.onQuickTask?$jsx(FirstTaskStart,{env,onCreate:props.onQuickTask}):null,$jsx("box",{paddingTop:1,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes17.DIM,wrapMode:"none",children:t3("workspace.welcome.docsHint")})})]})})}function EngineWelcomePage(props){let{theme}=useTheme(),t3=useT(),env=props.env;return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,children:t3("onboarding.engineTitle")}),env===null?$jsx("text",{fg:theme.textMuted,children:t3("onboarding.engineChecking")}):$jsxs($Fragment,{children:[$jsx("text",{fg:env.engines.length?theme.success:theme.warning,children:t3(env.engines.length?"onboarding.engineReady":"onboarding.engineMissing")}),env.engines.map((id)=>$jsx("text",{fg:theme.textMuted,children:t3("onboarding.engineUsable",{engine:engineDisplayName(id)})},id)),env.signedOut.map((id)=>$jsx("text",{fg:theme.warning,children:t3("onboarding.engineSignedOut",{engine:engineDisplayName(id)})},id)),env.engines.length===0?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("onboarding.engineSetup")}):null,!env.git?$jsx("text",{fg:theme.warning,children:t3("workspace.welcome.gitMissing")}):null,$jsx("box",{onMouseUp:props.onContinue,children:$jsx("text",{fg:theme.primary,children:t3("onboarding.engineContinue")})})]})]})}var PAD_X=2;function WelcomeDialogView(props){let{theme}=useTheme(),t3=useT(),[skillLine,setSkillLine]=import_react47.useState(null),steps=props.shell===null?["skill"]:["completions","skill"],[stepIndex,setStepIndex]=import_react47.useState(0),[yes,setYes]=import_react47.useState(!0),[answers,setAnswers]=import_react47.useState({}),[page,setPage]=import_react47.useState("engine"),[env,setEnv]=import_react47.useState(null),probe=props.probe??probeWelcomeEnv;import_react47.useEffect(()=>{let alive=!0;return probe().then((value)=>{if(alive)setEnv(value)}),()=>{alive=!1}},[probe]);let step=steps[stepIndex],answeredSteps=steps.slice(0,page==="questions"?stepIndex:steps.length);function finish(finalAnswers){props.onDone({completions:finalAnswers.completions??!1})}function confirm(choice=yes){if(page==="engine"){if(env!==null)setPage("questions");return}if(page==="keys"){finish(answers);return}let next={...answers,[step]:choice};if(setAnswers(next),step==="skill"&&choice)setSkillLine((props.installSkill??(()=>installSkillLine(t3)))());if(props.onAnswers?.({completions:next.completions??!1}),stepIndex+1>=steps.length){setPage("keys");return}setStepIndex(stepIndex+1),setYes(!0)}useBindings(()=>({bindings:[{key:"up",cmd:()=>setYes(!0)},{key:"k",cmd:()=>setYes(!0)},{key:"down",cmd:()=>setYes(!1)},{key:"j",cmd:()=>setYes(!1)},{key:"return",cmd:()=>confirm()}]}));function labelFor(s2){return s2==="completions"?t3("onboarding.completionsLabel",{shell:props.shell??""}):t3("onboarding.skillLabel")}let explain=step==="completions"?t3("onboarding.completionsExplain"):t3("onboarding.skillExplain");return $jsxs("box",{paddingLeft:PAD_X,paddingRight:PAD_X,gap:1,flexShrink:1,children:[$jsxs("box",{flexDirection:"column",gap:0,flexShrink:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes18.BOLD,wrapMode:"none",children:t3("onboarding.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("onboarding.subtitle")})]}),$jsxs("box",{flexDirection:"column",flexShrink:1,children:[page!=="engine"&&answeredSteps.length>0?$jsx("box",{flexDirection:"column",paddingBottom:1,children:answeredSteps.map((answered)=>$jsxs("box",{flexDirection:"row",gap:1,children:[$jsx("text",{fg:answers[answered]?theme.success:theme.textMuted,wrapMode:"none",children:answers[answered]?"\u2713":"\u2013"}),$jsx("text",{fg:theme.text,wrapMode:"none",children:labelFor(answered)}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:`\xB7 ${!answers[answered]?t3("onboarding.skipped"):answered==="skill"?skillLine:t3("onboarding.queued")}`})]},answered))}):null,page==="engine"?$jsx(EngineWelcomePage,{env,onContinue:()=>confirm()}):page==="keys"?$jsxs("box",{flexDirection:"column",onMouseUp:()=>confirm(),children:[$jsx("text",{fg:theme.text,attributes:TextAttributes18.BOLD,wrapMode:"word",children:t3("onboarding.keysTitle")}),wizardKeyLines(currentPrefixConfiguration().key).map((line)=>$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3(`onboarding.${line.msg}`,line.params)},line.msg)),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("onboarding.keysNext")})]}):$jsxs($Fragment,{children:[$jsxs("box",{flexDirection:"row",children:[$jsx("text",{fg:theme.text,attributes:TextAttributes18.BOLD,wrapMode:"none",flexGrow:1,children:labelFor(step)}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("onboarding.stepCounter",{n:String(stepIndex+1),total:String(steps.length)})})]}),$jsx("box",{paddingBottom:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:explain})}),[!0,!1].map((option)=>{let active=yes===option;return $jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,paddingRight:1,backgroundColor:active?theme.primary:void 0,onMouseUp:()=>confirm(option),children:[$jsx("text",{fg:active?theme.selectedListItemText:theme.text,wrapMode:"none",children:option?t3("onboarding.optionYes"):t3("onboarding.optionNo")}),option&&step==="skill"?$jsx("text",{fg:active?theme.selectedListItemText:theme.textMuted,wrapMode:"none",children:t3("onboarding.recommended")}):null]},String(option))})]})]}),$jsx("box",{paddingBottom:1,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes18.DIM,wrapMode:"none",children:t3(page==="engine"?"onboarding.engineLegend":page==="keys"?"onboarding.keysLegend":"onboarding.legend")})})]})}function installSkillLine(t3){let engines=skillTargets().map((target)=>target.displayName);if(engines.length===0)return t3("onboarding.skillNoEngines");let error=installSkillErrors();return error?t3("onboarding.skillFailed",{reason:error}):t3("onboarding.skillInstalled",{engines:engines.join(", ")})}function show5(dialog,opts){let settled=!1,confirmed={completions:!1},once=(choices)=>{if(settled)return;settled=!0,opts.onDone(choices)};dialog.replace(()=>$jsx(WelcomeDialogView,{shell:opts.shell,onAnswers:(choices)=>{confirmed=choices},onDone:(choices)=>{once(choices),dialog.clear()}}),()=>once(confirmed)),dialog.setSize("medium")}var WelcomeDialog={show:show5};function useWelcomeDialog(request,onClosed){let dialog=useDialog(),opened=import_react47.useRef(!1),shell=request?.shell??null;import_react47.useEffect(()=>{if(request===null||opened.current)return;opened.current=!0,WelcomeDialog.show(dialog,{shell,onDone:(choices)=>{onClosed(),trackWelcomeWrite(import("./chunk-zrf93zrx.js").then((m3)=>m3.recordWelcomeChoices(choices,shell)))}})},[request,dialog,onClosed,shell])}var import_react49=__toESM(require_react_production(),1);var SIDEBAR_WIDTH=24;function sidebarWidthFor(terminalWidth){return Math.max(SIDEBAR_WIDTH,Math.min(40,Math.floor(terminalWidth/6)))}var MIN_WORKSPACE_WIDTH=40;function resolveSidebarWidth(terminalWidth,override){if(override==null)return sidebarWidthFor(terminalWidth);let max=Math.max(SIDEBAR_WIDTH,terminalWidth-MIN_WORKSPACE_WIDTH);return Math.max(SIDEBAR_WIDTH,Math.min(max,Math.round(override)))}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 rowTokenTone(tone){switch(tone){case"info":return"primary";case"success":return"success";case"warning":return"warning";case"error":return"error";default:return"textMuted"}}function toneColor2(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 seq2=evt.sequence;if(!seq2||seq2.length!==1)return null;let code=seq2.charCodeAt(0);if(code<32||code===127)return null;return query+seq2}var listeners=new Set,tickCount=0,timer=null;function tick(){tickCount++;for(let listener of listeners)try{listener()}catch{}}function sidebarPollClockSnapshot(){return tickCount}function subscribeSidebarPollClock(listener){if(listeners.add(listener),timer===null)timer=setInterval(tick,MAIN_BRANCH_POLL_MS),timer.unref?.();return()=>{if(listeners.delete(listener),listeners.size===0&&timer!==null)clearInterval(timer),timer=null}}function rowStatusTone(status){switch(status?.kind){case"busy":case"running":case"unseen":return"accent";case"needs-input":return"warning";case"attention":return status.reason==="rate_limited"?"warning":"error";default:return"muted"}}function rowStatusGlyph(status,glyphs,frame=0){let tone=rowStatusTone(status);switch(status?.kind){case"busy":case"running":return{glyph:glyphs.spinner[frame%Math.max(1,glyphs.spinner.length)]??glyphs.idle,tone,spinning:!0};case"needs-input":return{glyph:glyphs.needsInput,tone,spinning:!1};case"attention":return{glyph:glyphs.attention,tone,spinning:!1};case"unseen":return{glyph:glyphs.unseen,tone,spinning:!1};default:return{glyph:glyphs.idle,tone,spinning:!1}}}var TONES={accent:"primary",warning:"warning",error:"error",muted:"textMuted"};function sidebarTone(tone){return TONES[tone]}var SPINNER_FRAME_MS=80,SPINNER_TICK_CYCLE=600,DONE_PULSE_MS=600;function noTrackingSubtitle(){return t("tasks.subtitle.noTracking")}function materializingSubtitle(){return t("tasks.subtitle.materializing")}function deletionSubtitle(failed){return failed?t("tasks.subtitle.deleteFailed"):t("tasks.subtitle.deleting")}function isCustomEngineTask(task){if(task.kind==="main")return!1;return task.vendor!==void 0&&!isBuiltinVendor(task.vendor)}function rowIsLoading(status){return rowStatusGlyph(status,DEFAULT_GLYPHS).spinning}function buildSidebarRowView(opts){let{task,status}=opts,isMain=task.kind==="main",branch=isMain?opts.mainBranch??"":task.branch,glyphs=opts.glyphs??DEFAULT_GLYPHS,mark=rowStatusGlyph(status,glyphs),untrackedCustomEngine=isCustomEngineTask(task)&&status?.state===void 0&&!mark.spinning,materializing=status?.kind==="busy"&&status.reason==="job",deleting=task.deletion?.phase==="queued"||task.deletion?.phase==="running",deleteFailed=task.deletion?.phase==="error",loading=mark.spinning,spinnerFrames=glyphs.spinner,stateGlyph=loading?breathGlyph(spinnerFrames,opts.spinnerFrame):mark.glyph,fallbackSubtitle=untrackedCustomEngine?noTrackingSubtitle():"\u2014",subagents=loading?opts.lifecycle?.subagents??0:0,branchWithMarks=subagents>0&&branch.length>0?`${glyphs.subagent}${subagents} ${branch}`:branch,subtitleText=deleting||deleteFailed?opts.truncateBranch(deletionSubtitle(deleteFailed),opts.subtitleBudget):materializing?opts.truncateBranch(materializingSubtitle(),opts.subtitleBudget):branchWithMarks.length>0?opts.truncateBranch(branchWithMarks,opts.subtitleBudget):opts.truncateBranch(fallbackSubtitle,opts.subtitleBudget);return{isMain,titleText:isMain?repoBasename(task.repo):task.title,subtitleText,loading,stateGlyph,tone:sidebarTone(mark.tone),spinnerFrames,materializing}}function withSpinnerFrame(view,frame){if(!view.loading)return view;let frames=view.spinnerFrames,spinner=breathGlyph(frames,frame());if(spinner===view.stateGlyph)return view;return{...view,stateGlyph:spinner}}var listeners2=new Set,frame=0,timer2=null;function tick2(){frame=(frame+1)%SPINNER_TICK_CYCLE;for(let listener of listeners2)try{listener()}catch{}}function spinnerFrameSnapshot(){return frame}function subscribeSpinnerFrame(listener){if(listeners2.add(listener),timer2===null)timer2=setInterval(tick2,SPINNER_FRAME_MS),timer2.unref?.();return()=>{if(listeners2.delete(listener),listeners2.size===0&&timer2!==null)clearInterval(timer2),timer2=null,frame=0}}var POLL_TIMEOUT_MS=4000,SLOW_REPO_RETRY_MS=60000,MIN_POLL_INTERVAL_MS=1500,poller=createBackgroundPoller({initial:null,equals:sameWorktreeChanges,timeoutMs:POLL_TIMEOUT_MS,slowRetryMs:SLOW_REPO_RETRY_MS,minIntervalMs:MIN_POLL_INTERVAL_MS,run:async(worktreePath,signal)=>{recordSpawn("sidebar.worktreeChanges",["git","status","--porcelain=v1"],worktreePath);let res=await spawnCapture("git",["status","--porcelain=v1"],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal});if(res.status!==0)throw Error("git status failed");return parsePorcelain(res.stdout)}});var import_react48=__toESM(require_react_production(),1);function useDiffInks(){let{theme}=useTheme(),kv=useOptionalKV(),colorblind=normalizeColorblind(kv?.get(COLORBLIND_KEY,DEFAULT_COLORBLIND))==="on";return import_react48.useMemo(()=>diffInks(theme,colorblind),[theme,colorblind])}var NOOP_SUBSCRIBE=()=>()=>{},ZERO_FRAME=()=>0;function useSpinnerFrame(active){return import_react49.useSyncExternalStore(active?subscribeSpinnerFrame:NOOP_SUBSCRIBE,active?spinnerFrameSnapshot:ZERO_FRAME)}function usePollOnClock(key,poll){import_react49.useEffect(()=>{if(!key)return;return poll(key),subscribeSidebarPollClock(()=>poll(key))},[key,poll])}function useClockTick(active){return import_react49.useSyncExternalStore(active?subscribeSidebarPollClock:NOOP_SUBSCRIBE,active?sidebarPollClockSnapshot:ZERO_FRAME)}function completionStampOf(activity){return activity?.state==="turn_complete"?activity.at:void 0}function useDonePulse(completionAt){let[pulsingAt,setPulsingAt]=import_react49.useState(null),seenRef=import_react49.useRef(void 0),seeded=import_react49.useRef(!1);return import_react49.useEffect(()=>{let previous=seenRef.current;if(seenRef.current=completionAt,!seeded.current){seeded.current=!0;return}if(completionAt===void 0||completionAt===previous)return;setPulsingAt(completionAt);let timer3=setTimeout(()=>setPulsingAt(null),DONE_PULSE_MS);return()=>clearTimeout(timer3)},[completionAt]),pulsingAt!==null&&pulsingAt===completionAt}var import_react50=__toESM(require_react_production(),1);var SORT_MODE_CYCLE=["default","recent","attention","name"];function readSortMode(stored){return SORT_MODE_CYCLE.find((mode)=>mode===stored)??"recent"}function useSidebarHostState(args){let{kv,tasks:tasks2,focusSidebar,notify}=args,[sortMode,setSortMode]=import_react50.useState(()=>readSortMode(kv.get("activeSortMode"))),toggleSortMode=()=>{let next=SORT_MODE_CYCLE[(SORT_MODE_CYCLE.indexOf(sortMode)+1)%SORT_MODE_CYCLE.length]??"default";setSortMode(next),kv.set("activeSortMode",next)},[moveMode,setMoveModeState]=import_react50.useState(!1),setMoveMode=(next)=>{if(next&&sortMode!=="default")setSortMode("default"),kv.set("activeSortMode","default"),notify?.(t("tasks.sort.reorderSwitched"));setMoveModeState(next)};return{sortMode,setSortMode,toggleSortMode,moveMode,setMoveMode,onLocalMergeRequest:(id)=>{if(!tasks2.find((row)=>row.id===id))return;if(!moveMode)focusSidebar();setMoveMode(!moveMode)}}}var import_react51=__toESM(require_react_production(),1);import{spawnSync as spawnSync2}from"child_process";function planSelfRefresh(inputs){if(inputs.staleInstall)return{kind:"unavailable",reason:"install-gone"};let stale=!!inputs.daemonVersion&&inputs.daemonVersion!==inputs.clientVersion;if(inputs.daemonRestarting)return{kind:"refresh",restartDaemon:!1};if(stale)return{kind:"refresh",restartDaemon:!0};return{kind:"current"}}function selfRelaunchArgv(proc){return[proc.execPath,...proc.execArgv,...proc.argv.slice(1)]}function relaunchSelf(opts){try{opts.renderer?.destroy()}catch(err){console.error("Rove: renderer.destroy() failed during refresh:",err)}let argv=selfRelaunchArgv(opts.proc??process),[command,...args]=argv;if(opts.notice)process.stdout.write(`
64
+ `});let row=rows[i2];if(!row)continue;for(let c2 of row)chunks.push(toTextChunk(c2))}return chunks}class TerminalRowPainter{parent;context;rows=[];cols=0;colors=null;constructor(parent,context){this.parent=parent;this.context=context}paint(source,cols,colors){if(this.parent.isDestroyed)return;let invalidate=this.cols!==cols||this.colors!==colors;this.cols=cols,this.colors=colors;for(let y3=0;y3<source.length;y3++){let row=source[y3];if(!row)continue;let painted=this.rows[y3];if(painted&&painted.source===row&&!invalidate)continue;if(!painted&&row.length===0)continue;let content=profileSpan("styled",()=>{let resolved=resolveInverseAttributes([textPresentationRow(row)],colors.foreground,colors.background),sealed=sealRowEndAttributes(resolved,cols,colors.foreground,colors.background);return new StyledText(rowsToStyledText(sealed))});if(!painted){let text=new TextRenderable(this.context,{id:`${this.parent.id}-row-${y3}`,position:"absolute",top:y3,left:0,right:0,height:1,wrapMode:"none",selectable:!1,fg:RGBA2.fromInts(...colors.foreground),content});painted={source:row,text},this.parent.add(text),this.rows[y3]=painted}else{if(invalidate)painted.text.fg=RGBA2.fromInts(...colors.foreground);painted.text.content=content,painted.source=row}profileTick("paintRow")}for(let y3=source.length;y3<this.rows.length;y3++){let row=this.rows[y3];if(row&&!row.text.isDestroyed)this.parent.remove(row.text),row.text.destroy()}if(this.rows.length>source.length)this.rows.length=source.length}dispose(){for(let row of this.rows){if(!row||row.text.isDestroyed)continue;if(!this.parent.isDestroyed)this.parent.remove(row.text);row.text.destroy()}this.rows=[]}}function useTerminalPaint(opts){let{visibleRows,firstRow,cols,selection,cursor,focused,colors}=opts,renderer=useRenderer(),cursorRows=import_react31.useMemo(()=>profileSpan("overlay",()=>{let withSelection=overlaySelection(visibleRows,selection,firstRow,cols);return overlayCursor(withSelection,focused&&!selection?cursor:null,colors)}),[visibleRows,selection,firstRow,cols,cursor,focused,colors]),[grid,setGrid]=import_react31.useState(null),painter=import_react31.useMemo(()=>grid?new TerminalRowPainter(grid,renderer):null,[grid,renderer]);return import_react31.useLayoutEffect(()=>()=>painter?.dispose(),[painter]),import_react31.useLayoutEffect(()=>{painter?.paint(cursorRows,cols,colors)},[painter,cursorRows,cols,colors]),setGrid}var import_react32=__toESM(require_react_production(),1);function useTerminalPointerForward(opts){let{pty,bodyEl,scrollBy}=opts,mouseOwnedByApp=import_react32.useRef(!1),paneCell=(screenX,screenY,body)=>({col:Math.max(1,screenX-body.screenX+1),row:Math.max(1,screenY-body.screenY+1)}),scrollFromPointer=(lines,screenX,screenY,shift=!1)=>{if(lines===0)return!1;let direction=lines<0?"up":"down";if(pty&&!pty.killed&&bodyEl){let{col,row}=paneCell(screenX,screenY,bodyEl);if(pty.wheel(direction,col,row,shift)){for(let i2=1;i2<Math.abs(lines);i2++)pty.wheel(direction,col,row,shift);return!0}}return scrollBy(lines),!1},forwardMouse=(kind,evt)=>{if(kind==="down")mouseOwnedByApp.current=!1;if(!pty||pty.killed||!bodyEl)return!1;if(kind!=="down"&&!mouseOwnedByApp.current)return!1;if(evt.modifiers?.shift)return!1;if(evt.button!==0&&evt.button!==1&&evt.button!==2)return kind!=="down"&&mouseOwnedByApp.current;let{col,row}=paneCell(evt.x,evt.y,bodyEl),forwarded=pty.click(kind,evt.button,col,row,evt.modifiers);if(kind==="down")mouseOwnedByApp.current=forwarded;return forwarded||mouseOwnedByApp.current},lastHoverCell=import_react32.useRef("");return{scrollFromPointer,forwardMouse,forwardHover:(evt)=>{if(!pty||pty.killed||!bodyEl||evt.modifiers?.shift)return;let{col,row}=paneCell(evt.x,evt.y,bodyEl),cell=`${col},${row}`;if(cell===lastHoverCell.current)return;lastHoverCell.current=cell,pty.click("move",0,col,row,evt.modifiers)}}}var import_react35=__toESM(require_react_production(),1);var schedulers=new WeakMap;function terminalFrameScheduler(renderer){let existing=schedulers.get(renderer);if(existing)return existing;let pending=new Set,flush=async()=>{renderer.removeFrameCallback(flush);let batch=[...pending];pending.clear();let requestRender=renderer.requestRender;renderer.requestRender=()=>{};try{flushSync(()=>{for(let refresh of batch)refresh()})}finally{if(renderer.requestRender=requestRender,pending.size>0)renderer.requestRender()}},schedule=(refresh)=>{if(pending.size===0)renderer.setFrameCallback(flush);return pending.add(refresh),renderer.requestRender(),()=>{if(pending.delete(refresh),pending.size===0)renderer.removeFrameCallback(flush)}};return schedulers.set(renderer,schedule),schedule}var NO_WRAP=[];function useTerminalPty(opts){let scheduleRefreshRef=useLatest(terminalFrameScheduler(useRenderer())),[pty,setPty]=import_react35.useState(null),[acquireError,setAcquireError]=import_react35.useState(null),[snapshot,setSnapshot]=import_react35.useState([]),snapshotWindowRef=import_react35.useRef(null),wrappedRef=import_react35.useRef(NO_WRAP),[cursor,setCursor]=import_react35.useState(null),[exited,setExited]=import_react35.useState(!1),commandRef=useLatest(opts.command),machineRef=useLatest(opts.machine),initialInputRef=useLatest(opts.initialInput),firstMessageRef=useLatest(opts.firstMessage),engineBinRef=useLatest(opts.engineBin),defaultColorsRef=useLatest(opts.defaultColors),alternateScreenStyleRewritesRef=useLatest(opts.alternateScreenStyleRewrites),bodyGeometryRef=useLatest(opts.bodyGeometry),registryRef=useLatest(opts.registry),onExitRef=useLatest(opts.onExit),onFreshPtyRef=useLatest(opts.onFreshPty),cwdRef=useLatest(opts.cwd),taskIdRef=useLatest(opts.taskId),geometryReady=opts.bodyGeometry!==null,cwd=opts.cwd,taskId=opts.taskId;import_react35.useEffect(()=>{if(!cwd||!taskId||!geometryReady){setPty(null),setSnapshot([]),snapshotWindowRef.current=null,wrappedRef.current=NO_WRAP,setCursor(null),setAcquireError(null);return}let geometry=bodyGeometryRef.current;if(!geometry)return;let handle;try{handle=registryRef.current.acquire(taskId,cwd,{...geometry,command:commandRef.current,initialInput:initialInputRef.current,firstMessage:firstMessageRef.current,engineBin:engineBinRef.current,defaultColors:defaultColorsRef.current,alternateScreenStyleRewrites:alternateScreenStyleRewritesRef.current,scheduleRefresh:scheduleRefreshRef.current,...machineRef.current?{machine:machineRef.current}:{}})}catch(err){let message=errorMessage(err);setAcquireError(message),setPty(null),setSnapshot([]),snapshotWindowRef.current=null,wrappedRef.current=NO_WRAP,setCursor(null);return}setAcquireError(null),setSnapshot([]),snapshotWindowRef.current=null,wrappedRef.current=NO_WRAP,setCursor(null),setExited(handle.killed),setPty(handle),onFreshPtyRef.current()},[cwd,taskId,geometryReady]),import_react35.useEffect(()=>{let killed=pty?pty.killed:!1;if(setExited(killed),!pty)return;if(killed){onExitRef.current?.({deadOnAttach:pty.deadOnAttach===!0});return}let unsubscribeExit=pty.onExit(()=>{setExited(!0),onExitRef.current?.({deadOnAttach:pty.deadOnAttach===!0})}),unsubscribe=pty.onData((snap,c2,window2,wrapped)=>{snapshotWindowRef.current=window2,wrappedRef.current=wrapped??NO_WRAP,setSnapshot(snap),setCursor(c2)});try{let initial=pty.capture();if(snapshotWindowRef.current=pty.captureWindow(),wrappedRef.current=pty.captureWrapped?.()??NO_WRAP,initial.length>0)setSnapshot(initial);setCursor(pty.captureCursor())}catch{}return()=>{unsubscribeExit(),unsubscribe()}},[pty]);let forceReacquire=import_react35.useCallback((nextCwd,nextTaskId,geometry,expected)=>{try{let opts2={...geometry,command:commandRef.current,initialInput:initialInputRef.current,firstMessage:firstMessageRef.current,engineBin:engineBinRef.current,defaultColors:defaultColorsRef.current,alternateScreenStyleRewrites:alternateScreenStyleRewritesRef.current,scheduleRefresh:scheduleRefreshRef.current},fresh=expected?registryRef.current.resetIfCurrent(nextTaskId,expected,nextCwd,opts2):registryRef.current.reset(nextTaskId,nextCwd,opts2);if(!fresh)return;setPty(fresh),setSnapshot([]),snapshotWindowRef.current=null,wrappedRef.current=NO_WRAP,setCursor(null),onFreshPtyRef.current()}catch(err){let message=errorMessage(err);setAcquireError(message),setPty(null),setSnapshot([]),snapshotWindowRef.current=null,wrappedRef.current=NO_WRAP,setCursor(null)}},[]),resetMountedRef=import_react35.useRef(!1);return import_react35.useEffect(()=>{if(opts.resetToken,!resetMountedRef.current){resetMountedRef.current=!0;return}let nextCwd=cwdRef.current,nextTaskId=taskIdRef.current,geometry=bodyGeometryRef.current;if(nextCwd&&nextTaskId&&geometry)forceReacquire(nextCwd,nextTaskId,geometry)},[opts.resetToken,forceReacquire]),{pty,snapshot,snapshotWindow:snapshotWindowRef.current,wrapped:wrappedRef.current,cursor,exited,acquireError,forceReacquire}}var import_react36=__toESM(require_react_production(),1);function useTerminalReset(args){let t3=useT(),resetTaskIdRef=useLatest(args.taskId),resetCwdRef=useLatest(args.cwd),mountedRef=import_react36.useRef(!0);return import_react36.useLayoutEffect(()=>{return mountedRef.current=!0,()=>{mountedRef.current=!1}},[]),()=>{if(!args.pty&&!args.acquireError)return;let{pty:ptyAtClick,cwd:cwdAtClick,taskId:taskIdAtClick,bodyGeometry:geometryAtClick}=args;if(!cwdAtClick||!taskIdAtClick||!geometryAtClick)return;if(!ptyAtClick){args.forceReacquire(cwdAtClick,taskIdAtClick,geometryAtClick);return}DialogConfirm.show(args.dialog,t3("terminal.reset.title"),t3("terminal.reset.body"),"cancel").then((ok)=>{if(ok!==!0||!mountedRef.current)return;if(resetTaskIdRef.current!==taskIdAtClick||resetCwdRef.current!==cwdAtClick)return;args.forceReacquire(cwdAtClick,taskIdAtClick,geometryAtClick,ptyAtClick)})}}var import_react38=__toESM(require_react_production(),1);import{spawn as spawn2}from"child_process";import{spawnSync}from"child_process";var CLIPBOARD_CANDIDATES={darwin:[["pbcopy"]],linux:[["wl-copy"],["xclip","-selection","clipboard","-in"],["xsel","--clipboard","--input"]],win32:[["clip"],["powershell","-NoProfile","-Command","Set-Clipboard"]]};function resolveClipboardCopyCommand(platform,hasCommand){for(let candidate of CLIPBOARD_CANDIDATES[platform]??[])if(hasCommand(candidate[0]))return candidate;return null}var clipboardBinaryOnPath=(binary)=>{try{let command=process.platform==="win32"?"where":"which";return spawnSync(command,[binary],{encoding:"utf8"}).status===0}catch{return!1}};var resolvedCommand;function clipboardCommand(){if(resolvedCommand===void 0)resolvedCommand=resolveClipboardCopyCommand(process.platform,clipboardBinaryOnPath);return resolvedCommand}function pipeToClipboardCommand(text,cmd){if(!cmd||cmd.length===0)return Promise.resolve(!1);return new Promise((resolve2)=>{try{let proc=spawn2(cmd[0],cmd.slice(1),{stdio:["pipe","ignore","ignore"]}),settled=!1,done=(ok)=>{if(settled)return;settled=!0,resolve2(ok)};proc.on("error",()=>done(!1)),proc.stdin.on("error",()=>done(!1)),proc.on("close",(code)=>done(code===0)),proc.stdin.end(text)}catch{resolve2(!1)}})}async function copyTextToSystemClipboard(text,osc52){let piped=await pipeToClipboardCommand(text,clipboardCommand()),escaped=!1;try{escaped=osc52(text)===!0}catch{}return piped||escaped}var AUTO_SCROLL_MS=50,AUTO_SCROLL_MAX_LINES=5;function useTerminalSelection(opts){let[selAnchor,setSelAnchor]=import_react38.useState(null),[selHead,setSelHead]=import_react38.useState(null),draggingRef=import_react38.useRef(!1),anchorRef=import_react38.useRef(null),renderer=useRenderer(),notifications=useOptionalNotifications(),t3=useT(),selection=import_react38.useMemo(()=>{if(!selAnchor||!selHead)return null;if(selAnchor.row===selHead.row&&selAnchor.col===selHead.col)return null;return{anchor:selAnchor,head:selHead}},[selAnchor,selHead]),resolvePointer=(evt)=>{let{bodyEl:body,bodyGeometry:geometry,bodyRows,visibleRangeStart,snapshot}=opts;if(!body||!geometry)return null;return pointerCell((evt.x??0)-body.screenX,(evt.y??0)-body.screenY,{cols:geometry.cols,rows:bodyRows},visibleRangeStart,snapshot.length)},cellFromEvent=(evt)=>resolvePointer(evt)?.cell??null,captureDrag=(el)=>{renderer?.setCapturedRenderable?.(el??void 0)},beginSelection=(cell)=>{draggingRef.current=!0,captureDrag(opts.bodyEl),appScrolledRef.current=!1,shadowRef.current=EMPTY_SHADOW,lastSnapshotRef.current=opts.snapshot,lastWindowRef.current=opts.snapshotWindow,anchorRef.current=cell,setSelAnchor(cell),setSelHead(cell)},dragPointRef=import_react38.useRef(null),appScrolledRef=import_react38.useRef(!1),shadowRef=import_react38.useRef(EMPTY_SHADOW),lastSnapshotRef=import_react38.useRef(opts.snapshot),lastWindowRef=import_react38.useRef(opts.snapshotWindow),autoScrollRef=import_react38.useRef(null),tickRef=import_react38.useRef(()=>{}),clearSelectionState=()=>{anchorRef.current=null,appScrolledRef.current=!1,shadowRef.current=EMPTY_SHADOW,setSelAnchor(null),setSelHead(null)},stopAutoScroll=()=>{if(!autoScrollRef.current)return;clearInterval(autoScrollRef.current),autoScrollRef.current=null},stopDragging=()=>{draggingRef.current=!1,captureDrag(null),dragPointRef.current=null,stopAutoScroll()},pullFor=(at2,anchor)=>{if(at2.edgePull===0||!anchor)return 0;if(at2.edgePull<0)return at2.cell.row<anchor.row?at2.edgePull:0;return at2.cell.row>anchor.row?at2.edgePull:0},dragTo=(evt)=>{if(!draggingRef.current)return;let at2=resolvePointer(evt);if(!at2)return;if(dragPointRef.current={x:evt.x??0,y:evt.y??0},setSelHead(at2.cell),pullFor(at2,anchorRef.current)===0)stopAutoScroll();else if(!autoScrollRef.current)autoScrollRef.current=setInterval(()=>tickRef.current(),AUTO_SCROLL_MS)};import_react38.useEffect(()=>{tickRef.current=()=>{let point=dragPointRef.current,at2=point&&draggingRef.current?resolvePointer(point):null,pull=at2?pullFor(at2,anchorRef.current):0;if(pull===0||!point){stopAutoScroll();return}let capped=Math.max(-AUTO_SCROLL_MAX_LINES,Math.min(AUTO_SCROLL_MAX_LINES,pull));if(opts.scrollBy(capped,point.x,point.y))appScrolledRef.current=!0}}),import_react38.useEffect(()=>{if(!draggingRef.current)return;let point=dragPointRef.current,at2=point?resolvePointer(point):null;if(at2)setSelHead(at2.cell)},[opts.visibleRangeStart]);let applyShift=(rolled)=>{shadowRef.current=rolled.shadow,anchorRef.current=rolled.anchor,setSelAnchor(rolled.anchor),setSelHead(rolled.head)};import_react38.useEffect(()=>{let prevSnapshot=lastSnapshotRef.current,prevWindow=lastWindowRef.current;if(lastSnapshotRef.current=opts.snapshot,lastWindowRef.current=opts.snapshotWindow,!anchorRef.current)return;let state={anchor:anchorRef.current,head:selHead,shadow:shadowRef.current},windowed=followWindowShift(state,prevWindow,opts.snapshotWindow,opts.snapshot.length,draggingRef.current);if(!windowed){clearSelectionState();return}if(windowed!==state){applyShift(windowed);return}if(!appScrolledRef.current||prevSnapshot===opts.snapshot)return;applyShift(followContentShift(state,prevSnapshot,opts.snapshot,draggingRef.current))},[opts.snapshot,opts.snapshotWindow]);let appOwnedMouseRef=import_react38.useRef(opts.appOwnsMouse);return import_react38.useEffect(()=>{let took=appTookMouse(appOwnedMouseRef.current,opts.appOwnsMouse);if(appOwnedMouseRef.current=opts.appOwnsMouse,!took)return;stopDragging(),clearSelectionState()},[opts.appOwnsMouse]),import_react38.useEffect(()=>()=>{if(autoScrollRef.current)clearInterval(autoScrollRef.current)},[]),{selection,cellFromEvent,beginSelection,dragTo,isDragging:()=>draggingRef.current,endDragging:stopDragging,clearSelection:clearSelectionState,copySelection:()=>{if(!selection)return;let text=extractShadowedSelection(opts.snapshot,shadowRef.current,selection,opts.wrapped);if(text.trim().length===0)return;copyTextToSystemClipboard(text,(payload)=>renderer?.copyToClipboardOSC52(payload)).then((copied)=>{if(!copied)notifications?.notify({kind:"error",taskId:"",tabId:"",title:t3("tasks.toast.copyFailed")})})},noteAppScroll:()=>{if(anchorRef.current)appScrolledRef.current=!0}}}var NO_ROWS=[];function Terminal(props){return $jsx(TerminalSession,{...props},props.taskId)}function TerminalSession(props){let{theme}=useTheme(),t3=useT(),registry=props.registry??getDefaultPtyRegistry(),[focusedLocal,setFocusedLocal]=import_react39.useState(!1),focused=props.focused??focusedLocal,[scrollState,setScrollState]=import_react39.useState(FOLLOW_VIEWPORT),{bodyEl,setBodyEl,bodyRows,bodyGeometry,bumpGeomTick,dims,geomTick}=useTerminalGeometry(),defaultColors=import_react39.useMemo(()=>{let[foregroundR,foregroundG,foregroundB]=theme.text.toInts(),[backgroundR,backgroundG,backgroundB]=theme.background.toInts(),hex=(r6,g3,b3)=>`#${[r6,g3,b3].map((component)=>component.toString(16).padStart(2,"0")).join("")}`;return{foreground:hex(foregroundR,foregroundG,foregroundB),background:hex(backgroundR,backgroundG,backgroundB)}},[theme]),alternateScreenStyleRewrites=import_react39.useMemo(()=>props.terminalPresentation?.alternateScreenStyleRewrites(defaultColors),[props.terminalPresentation,defaultColors]),{pty,snapshot,snapshotWindow,wrapped,cursor,exited,acquireError,forceReacquire}=useTerminalPty({cwd:props.cwd,taskId:props.taskId,machine:props.machine,command:props.command,initialInput:props.initialInput,firstMessage:props.firstMessage,engineBin:props.engineBin,defaultColors,alternateScreenStyleRewrites,resetToken:props.resetToken,onExit:props.onExit,registry,bodyGeometry,onFreshPty:()=>setScrollState(FOLLOW_VIEWPORT)}),scrollOffset=resolveViewportScrollOffset(snapshot.length,bodyRows,scrollState,snapshotWindow),scrollBy=(lines)=>{setScrollState((current2)=>moveViewportScroll(current2,snapshot.length,bodyRows,lines,snapshotWindow))},{scrollFromPointer,forwardMouse,forwardHover}=useTerminalPointerForward({pty,bodyEl,scrollBy}),visibleRange=import_react39.useMemo(()=>computeViewport(snapshot.length,bodyRows,scrollOffset),[snapshot.length,bodyRows,scrollOffset]),visibleRows=import_react39.useMemo(()=>{let rows=snapshot.slice(visibleRange.start,visibleRange.end);return rows.length===0?NO_ROWS:rows},[snapshot,visibleRange]),visibleCursor=import_react39.useMemo(()=>viewportCursor(cursor,scrollOffset,visibleRange),[cursor,scrollOffset,visibleRange]),[imeCursorRetention]=import_react39.useState(()=>new ImeCursorRetention),imeCursor=imeCursorRetention.update(pty,cursor),visibleImeCursor=import_react39.useMemo(()=>viewportCursor(imeCursor,scrollOffset,visibleRange),[imeCursor,scrollOffset,visibleRange]),selection=useTerminalSelection({bodyEl,bodyGeometry,bodyRows,visibleRangeStart:visibleRange.start,snapshot,snapshotWindow,wrapped,scrollBy:scrollFromPointer,appOwnsMouse:pty?.appOwnsMouse??!1}),terminalColors=import_react39.useMemo(()=>{let foreground=theme.text.toInts(),background=theme.background.toInts();return{foreground:[foreground[0],foreground[1],foreground[2]],background:[background[0],background[1],background[2]]}},[theme]),setSnapshotGrid=useTerminalPaint({visibleRows,firstRow:visibleRange.start,cols:bodyGeometry?.cols??80,selection:selection.selection,cursor:visibleCursor,focused,colors:terminalColors}),dialog=useDialog(),imeAnchorActive=(props.imeAnchorActive??!0)&&dialog.stack.length===0,unfocusedAttachmentTarget=props.imeAnchorActive===!0&&dialog.stack.length===0,requestReset=useTerminalReset({pty,acquireError,cwd:props.cwd,taskId:props.taskId,bodyGeometry,forceReacquire,dialog}),copySelectionIfAny=()=>{if(!selection.selection)return!1;return selection.copySelection(),selection.endDragging(),selection.clearSelection(),!0};useTerminalBindings({focused,unfocusedAttachmentTarget,inputModes:()=>pty?.inputModes()??{applicationCursorKeys:!1,applicationKeypad:!1},copySelection:copySelectionIfAny,write:(data)=>{if(data==="\x03"&&copySelectionIfAny())return;if(!pty||pty.killed)return;pty.write(data),props.onUserInput?.(data)},paste:(text)=>{if(!pty||pty.killed)return;pty.paste(text)},scroll:scrollBy,reset:props.engineExit?.onRetry??requestReset}),useTerminalHostCursor({pty,bodyEl,bodyGeometry,visibleImeCursor,imeAnchorActive,dims,geomTick});let[recovery,setRecovery]=import_react39.useState(null);return import_react39.useEffect(()=>{return setRecovery(null),pty?.onRecovery?.(setRecovery)},[pty]),$jsxs("box",{flexDirection:"column",flexGrow:1,overflow:"hidden",backgroundColor:theme.background,onMouseDown:(evt)=>{if(!focused)props.onRequestFocus?.();if(forwardMouse("down",evt))return;if(evt.button!==0)return;let cell=selection.cellFromEvent(evt);if(!cell)return;selection.beginSelection(cell)},onMouseDrag:(evt)=>{if(forwardMouse("drag",evt))return;selection.dragTo(evt)},onMouseMove:forwardHover,onMouseUp:(evt)=>{if(setFocusedLocal(!0),forwardMouse("up",evt))return;if(!selection.isDragging())return;if(selection.endDragging(),selection.selection)selection.copySelection();else selection.clearSelection()},onMouseScroll:(evt)=>{let scroll=evt.scroll;if(!scroll||scroll.direction!=="up"&&scroll.direction!=="down")return;let step=Math.max(1,scroll.delta||1),lines=scroll.direction==="up"?-step:step;if(scrollFromPointer(lines,evt.x,evt.y,evt.modifiers?.shift===!0))selection.noteAppScroll()},children:[recovery!==null&&(!exited||recovery==="restored")?$jsx("box",{flexShrink:0,paddingLeft:1,paddingRight:1,children:$jsx("text",{fg:recovery==="live"?theme.textMuted:theme.warning,wrapMode:"word",children:t3(`terminal.recovery.${recovery}`)})}):null,props.engineExit?$jsx(EngineExitBanner,{...props.engineExit,onRequestFocus:props.onRequestFocus}):props.usageLimit?$jsx(UsageLimitBanner,{...props.usageLimit,onRequestFocus:props.onRequestFocus}):exited?$jsx("box",{flexDirection:"row",flexShrink:0,paddingLeft:1,paddingRight:1,children:$jsx("text",{fg:theme.error,wrapMode:"none",onMouseUp:(event)=>{if(event.stopPropagation(),event.button===0)requestReset()},children:t3("terminal.exited")})}):null,scrollOffset>0?$jsxs("box",{position:"absolute",zIndex:10,left:0,right:0,bottom:0,flexDirection:"row",paddingLeft:1,paddingRight:1,gap:1,onMouseDown:(event)=>event.stopPropagation(),onMouseUp:(event)=>event.stopPropagation(),backgroundColor:theme.backgroundElement,children:[$jsx("text",{fg:theme.warning,wrapMode:"none",children:t3("terminal.scrolledBack",{lines:scrollOffset})}),$jsx("text",{fg:theme.info,wrapMode:"none",onMouseUp:(event)=>{if(event.stopPropagation(),event.button!==0)return;selection.clearSelection(),scrollBy(-snapshot.length),props.onRequestFocus?.()},children:t3("terminal.scrollFirst")}),$jsx("text",{fg:theme.info,wrapMode:"none",onMouseUp:(event)=>{if(event.stopPropagation(),event.button!==0)return;selection.clearSelection(),setScrollState(FOLLOW_VIEWPORT),props.onRequestFocus?.()},children:t3("terminal.scrollLatest")})]}):null,$jsx("box",{ref:bodyGeometry?setBodyEl:(r6)=>setBodyEl(r6),onSizeChange:bumpGeomTick,flexGrow:1,overflow:"hidden",children:pty?$jsx("box",{flexGrow:1,overflow:"hidden",ref:setSnapshotGrid}):$jsx("box",{paddingLeft:1,paddingTop:1,flexDirection:"column",gap:0,children:acquireError?$jsxs($Fragment,{children:[$jsx("text",{fg:theme.error,wrapMode:"word",children:isShellMissing(acquireError)?t3("terminal.unavailable.shellMissing"):t3("terminal.unavailable.spawnFailed")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:acquireError}),$jsx("text",{fg:theme.info,wrapMode:"none",onMouseUp:(event)=>{if(event.stopPropagation(),event.button===0)requestReset()},children:t3("terminal.unavailable.retry")})]}):$jsx("text",{fg:theme.textMuted,children:t3("terminal.noTask")})})})]})}var import_react40=__toESM(require_react_production(),1);function createLiveEngines(opts={}){let entries=opts.entries??(()=>getDefaultPtyRegistry().entries()),snapshot=opts.snapshot??psSnapshot,releaseAfterMisses=Math.max(1,opts.releaseAfterMisses??2),maxQuietSkipMs=opts.maxQuietSkipMs??1e4,now=opts.now??Date.now,vendors=new Map,misses=new Map,answered=new Set,auxPids=new Map,listeners=new Set,disposed=!1,lastWalk=null,emit=()=>{for(let l2 of listeners)l2()},outputStamps=()=>{let out=new Map;for(let[key,pty]of entries())out.set(key,pty.lastOutputAtMs?pty.lastOutputAtMs():null);return out},collectPids=()=>{let pids=new Map,live=new Set;for(let[key,pid]of auxPids)live.add(key),pids.set(key,pid);for(let[key,pty]of entries()){live.add(key);let pid=pty.shellPid??null;if(pid!==null)pids.set(key,pid)}return{pids,live}},walkIsCurrent=()=>{if(!lastWalk||misses.size>0||now()-lastWalk.at>=maxQuietSkipMs)return!1;let{pids}=collectPids();if(pids.size!==lastWalk.pids.size)return!1;for(let[key,pid]of pids)if(lastWalk.pids.get(key)!==pid)return!1;let registry=new Map(entries());for(let key of pids.keys()){let pty=registry.get(key);if(!pty?.lastOutputAtMs||pty.lastOutputAtMs()!==lastWalk.out.get(key))return!1}return!0},store={async probe(){if(disposed)return;let{pids,live}=collectPids(),changed=!1;for(let key of[...vendors.keys()]){if(live.has(key)&&pids.has(key))continue;vendors.delete(key),misses.delete(key),changed=!0}for(let key of[...answered]){if(live.has(key)&&pids.has(key))continue;answered.delete(key)}let out=outputStamps();if(pids.size>0){let rows;try{rows=parsePsSnapshot(await snapshot([...pids.values()]))}catch{if(lastWalk=null,changed)emit();return}if(disposed)return;lastWalk={at:now(),pids,out};for(let[key,pid]of pids){let vendor=foregroundEngineIn(rows,pid)?.vendor??null;answered.add(key);let prev=vendors.get(key)??null;if(vendor){if(misses.delete(key),prev===vendor)continue;vendors.set(key,vendor),changed=!0;continue}if(prev===null)continue;let count=(misses.get(key)??0)+1;if(count<releaseAfterMisses){misses.set(key,count);continue}misses.delete(key),vendors.delete(key),changed=!0}}if(changed)emit()},get(key){return vendors.get(key)??null},resolve(key){let vendor=vendors.get(key);if(vendor)return vendor;return answered.has(key)?null:void 0},setAuxPids(pids){auxPids=pids},subscribe(listener){return listeners.add(listener),()=>{listeners.delete(listener)}},dispose(){disposed=!0,listeners.clear(),vendors.clear(),misses.clear(),answered.clear(),clearInterval(handle)}},handle=setInterval(()=>{if(!walkIsCurrent())store.probe()},opts.intervalMs??2000);return handle.unref?.(),store}var defaultStore=null;function getDefaultLiveEngines(){if(!defaultStore)defaultStore=createLiveEngines();return defaultStore}function createTitleSubscriptions(lookup=getDefaultPtyRegistry().get.bind(getDefaultPtyRegistry())){let subs=new Map,listeners=new Set,emit=()=>{for(let l2 of listeners)l2()};return{reconcile(ptyKeys){let wanted=new Set(ptyKeys),changed=!1;for(let[key,sub]of subs){if((wanted.has(key)?lookup(key):null)===sub.pty)continue;sub.unsub(),subs.delete(key),changed=!0}for(let key of wanted){if(subs.has(key))continue;let pty=lookup(key);if(!pty)continue;let entry2={pty,unsub:()=>{},title:void 0};entry2.unsub=pty.onTitleChange((raw)=>{if(entry2.title===raw)return;entry2.title=raw,emit()}),subs.set(key,entry2),changed=!0}return changed},get(key){return subs.get(key)?.title},subscribe(listener){return listeners.add(listener),()=>{listeners.delete(listener)}},dispose(){for(let sub of subs.values())sub.unsub();subs.clear(),listeners.clear()}}}var TITLE_ATTACH_MS=2000;function useTitleSubscriptions(ptyKeys){let storeRef=import_react40.useRef(null);if(storeRef.current===null)storeRef.current=createTitleSubscriptions();let store=storeRef.current,[titles,setTitles]=import_react40.useState(new Map),ptyKeysRef=useLatest(ptyKeys),reconcile=import_react40.useCallback(()=>{let keys=ptyKeysRef.current;store.reconcile(keys.values());let liveEngines=getDefaultLiveEngines();setTitles((prev)=>{let next=new Map;for(let[id,key]of keys){let title=store.get(key);if(title===void 0)continue;next.set(id,stripEngineStatusPrefix(title,liveEngines.resolve(key)))}if(next.size===prev.size&&[...next].every(([id,v3])=>prev.get(id)===v3))return prev;return next})},[store]);return import_react40.useEffect(()=>{let timer=setInterval(reconcile,TITLE_ATTACH_MS);return()=>clearInterval(timer)},[reconcile]),import_react40.useEffect(()=>{reconcile()},[ptyKeys,reconcile]),import_react40.useEffect(()=>{let active=!0,scheduled=!1,unsub=store.subscribe(()=>{if(scheduled)return;scheduled=!0,queueMicrotask(()=>{if(scheduled=!1,active)reconcile()})});return()=>{active=!1,unsub()}},[store,reconcile]),import_react40.useEffect(()=>()=>store.dispose(),[store]),titles}var UNSPLIT=initialSplit(null);function releaseSplitLeaves(tabKey,tree){if(!tree)return;for(let leaf of leaves(tree.root))if(leaf.id!=="leaf-1")getDefaultPtyRegistry().release(splitLeafPtyKey(tabKey,leaf.id))}function TerminalSplit(props){let{theme,transparentBackground}=useTheme(),inactiveBorder=transparentBackground?theme.border:theme.borderSubtle,t3=useT(),kv=useKV(),state=props.splitTree??UNSPLIT,[activeLeaf,setActiveLeaf]=import_react41.useState(state.activeLeafId);import_react41.useEffect(()=>{setActiveLeaf((props.splitTree??UNSPLIT).activeLeafId)},[props.splitTree]);let fullState=()=>({...state,activeLeafId:activeLeaf}),update=(next)=>{if(next===state)return;props.onSplitChange(collapseSplit(next))},isSplit=isTabSplit(state),splitStyle=isSplit?normalizeSplitStyle(kv.get(SPLIT_STYLE_KEY)):"line",renderViaTree=collapseSplit(state)!==null;function removeAndRelease(id){let cur=fullState(),next=removeLeaf(cur,id);if(next===null)return!1;if(next!==cur)update(next),getDefaultPtyRegistry().release(splitLeafPtyKey(props.tabKey,id));return!0}function onLeafExit(id){if(removeAndRelease(id))return;releaseSplitLeaves(props.tabKey,state),props.onSplitChange(null),props.onExit?.()}let activeLeafSize=()=>getDefaultPtyRegistry().get(splitLeafPtyKey(props.tabKey,activeLeaf))?.size??null;useBindings(()=>({enabled:props.focused,bindings:bindByIds({"workspace.split.right":()=>update(splitActive(fullState(),"row",[defaultShell()],activeLeafSize())),"workspace.split.down":()=>update(splitActive(fullState(),"column",[defaultShell()],activeLeafSize())),"workspace.split.focus-next":()=>setActiveLeaf(cycleLeaf(fullState(),1).activeLeafId)})}));let dialog=useDialog();useBindings(()=>({enabled:props.focused&&isSplit,bindings:bindByIds({"workspace.split.close":prefixAction(()=>removeAndRelease(activeLeaf)),"workspace.split.rename":()=>{let id=activeLeaf;RenameTaskDialog.show(dialog,leafNames.get(id)??"",{dialogTitle:t3("terminal.split.renameTitle"),fieldLabel:t3("terminal.split.renameField"),submitLabel:t3("terminal.tab.renameSubmit"),allowEmpty:!0}).then((title)=>{if(title===void 0)return;update(renameLeaf(fullState(),id,title))})}})}));let leafFocused=(id)=>props.focused&&activeLeaf===id,leafPtyKeys=import_react41.useMemo(()=>{let map=new Map;for(let leaf of leaves(state.root))map.set(leaf.id,splitLeafPtyKey(props.tabKey,leaf.id));return map},[props.tabKey,state]),liveTitles=useTitleSubscriptions(leafPtyKeys),leafNames=splitLeafNames(leaves(state.root),props.command,props.engineTitle,liveTitles),focusedLeaf=props.focused?activeLeaf:null,renderLeaf=(leaf,divider,dividerLit=!1)=>{let focusThis=()=>setActiveLeaf(leaf.id),imeAnchorActive=activeLeaf===leaf.id,focused=leafFocused(leaf.id),name=leafNames.get(leaf.id)??"",chrome=paneChrome(splitStyle,divider),body=$jsxs($Fragment,{children:[$jsx(Terminal,{cwd:props.cwd,taskId:splitLeafPtyKey(props.tabKey,leaf.id),command:leaf.content??props.command,initialInput:leaf.content===null?props.initialInput:void 0,firstMessage:leaf.content===null?props.firstMessage:void 0,engineBin:leaf.content===null?props.engineBin:void 0,terminalPresentation:leaf.content===null?props.terminalPresentation:void 0,engineExit:leaf.content===null?props.engineExit:void 0,usageLimit:leaf.content===null?props.usageLimit:void 0,onUserInput:leaf.content===null?props.onUserInput:void 0,onExit:()=>onLeafExit(leaf.id),resetToken:leaf.id==="leaf-1"?props.resetToken:void 0,focused,imeAnchorActive,onRequestFocus:()=>{props.onRequestFocus?.(),focusThis()}}),isSplit&&!chrome.nameOnRule?$jsx("box",{position:"absolute",right:0,top:0,zIndex:10,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:focused?theme.focusAccent:theme.textMuted,attributes:focused?TextAttributes16.BOLD:TextAttributes16.DIM,wrapMode:"none",children:` ${name} `})}):null]});return $jsx("box",{flexGrow:1,flexShrink:1,flexBasis:0,...paneBoxProps(chrome,{edge:(splitStyle==="line"?dividerLit:focused)?theme.focusAccent:inactiveBorder,name,nameInk:focused?theme.focusAccent:theme.textMuted}),onMouseUp:focusThis,children:body},leaf.id)},renderNode=(node,groupKey,divider,dividerLit=!1)=>node.kind==="leaf"?renderLeaf(node,divider,dividerLit):$jsx("box",{flexDirection:node.orientation,flexGrow:1,flexShrink:1,flexBasis:0,...paneBoxProps(groupChrome(splitStyle,divider),{edge:dividerLit?theme.focusAccent:inactiveBorder}),children:node.children.map((child,i2)=>{let prev=node.children[i2-1],lit=prev!==void 0&&focusedLeaf!==null&&(leafOnEdge(prev,node.orientation,!0,focusedLeaf)||leafOnEdge(child,node.orientation,!1,focusedLeaf));return renderNode(child,child.kind==="leaf"?child.id:`${groupKey}.${i2}`,i2>0?node.orientation==="row"?"left":"top":void 0,lit)})},groupKey);if(renderViaTree)return $jsx("box",{flexDirection:"column",flexGrow:1,overflow:"hidden",children:renderNode(state.root,"root")});return $jsx(Terminal,{cwd:props.cwd,taskId:props.tabKey,command:props.command,initialInput:props.initialInput,firstMessage:props.firstMessage,engineBin:props.engineBin,terminalPresentation:props.terminalPresentation,engineExit:props.engineExit,usageLimit:props.usageLimit,onUserInput:props.onUserInput,onExit:props.onExit,resetToken:props.resetToken,focused:props.focused,imeAnchorActive:!0,onRequestFocus:props.onRequestFocus})}function releaseClosedTabPtys(taskId,closing,closedId){let key=closing?tabPtyKeyFor(taskId,closing):tabPtyKey(taskId,closedId);if(releaseSplitLeaves(key,closing?.splitTree??null),closing?.kind==="engine"&&closing.ptyTask&&closing.ptyTask.tabId===void 0)return;noteClosedPtyKey(key);let registry=getDefaultPtyRegistry(),local=registry.get(key);if(registry.release(key),!local)killHostedSession(key)}function killHostedSession(key){let client=peekSharedPtyClient();if(!client){logClientError("pty",Error(`pty.kill skipped for ${key}: no shared pty client in this process`));return}client.then((c2)=>c2.request("pty.kill",{key})).catch((err)=>{logClientError("pty",Error(`pty.kill failed for ${key}: ${err instanceof Error?err.message:String(err)}`))})}function closeTaskTab(kv,taskId,tabId){let state=knownTabsState(kv,taskId);if(!state||!state.tabs.some((tab)=>tab.id===tabId))return!1;if(requestTabClose(taskId,tabId),!takeUnclaimedTabClose())return!0;let closing=state.tabs.find((tab)=>tab.id===tabId),{state:next,closedId}=closeTab(state,tabId,{allowEmpty:!0});if(!closedId)return!1;return setTaskTabs2(taskId,next),reportTabsDelta(taskId,state.tabs,next.tabs),releaseClosedTabPtys(taskId,closing,closedId),!0}function closeOtherTaskTabs(kv,taskId,keepId){let state=knownTabsState(kv,taskId);if(!state||!state.tabs.some((tab)=>tab.id===keepId))return 0;let closed=0;for(let tab of state.tabs)if(tab.id!==keepId&&closeTaskTab(kv,taskId,tab.id))closed++;return closed}function closeAllTaskTabs(kv,taskId){let state=knownTabsState(kv,taskId);if(!state)return 0;let closed=0;for(let tab of state.tabs)if(closeTaskTab(kv,taskId,tab.id))closed++;return closed}function renameTaskTab(kv,taskId,tabId,title){let state=knownTabsState(kv,taskId);if(!state||!state.tabs.some((tab)=>tab.id===tabId))return!1;if(requestTabRename(taskId,tabId,title),!takeUnclaimedTabRename())return!0;let next=setTabTitle(state,tabId,title);if(next===state)return!0;return setTaskTabs2(taskId,next),!0}var STALE_NOTICE_MS=1e4,NO_NOTICES=createStateCell(null),NO_TAB_OPENS=createStateCell(null),NO_TAB_CLOSES=createStateCell(null),NO_TAB_RENAMES=createStateCell(null),NO_TAB_ADDS=createStateCell(null),NO_PROMPTS=createStateCell(null);function useDaemonTabOpens(orch){let request=useAccessor(orch?orch.tabOpenStore():NO_TAB_OPENS),seenAt=import_react42.useRef(null);import_react42.useEffect(()=>{if(!request||request.at===seenAt.current)return;if(seenAt.current=request.at,Date.now()-request.at>STALE_NOTICE_MS)return;requestTabOpen(request.taskId,request.argv,request.title,request.placement,request.direction,request.tabId)},[request])}function useDaemonTabCloses(orch){let kv=useKV(),request=useAccessor(orch?orch.tabCloseStore():NO_TAB_CLOSES),seenAt=import_react42.useRef(null);import_react42.useEffect(()=>{if(!request||request.at===seenAt.current)return;if(seenAt.current=request.at,Date.now()-request.at>STALE_NOTICE_MS)return;if("requestId"in request){let closed=closeTaskTab(kv,request.taskId,request.tabId);orch?.replyTerminalTabClose(request.requestId,closed);return}requestPaneClose(request.taskId,request.title,request.tabId)},[request,kv,orch])}function useDaemonTabRenames(orch){let kv=useKV(),request=useAccessor(orch?orch.tabRenameStore():NO_TAB_RENAMES),seenAt=import_react42.useRef(null);import_react42.useEffect(()=>{if(!request||request.at===seenAt.current)return;if(seenAt.current=request.at,Date.now()-request.at>STALE_NOTICE_MS)return;renameTaskTab(kv,request.taskId,request.tabId,request.title)},[request,kv])}function useDaemonTabAdds(orch){let kv=useKV(),request=useAccessor(orch?orch.tabAddStore():NO_TAB_ADDS),seenAt=import_react42.useRef(null);import_react42.useEffect(()=>{if(!request||request.at===seenAt.current)return;if(seenAt.current=request.at,Date.now()-request.at>STALE_NOTICE_MS)return;addTaskTab(kv,request.taskId,request.tab)},[request,kv])}function useDaemonPrompts(orch,dialog){let request=useAccessor(orch?orch.uiPromptStore():NO_PROMPTS),seenAt=import_react42.useRef(null),dialogRef=import_react42.useRef(dialog);dialogRef.current=dialog,import_react42.useEffect(()=>{if(!orch||!request||request.at===seenAt.current)return;if(seenAt.current=request.at,Date.now()-request.at>STALE_NOTICE_MS)return;RenameTaskDialog.show(dialogRef.current,request.initial??"",{dialogTitle:request.title,fieldLabel:t("common.prompt.fieldLabel"),submitLabel:t("common.prompt.submitLabel"),placeholder:request.placeholder??"",allowEmpty:!0}).then((value)=>orch.replyPrompt(request.promptId,value))},[request,orch])}function useDaemonNotices(orch,notify,dialog){useDaemonTabOpens(orch),useDaemonTabCloses(orch),useDaemonTabRenames(orch),useDaemonTabAdds(orch),useDaemonPrompts(orch,dialog);let notice=useAccessor(orch?orch.noticeStore():NO_NOTICES),seenAt=import_react42.useRef(null),notifyRef=import_react42.useRef(notify);notifyRef.current=notify,import_react42.useEffect(()=>{if(!notice||notice.at===seenAt.current)return;if(seenAt.current=notice.at,Date.now()-notice.at>STALE_NOTICE_MS)return;let kind=notice.kind==="needs_input"||notice.kind==="error"?notice.kind:"done";notifyRef.current({kind,taskId:notice.taskId??"",tabId:"",title:notice.title,...notice.body?{body:notice.body}:{}})},[notice])}function useTaskColor(taskId){let{theme}=useTheme(),kv=useOptionalKV();if(!taskId||normalizeTaskColors(kv?.get(TASK_COLORS_KEY,DEFAULT_TASK_COLORS))==="off")return;return taskColor(taskId,theme)}var import_react47=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes18}from"@opentui/core";var KEY_HINTS_ENABLED_KEY="hints.keyboard.enabled",PANE_HINT_USED_KEYS={sidebar:"hints.sidebar.used",files:"hints.files.used"};function keyHintsEnabled(raw){return raw!==!1}function keyHintsToggleOn(kv){return keyHintsEnabled(kv.get(KEY_HINTS_ENABLED_KEY,!0))}function toggleKeyHints(kv){let next=!keyHintsToggleOn(kv);if(kv.set(KEY_HINTS_ENABLED_KEY,next),next)for(let key of Object.values(PANE_HINT_USED_KEYS))kv.set(key,!1)}function paneHintVisible(enabledRaw,usedRaw){return keyHintsEnabled(enabledRaw)&&usedRaw!==!0}function statusHintTokens(reach,prefixKey){let tokens=[];if(prefixKey!==null&&reach.prefix.size>0)tokens.push({chord:prefixKey,msg:"commands"});else if(reach.inputPassthrough){let cap=reach.direct.has("focus.sidebar")?legendCap("focus.sidebar"):null;if(cap)tokens.push({chord:cap,msg:"sidebar"})}if(reach.direct.has("help.open")){let cap=legendCap("help.open");if(cap)tokens.push({chord:cap,msg:"help"})}return tokens}var PANE_HINT_ROWS={sidebar:[{id:"sidebar.nav",msg:"move"},{id:"sidebar.select",msg:"open"}],files:[{id:"files.nav",msg:"move"},{id:"files.hierarchy",msg:"collapse"},{id:"files.open",msg:"open",always:!0},{id:"files.diff",msg:"diff",always:!0}]};function paneHintTokens(pane,mode){return PANE_HINT_ROWS[pane].flatMap((row)=>{if(mode==="always"&&row.always!==!0)return[];let cap=legendCap(row.id);return cap?[{cap,msg:row.msg}]:[]})}function wizardKeyLines(prefixKey){let lines=[],nav=legendCap("sidebar.nav"),open=legendCap("sidebar.select");if(nav&&open)lines.push({msg:"keysBare",params:{nav:formatChord(nav),open:formatChord(open)}});let newTab=legendCap("chat.tab.new"),focusNext=legendCap("focus.next");if(newTab&&focusNext)lines.push({msg:"keysOnePress",params:{newTab:formatChord(newTab),focusNext:formatChord(focusNext)}});if(prefixKey!==null)lines.push({msg:"keysPrefix",params:{prefix:formatChord(prefixKey)}});let help=legendCap("help.open");if(help)lines.push({msg:"keysHelp",params:{help:formatChord(help)}});return lines}var import_react46=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes17}from"@opentui/core";function DoctorSuggestions({fixes}){let{theme}=useTheme(),t3=useT();return $jsxs("box",{gap:1,children:[fixes.map((fix)=>$jsxs("box",{children:[$jsx("text",{fg:theme.warning,wrapMode:"word",children:fix.label}),$jsx("text",{fg:theme.primary,wrapMode:"word",children:fix.kind==="manual"?fix.action:fix.command.join(" ")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:fix.why})]},fix.id)),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("common.failureHint",{command:"rove doctor"})})]})}var import_react45=__toESM(require_react_production(),1);var import_react44=__toESM(require_react_production(),1);function quickTaskBindings(field,h2){return[{key:"tab",cmd:()=>h2.cycleField(1)},{key:"shift+tab",cmd:()=>h2.cycleField(-1)},{key:"ctrl+e",cmd:()=>h2.stepEngine(1)},{key:"ctrl+v",cmd:()=>h2.pasteAttachment()},{key:"ctrl+x",cmd:()=>h2.removeLastAttachment()},...field==="attempts"?[{key:"left",cmd:()=>h2.stepAttempts(-1)},{key:"right",cmd:()=>h2.stepAttempts(1)},{key:"h",cmd:()=>h2.stepAttempts(-1)},{key:"l",cmd:()=>h2.stepAttempts(1)},{key:"return",cmd:()=>h2.commit()}]:[],...field==="engine"?[{key:"left",cmd:()=>h2.stepEngine(-1)},{key:"right",cmd:()=>h2.stepEngine(1)},{key:"h",cmd:()=>h2.stepEngine(-1)},{key:"l",cmd:()=>h2.stepEngine(1)},{key:"return",cmd:()=>h2.commit()}]:[]]}var ATTEMPT_CHOICES=["1","2","3","4","5"],FIELDS=["prompt","attempts","engine","branch"];function QuickTaskComposerView(props){let dialog=useDialog(),{theme}=useTheme(),t3=useT(),padX=useDialogPaddingX(),[field,setField]=import_react44.useState("prompt"),[prompt,setPrompt]=import_react44.useState(""),[attempts,setAttempts]=import_react44.useState(1),[vendor,setVendor]=import_react44.useState(props.defaultVendor),[baseRef,setBaseRef]=import_react44.useState(props.defaultBaseRef),[attachments,setAttachments]=import_react44.useState([]);usePaste((event)=>{let paths=asAttachmentPaths(new TextDecoder().decode(event.bytes));if(!paths)return;event.preventDefault(),setAttachments((prev)=>[...prev,...paths.filter((p3)=>!prev.includes(p3))])});function pasteAttachment(){captureClipboardAttachment().then((path)=>{if(path)setAttachments((prev)=>prev.includes(path)?prev:[...prev,path])})}function cycleField(dir){setField((f2)=>{let i2=FIELDS.indexOf(f2);return FIELDS[(i2+dir+FIELDS.length)%FIELDS.length]??"prompt"})}function stepAttempts(dir){setAttempts((n2)=>Math.min(ATTEMPT_CHOICES.length,Math.max(1,n2+dir)))}function stepEngine(dir){let list=props.engines;if(list.length===0)return;if(dir>0){setVendor((v3)=>nextVendorWithin(list,v3));return}setVendor((v3)=>{let i2=Math.max(0,list.indexOf(v3));return list[(i2-1+list.length)%list.length]??v3})}function commit(){if(isBlankText(prompt)){setField("prompt");return}props.onSubmit({prompt:prompt.trim(),vendor,baseRef:baseRef.trim()||props.defaultBaseRef,attachments,attempts}),dialog.clear()}return useBindings(()=>({enabled:!0,bindings:quickTaskBindings(field,{cycleField,stepAttempts,stepEngine,commit,pasteAttachment,removeLastAttachment:()=>setAttachments((prev)=>prev.slice(0,-1))})})),$jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:0,children:[$jsx(DialogHeader2,{title:t3("quickTask.title",{repoLabel:props.repoLabel}),onClose:()=>props.onCancel()}),props.intent?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:props.intent}):null,$jsxs("box",{gap:1,paddingTop:1,children:[$jsx(DialogSection2,{label:t3("quickTask.promptLabel"),focused:field==="prompt",onPress:()=>setField("prompt"),children:$jsx(DialogField2,{focused:field==="prompt",children:$jsx("input",{value:prompt,placeholder:t3("quickTask.promptPlaceholder"),focused:field==="prompt",onInput:(v3)=>setPrompt(stripNewlines2(v3)),onSubmit:()=>commit(),onMouseUp:()=>setField("prompt")})})}),attachments.length>0?$jsx("box",{flexDirection:"row",gap:2,flexWrap:"wrap",children:attachments.map((path,i2)=>$jsx("text",{fg:theme.primary,wrapMode:"none",flexShrink:0,onMouseUp:()=>setAttachments((prev)=>prev.filter((p3)=>p3!==path)),children:attachmentLabel(path,i2)},path))}):null,$jsx(DialogSection2,{label:t3("quickTask.attemptsLabel"),focused:field==="attempts",hint:"\u2190/\u2192",onPress:()=>setField("attempts"),children:$jsx(ChipRow2,{choices:ATTEMPT_CHOICES,selected:String(attempts),onPick:(v3)=>{setAttempts(Number(v3)),setField("attempts")}})}),$jsx(DialogSection2,{label:t3("quickTask.engineLabel"),focused:field==="engine",hint:"\u2190/\u2192",onPress:()=>setField("engine"),children:$jsx(ChipRow2,{choices:props.engines,selected:vendor,display:(v3)=>props.engineLabel(v3),onPick:(v3)=>{setVendor(v3),setField("engine")}})}),$jsx(DialogSection2,{label:t3("quickTask.branchLabel"),focused:field==="branch",onPress:()=>setField("branch"),children:$jsx(DialogField2,{focused:field==="branch",children:$jsx("input",{value:baseRef,placeholder:props.defaultBaseRef,focused:field==="branch",onInput:(v3)=>setBaseRef(stripNewlines2(v3)),onSubmit:()=>commit(),onMouseUp:()=>setField("branch")})})}),$jsx(DialogFooter2,{children:t3("quickTask.legend")})]})]})}function show4(dialog,opts){return showDialog(dialog,(resolve2)=>$jsx(QuickTaskComposerView,{...opts,onSubmit:(r6)=>resolve2(r6),onCancel:()=>resolve2(void 0)}),{size:"medium"})}var QuickTaskComposer={show:show4};function firstTaskRepo(cwd){try{return validateRepoPath(cwd)===null?resolveMainRepoRoot(cwd):null}catch{return null}}function FirstTaskStart(props){let{theme}=useTheme(),t3=useT(),dialog=useDialog(),[repo]=import_react45.useState(()=>firstTaskRepo(process.cwd())),[opening,setOpening]=import_react45.useState(!1);if(repo===null||!props.env.git||props.env.engines.length===0)return null;let start=async()=>{if(opening)return;setOpening(!0);try{let engines=props.env.engines,result=await QuickTaskComposer.show(dialog,{...quickForkComposerOptions(repo,engines,quickForkDefaultVendor2(repo,engines),process.cwd()),intent:t3("onboarding.quickIntent",{key:formatChord(legendCap("task.new")??"n")})});if(result)props.onCreate(repo,result)}finally{setOpening(!1)}};return $jsxs("box",{paddingTop:1,flexDirection:"column",children:[$jsx("box",{onMouseUp:()=>void start(),children:$jsx("text",{fg:theme.primary,children:t3("onboarding.quickStart")})}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("onboarding.quickIntent",{key:formatChord(legendCap("task.new")??"n")})})]})}async function probeWelcomeEnv(){let{usable,signedOut}=await probeableEngineIds().then(detectEngineStatuses).then(summarizeEngines).catch(()=>({usable:[],signedOut:[]})),git=globalThis.Bun?.which?globalThis.Bun.which("git")!==null:!0;return{engines:usable,signedOut,git}}function stepLines(){let lines=[],newTask=legendCap("task.new");if(newTask)lines.push({cap:formatChord(newTask),msg:"stepNew"});let help=legendCap("help.open");if(help)lines.push({cap:formatChord(help),msg:"stepHelp"});let prefix=currentPrefixConfiguration().key;if(prefix!==null)lines.push({cap:formatChord(prefix),msg:"stepPrefix"});return lines}function WelcomePane(props){let{theme}=useTheme(),t3=useT(),[env,setEnv]=import_react46.useState(null),probe=props.probe??probeWelcomeEnv;import_react46.useEffect(()=>{let alive=!0;return probe().then((result)=>{if(alive)setEnv(result)}),()=>{alive=!1}},[]);let steps=stepLines(),capWidth=Math.max(...steps.map((s2)=>displayWidth(s2.cap)),0),broken=env!==null&&(env.engines.length===0||!env.git),engineLine=env===null?null:env.engines.length>0?{key:"enginesFound",fg:theme.textMuted,list:env.engines.map(engineDisplayName).join(" \xB7 ")}:env.signedOut.length>0?{key:"enginesSignedOut",fg:theme.warning,list:env.signedOut.map(engineDisplayName).join(" \xB7 ")}:{key:"enginesMissing",fg:theme.warning,list:""};return $jsx("scrollbox",{flexGrow:1,contentOptions:{alignItems:"center"},children:$jsxs("box",{flexDirection:"column",flexShrink:0,maxWidth:72,paddingLeft:2,paddingRight:2,children:[$jsx("text",{fg:theme.primary,attributes:TextAttributes17.BOLD,wrapMode:"none",children:t3("workspace.welcome.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("workspace.welcome.tagline")}),$jsx("box",{flexDirection:"column",paddingTop:1,children:steps.map((step)=>$jsxs("box",{flexDirection:"row",gap:2,children:[$jsx("text",{fg:theme.primary,wrapMode:"none",children:padEndCells(step.cap,capWidth)}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3(`workspace.welcome.${step.msg}`)})]},step.msg))}),$jsx("box",{paddingTop:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("workspace.welcome.worktreeExplain")})}),env!==null&&engineLine!==null?$jsxs("box",{flexDirection:"column",paddingTop:1,children:[$jsx("text",{fg:engineLine.fg,wrapMode:"word",children:t3(`workspace.welcome.${engineLine.key}`,{list:engineLine.list})}),env.git?null:$jsx("text",{fg:theme.warning,wrapMode:"word",children:t3("workspace.welcome.gitMissing")}),broken?$jsx(DoctorSuggestions,{fixes:[...!env.git?[humanOnlyFix("git")]:[],...env.engines.length===0?[noEngineFix(env.signedOut)]:[]]}):null]}):null,env&&props.onQuickTask?$jsx(FirstTaskStart,{env,onCreate:props.onQuickTask}):null,$jsx("box",{paddingTop:1,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes17.DIM,wrapMode:"none",children:t3("workspace.welcome.docsHint")})})]})})}function EngineWelcomePage(props){let{theme}=useTheme(),t3=useT(),env=props.env;return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,children:t3("onboarding.engineTitle")}),env===null?$jsx("text",{fg:theme.textMuted,children:t3("onboarding.engineChecking")}):$jsxs($Fragment,{children:[$jsx("text",{fg:env.engines.length?theme.success:theme.warning,children:t3(env.engines.length?"onboarding.engineReady":"onboarding.engineMissing")}),env.engines.map((id)=>$jsx("text",{fg:theme.textMuted,children:t3("onboarding.engineUsable",{engine:engineDisplayName(id)})},id)),env.signedOut.map((id)=>$jsx("text",{fg:theme.warning,children:t3("onboarding.engineSignedOut",{engine:engineDisplayName(id)})},id)),env.engines.length===0?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("onboarding.engineSetup")}):null,!env.git?$jsx("text",{fg:theme.warning,children:t3("workspace.welcome.gitMissing")}):null,$jsx("box",{onMouseUp:props.onContinue,children:$jsx("text",{fg:theme.primary,children:t3("onboarding.engineContinue")})})]})]})}var PAD_X=2;function WelcomeDialogView(props){let{theme}=useTheme(),t3=useT(),[skillLine,setSkillLine]=import_react47.useState(null),steps=props.shell===null?["skill"]:["completions","skill"],[stepIndex,setStepIndex]=import_react47.useState(0),[yes,setYes]=import_react47.useState(!0),[answers,setAnswers]=import_react47.useState({}),[page,setPage]=import_react47.useState("engine"),[env,setEnv]=import_react47.useState(null),probe=props.probe??probeWelcomeEnv;import_react47.useEffect(()=>{let alive=!0;return probe().then((value)=>{if(alive)setEnv(value)}),()=>{alive=!1}},[probe]);let step=steps[stepIndex],answeredSteps=steps.slice(0,page==="questions"?stepIndex:steps.length);function finish(finalAnswers){props.onDone({completions:finalAnswers.completions??!1})}function confirm(choice=yes){if(page==="engine"){if(env!==null)setPage("questions");return}if(page==="keys"){finish(answers);return}let next={...answers,[step]:choice};if(setAnswers(next),step==="skill"&&choice)setSkillLine((props.installSkill??(()=>installSkillLine(t3)))());if(props.onAnswers?.({completions:next.completions??!1}),stepIndex+1>=steps.length){setPage("keys");return}setStepIndex(stepIndex+1),setYes(!0)}useBindings(()=>({bindings:[{key:"up",cmd:()=>setYes(!0)},{key:"k",cmd:()=>setYes(!0)},{key:"down",cmd:()=>setYes(!1)},{key:"j",cmd:()=>setYes(!1)},{key:"return",cmd:()=>confirm()}]}));function labelFor(s2){return s2==="completions"?t3("onboarding.completionsLabel",{shell:props.shell??""}):t3("onboarding.skillLabel")}let explain=step==="completions"?t3("onboarding.completionsExplain"):t3("onboarding.skillExplain");return $jsxs("box",{paddingLeft:PAD_X,paddingRight:PAD_X,gap:1,flexShrink:1,children:[$jsxs("box",{flexDirection:"column",gap:0,flexShrink:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes18.BOLD,wrapMode:"none",children:t3("onboarding.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("onboarding.subtitle")})]}),$jsxs("box",{flexDirection:"column",flexShrink:1,children:[page!=="engine"&&answeredSteps.length>0?$jsx("box",{flexDirection:"column",paddingBottom:1,children:answeredSteps.map((answered)=>$jsxs("box",{flexDirection:"row",gap:1,children:[$jsx("text",{fg:answers[answered]?theme.success:theme.textMuted,wrapMode:"none",children:answers[answered]?"\u2713":"\u2013"}),$jsx("text",{fg:theme.text,wrapMode:"none",children:labelFor(answered)}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:`\xB7 ${!answers[answered]?t3("onboarding.skipped"):answered==="skill"?skillLine:t3("onboarding.queued")}`})]},answered))}):null,page==="engine"?$jsx(EngineWelcomePage,{env,onContinue:()=>confirm()}):page==="keys"?$jsxs("box",{flexDirection:"column",onMouseUp:()=>confirm(),children:[$jsx("text",{fg:theme.text,attributes:TextAttributes18.BOLD,wrapMode:"word",children:t3("onboarding.keysTitle")}),wizardKeyLines(currentPrefixConfiguration().key).map((line)=>$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3(`onboarding.${line.msg}`,line.params)},line.msg)),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("onboarding.keysNext")})]}):$jsxs($Fragment,{children:[$jsxs("box",{flexDirection:"row",children:[$jsx("text",{fg:theme.text,attributes:TextAttributes18.BOLD,wrapMode:"none",flexGrow:1,children:labelFor(step)}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("onboarding.stepCounter",{n:String(stepIndex+1),total:String(steps.length)})})]}),$jsx("box",{paddingBottom:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:explain})}),[!0,!1].map((option)=>{let active=yes===option;return $jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,paddingRight:1,backgroundColor:active?theme.primary:void 0,onMouseUp:()=>confirm(option),children:[$jsx("text",{fg:active?theme.selectedListItemText:theme.text,wrapMode:"none",children:option?t3("onboarding.optionYes"):t3("onboarding.optionNo")}),option&&step==="skill"?$jsx("text",{fg:active?theme.selectedListItemText:theme.textMuted,wrapMode:"none",children:t3("onboarding.recommended")}):null]},String(option))})]})]}),$jsx("box",{paddingBottom:1,flexShrink:0,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes18.DIM,wrapMode:"none",children:t3(page==="engine"?"onboarding.engineLegend":page==="keys"?"onboarding.keysLegend":"onboarding.legend")})})]})}function installSkillLine(t3){let engines=skillTargets().map((target)=>target.displayName);if(engines.length===0)return t3("onboarding.skillNoEngines");let error=installSkillErrors();return error?t3("onboarding.skillFailed",{reason:error}):t3("onboarding.skillInstalled",{engines:engines.join(", ")})}function show5(dialog,opts){let settled=!1,confirmed={completions:!1},once=(choices)=>{if(settled)return;settled=!0,opts.onDone(choices)};dialog.replace(()=>$jsx(WelcomeDialogView,{shell:opts.shell,onAnswers:(choices)=>{confirmed=choices},onDone:(choices)=>{once(choices),dialog.clear()}}),()=>once(confirmed)),dialog.setSize("medium")}var WelcomeDialog={show:show5};function useWelcomeDialog(request,onClosed){let dialog=useDialog(),opened=import_react47.useRef(!1),shell=request?.shell??null;import_react47.useEffect(()=>{if(request===null||opened.current)return;opened.current=!0,WelcomeDialog.show(dialog,{shell,onDone:(choices)=>{onClosed(),trackWelcomeWrite(import("./chunk-w2tcb3rn.js").then((m3)=>m3.recordWelcomeChoices(choices,shell)))}})},[request,dialog,onClosed,shell])}var import_react49=__toESM(require_react_production(),1);var SIDEBAR_WIDTH=24;function sidebarWidthFor(terminalWidth){return Math.max(SIDEBAR_WIDTH,Math.min(40,Math.floor(terminalWidth/6)))}var MIN_WORKSPACE_WIDTH=40;function resolveSidebarWidth(terminalWidth,override){if(override==null)return sidebarWidthFor(terminalWidth);let max=Math.max(SIDEBAR_WIDTH,terminalWidth-MIN_WORKSPACE_WIDTH);return Math.max(SIDEBAR_WIDTH,Math.min(max,Math.round(override)))}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 rowTokenTone(tone){switch(tone){case"info":return"primary";case"success":return"success";case"warning":return"warning";case"error":return"error";default:return"textMuted"}}function toneColor2(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 seq2=evt.sequence;if(!seq2||seq2.length!==1)return null;let code=seq2.charCodeAt(0);if(code<32||code===127)return null;return query+seq2}var listeners=new Set,tickCount=0,timer=null;function tick(){tickCount++;for(let listener of listeners)try{listener()}catch{}}function sidebarPollClockSnapshot(){return tickCount}function subscribeSidebarPollClock(listener){if(listeners.add(listener),timer===null)timer=setInterval(tick,MAIN_BRANCH_POLL_MS),timer.unref?.();return()=>{if(listeners.delete(listener),listeners.size===0&&timer!==null)clearInterval(timer),timer=null}}function rowStatusTone(status){switch(status?.kind){case"busy":case"running":case"unseen":return"accent";case"needs-input":return"warning";case"attention":return status.reason==="rate_limited"?"warning":"error";default:return"muted"}}function rowStatusGlyph(status,glyphs,frame=0){let tone=rowStatusTone(status);switch(status?.kind){case"busy":case"running":return{glyph:glyphs.spinner[frame%Math.max(1,glyphs.spinner.length)]??glyphs.idle,tone,spinning:!0};case"needs-input":return{glyph:glyphs.needsInput,tone,spinning:!1};case"attention":return{glyph:glyphs.attention,tone,spinning:!1};case"unseen":return{glyph:glyphs.unseen,tone,spinning:!1};default:return{glyph:glyphs.idle,tone,spinning:!1}}}var TONES={accent:"primary",warning:"warning",error:"error",muted:"textMuted"};function sidebarTone(tone){return TONES[tone]}var SPINNER_FRAME_MS=80,SPINNER_TICK_CYCLE=600,DONE_PULSE_MS=600;function noTrackingSubtitle(){return t("tasks.subtitle.noTracking")}function materializingSubtitle(){return t("tasks.subtitle.materializing")}function deletionSubtitle(failed){return failed?t("tasks.subtitle.deleteFailed"):t("tasks.subtitle.deleting")}function isCustomEngineTask(task){if(task.kind==="main")return!1;return task.vendor!==void 0&&!isBuiltinVendor(task.vendor)}function rowIsLoading(status){return rowStatusGlyph(status,DEFAULT_GLYPHS).spinning}function buildSidebarRowView(opts){let{task,status}=opts,isMain=task.kind==="main",branch=isMain?opts.mainBranch??"":task.branch,glyphs=opts.glyphs??DEFAULT_GLYPHS,mark=rowStatusGlyph(status,glyphs),untrackedCustomEngine=isCustomEngineTask(task)&&status?.state===void 0&&!mark.spinning,materializing=status?.kind==="busy"&&status.reason==="job",deleting=task.deletion?.phase==="queued"||task.deletion?.phase==="running",deleteFailed=task.deletion?.phase==="error",loading=mark.spinning,spinnerFrames=glyphs.spinner,stateGlyph=loading?breathGlyph(spinnerFrames,opts.spinnerFrame):mark.glyph,fallbackSubtitle=untrackedCustomEngine?noTrackingSubtitle():"\u2014",subagents=loading?opts.lifecycle?.subagents??0:0,branchWithMarks=subagents>0&&branch.length>0?`${glyphs.subagent}${subagents} ${branch}`:branch,subtitleText=deleting||deleteFailed?opts.truncateBranch(deletionSubtitle(deleteFailed),opts.subtitleBudget):materializing?opts.truncateBranch(materializingSubtitle(),opts.subtitleBudget):branchWithMarks.length>0?opts.truncateBranch(branchWithMarks,opts.subtitleBudget):opts.truncateBranch(fallbackSubtitle,opts.subtitleBudget);return{isMain,titleText:isMain?repoBasename(task.repo):task.title,subtitleText,loading,stateGlyph,tone:sidebarTone(mark.tone),spinnerFrames,materializing}}function withSpinnerFrame(view,frame){if(!view.loading)return view;let frames=view.spinnerFrames,spinner=breathGlyph(frames,frame());if(spinner===view.stateGlyph)return view;return{...view,stateGlyph:spinner}}var listeners2=new Set,frame=0,timer2=null;function tick2(){frame=(frame+1)%SPINNER_TICK_CYCLE;for(let listener of listeners2)try{listener()}catch{}}function spinnerFrameSnapshot(){return frame}function subscribeSpinnerFrame(listener){if(listeners2.add(listener),timer2===null)timer2=setInterval(tick2,SPINNER_FRAME_MS),timer2.unref?.();return()=>{if(listeners2.delete(listener),listeners2.size===0&&timer2!==null)clearInterval(timer2),timer2=null,frame=0}}var POLL_TIMEOUT_MS=4000,SLOW_REPO_RETRY_MS=60000,MIN_POLL_INTERVAL_MS=1500,poller=createBackgroundPoller({initial:null,equals:sameWorktreeChanges,timeoutMs:POLL_TIMEOUT_MS,slowRetryMs:SLOW_REPO_RETRY_MS,minIntervalMs:MIN_POLL_INTERVAL_MS,run:async(worktreePath,signal)=>{recordSpawn("sidebar.worktreeChanges",["git","status","--porcelain=v1"],worktreePath);let res=await spawnCapture("git",["status","--porcelain=v1"],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal});if(res.status!==0)throw Error("git status failed");return parsePorcelain(res.stdout)}});var import_react48=__toESM(require_react_production(),1);function useDiffInks(){let{theme}=useTheme(),kv=useOptionalKV(),colorblind=normalizeColorblind(kv?.get(COLORBLIND_KEY,DEFAULT_COLORBLIND))==="on";return import_react48.useMemo(()=>diffInks(theme,colorblind),[theme,colorblind])}var NOOP_SUBSCRIBE=()=>()=>{},ZERO_FRAME=()=>0;function useSpinnerFrame(active){return import_react49.useSyncExternalStore(active?subscribeSpinnerFrame:NOOP_SUBSCRIBE,active?spinnerFrameSnapshot:ZERO_FRAME)}function usePollOnClock(key,poll){import_react49.useEffect(()=>{if(!key)return;return poll(key),subscribeSidebarPollClock(()=>poll(key))},[key,poll])}function useClockTick(active){return import_react49.useSyncExternalStore(active?subscribeSidebarPollClock:NOOP_SUBSCRIBE,active?sidebarPollClockSnapshot:ZERO_FRAME)}function completionStampOf(activity){return activity?.state==="turn_complete"?activity.at:void 0}function useDonePulse(completionAt){let[pulsingAt,setPulsingAt]=import_react49.useState(null),seenRef=import_react49.useRef(void 0),seeded=import_react49.useRef(!1);return import_react49.useEffect(()=>{let previous=seenRef.current;if(seenRef.current=completionAt,!seeded.current){seeded.current=!0;return}if(completionAt===void 0||completionAt===previous)return;setPulsingAt(completionAt);let timer3=setTimeout(()=>setPulsingAt(null),DONE_PULSE_MS);return()=>clearTimeout(timer3)},[completionAt]),pulsingAt!==null&&pulsingAt===completionAt}var import_react50=__toESM(require_react_production(),1);var SORT_MODE_CYCLE=["default","recent","attention","name"];function readSortMode(stored){return SORT_MODE_CYCLE.find((mode)=>mode===stored)??"recent"}function useSidebarHostState(args){let{kv,tasks:tasks2,focusSidebar,notify}=args,[sortMode,setSortMode]=import_react50.useState(()=>readSortMode(kv.get("activeSortMode"))),toggleSortMode=()=>{let next=SORT_MODE_CYCLE[(SORT_MODE_CYCLE.indexOf(sortMode)+1)%SORT_MODE_CYCLE.length]??"default";setSortMode(next),kv.set("activeSortMode",next)},[moveMode,setMoveModeState]=import_react50.useState(!1),setMoveMode=(next)=>{if(next&&sortMode!=="default")setSortMode("default"),kv.set("activeSortMode","default"),notify?.(t("tasks.sort.reorderSwitched"));setMoveModeState(next)};return{sortMode,setSortMode,toggleSortMode,moveMode,setMoveMode,onLocalMergeRequest:(id)=>{if(!tasks2.find((row)=>row.id===id))return;if(!moveMode)focusSidebar();setMoveMode(!moveMode)}}}var import_react51=__toESM(require_react_production(),1);import{spawnSync as spawnSync2}from"child_process";function planSelfRefresh(inputs){if(inputs.staleInstall)return{kind:"unavailable",reason:"install-gone"};let stale=!!inputs.daemonVersion&&inputs.daemonVersion!==inputs.clientVersion;if(inputs.daemonRestarting)return{kind:"refresh",restartDaemon:!1};if(stale)return{kind:"refresh",restartDaemon:!0};return{kind:"current"}}function selfRelaunchArgv(proc){return[proc.execPath,...proc.execArgv,...proc.argv.slice(1)]}function relaunchSelf(opts){try{opts.renderer?.destroy()}catch(err){console.error("Rove: renderer.destroy() failed during refresh:",err)}let argv=selfRelaunchArgv(opts.proc??process),[command,...args]=argv;if(opts.notice)process.stdout.write(`
65
65
  ${opts.notice}
66
66
  `);let execve=process.execve;if(execve)try{execve(command,argv,opts.env??process.env)}catch{}let result=spawnSync2(command,args,{stdio:"inherit",env:opts.env??process.env});if(result.error)process.stderr.write(`
67
67
  rove: could not relaunch (${result.error.message}). Start rove again from your shell; run rove doctor if it still fails.
68
- `),process.exit(1);process.exit(result.status??0)}import{TextAttributes as TextAttributes19}from"@opentui/core";function BannerStrip(props){let{theme}=useTheme(),ruleWidth=Math.max(4,props.width-2);return $jsxs("box",{flexDirection:"column",flexShrink:0,paddingLeft:1,paddingRight:1,paddingBottom:1,onMouseUp:props.onPress,children:[$jsx("text",{fg:props.tone,wrapMode:"none",children:"\u2594".repeat(ruleWidth)}),$jsx("box",{flexDirection:"row",gap:1,children:$jsx("text",{fg:props.tone,attributes:TextAttributes19.BOLD,wrapMode:"none",children:props.title})}),$jsx("box",{flexDirection:"row",gap:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:props.hint})})]})}function VersionSkewBanner(props){let{theme}=useTheme(),t3=useT();if(!props.stale)return null;let params={daemon:props.daemonVersion?`v${props.daemonVersion}`:t3("update.skew.olderBuild"),clientVersion:props.clientVersion},hint=props.refreshChord?t3("update.skew.hint",{...params,keys:props.refreshChord}):t3("update.skew.hintNoKey",params);return $jsx(BannerStrip,{tone:theme.warning,title:t3("update.skew.title"),hint,width:props.width})}function StaleInstallBanner(props){let{theme}=useTheme(),t3=useT();if(!props.message)return null;return $jsx(BannerStrip,{tone:theme.error,title:t3("update.staleInstall.title"),hint:t3("update.staleInstall.hint"),width:props.width})}function SkillBanner(props){let{theme}=useTheme(),t3=useT();if(props.engines.length===0)return null;let hint=props.error?t3("settings.engines.skill.failed",{reason:props.error}):t3("settings.engines.skill.bannerHint",{engines:props.engines.join(", ")});return $jsx(BannerStrip,{tone:props.error?theme.error:theme.primary,title:t3("settings.engines.skill.bannerTitle"),hint,width:props.width,onPress:props.onInstall})}function useHostBanner(orch,width){let daemonStale=useAccessor(orch.daemonStaleSignal()),daemonVersion=useAccessor(orch.daemonVersionSignal()),update=useAccessor(orch.updateSignal()),staleInstall=useAccessor(orch.staleInstallSignal()),daemonRestarting=useAccessor(orch.daemonRestartingSignal()),missingSkill=useAccessor(skillMissing),[skillError,setSkillError]=import_react51.useState(null),inputs={daemonVersion,clientVersion:CURRENT_VERSION,staleInstall,daemonRestarting},available=planSelfRefresh(inputs).kind==="refresh";return{element:staleInstall?$jsx(StaleInstallBanner,{message:staleInstall,width}):$jsxs($Fragment,{children:[$jsx(VersionSkewBanner,{stale:daemonStale,daemonVersion,clientVersion:CURRENT_VERSION,refreshChord:available?refreshChord():null,width}),$jsx(SkillBanner,{engines:missingSkill,error:skillError,onInstall:()=>setSkillError(installSkillNow()),width})]}),update,refresh:{available,inputs}}}function refreshChord(){let prefixKey=currentPrefixConfiguration().key,stroke=findBinding("app.refresh")?.prefixKeys?.[0];return prefixKey&&stroke?`${formatChord(prefixKey)} ${stroke}`:null}function FullWindowPage(props){return $jsxs("box",{flexDirection:"column",flexGrow:1,backgroundColor:props.background,children:[props.banner,props.children]})}var import_react59=__toESM(require_react_production(),1);var import_react58=__toESM(require_react_production(),1);async function remoteVerb(alias,verb,params){let envelope=await forwardVerb(requireMachine(alias),verb,params);if(!envelope.ok)throw Error(envelope.error.message);return envelope.result}async function remoteFiles(alias,taskId){return(await remoteVerb(alias,"worktree-files",{"task-id":taskId})).files}async function remoteChanges(alias,taskId,scope){let diff=await remoteVerb(alias,"worktree-diff",{"task-id":taskId}),entries=diff.files.filter((row)=>row.scope===scope).map((row)=>({path:row.path,status:row.status,added:row.added,deleted:row.deleted}));return{base:diff.base,entries}}function remotePreview(alias,taskId,relPath,base){return remoteVerb(alias,"worktree-diff-file",{"task-id":taskId,path:relPath,scope:base?"branch":"working"})}var lists=new Map;function cachedFileList(worktreePath){return lists.get(worktreePath)??null}function rememberFileList(worktreePath,files){lists.delete(worktreePath),lists.set(worktreePath,files);while(lists.size>4){let oldest=lists.keys().next().value;lists.delete(oldest)}}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{watch}from"fs";function statusToken(s2){switch(s2){case"M":return"warning";case"A":return"added";case"D":return"removed";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,w4){let stats=(w4.added>0?w4.added+1:0)+(w4.deleted>0?w4.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 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_react53=__toESM(require_react_production(),1);var import_react52=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes20}from"@opentui/core";var PLACEMENT={spinner:["rows","primary"],needsInput:["rows","warning"],attention:["rows","error"],unseen:["rows","primary"],idle:["rows","textMuted"],subagent:["rows","textMuted"],remote:["rows","textMuted"],done:["inbox","success"],rateLimited:["inbox","warning"],dead:["inbox","error"],routineFailed:["inbox","error"],conflict:["pr","error"],checksFailing:["pr","error"],checksPassing:["pr","success"],running:null},GROUP_ORDER=["rows","inbox","pr"];function glyphLegendSections(glyphs){let marks=Object.keys(PLACEMENT);return GROUP_ORDER.map((group)=>({group,rows:marks.flatMap((mark)=>{let placement=PLACEMENT[mark];if(placement?.[0]!==group)return[];let value=glyphs[mark];return[{mark,glyph:typeof value==="string"?value:value[0]??"",tone:placement[1]}]})}))}function useGlyphs(){return GLYPH_SETS[normalizeGlyphSet(useOptionalKV()?.get(GLYPH_SET_KEY,DEFAULT_GLYPH_SET))]}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(),[filtering,setFiltering]=import_react52.useState(!1),[query,setQuery]=import_react52.useState(""),keymapVersion2=useKeymapVersion(),pureTuiPrefix=currentPrefixConfiguration(),filteredSections=import_react52.useMemo(()=>grammarHelpSections(RoveKeymap,props.currentScope??null,pureTuiPrefix.key,props.reachability),[keymapVersion2,props.currentScope,props.reachability,pureTuiPrefix.key]).map((section)=>({...section,rows:section.rows.filter((row)=>matchesHelpAction(query,tKeys("desc",row.binding.id),row.primary))})).filter((section)=>section.rows.length>0),glyphs=useGlyphs(),legendSections=glyphLegendSections(glyphs).map((section)=>({...section,rows:section.rows.filter((row)=>matchesHelpAction(query,t3(`help.mark.${row.mark}`),row.glyph))})).filter((section)=>section.rows.length>0),close=()=>props.onClose?props.onClose():dialog.clear(),scrollRef=import_react52.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:[...!filtering?[{key:"?",cmd:close},{key:"/",cmd:()=>setFiltering(!0)}]:[],{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:TextAttributes20.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:TextAttributes20.DIM,children:t3("help.scrollKeys")}),$jsx("text",{fg:theme.textMuted,onMouseUp:close,children:t3("help.esc")})]})]}),filtering?$jsx("input",{focused:!0,value:query,placeholder:t3("help.search"),onInput:(value)=>{setQuery(value),scrollToEdge("top")}}):$jsx("text",{fg:theme.textMuted,children:t3("help.filter")}),filteredSections.length===0&&legendSections.length===0?$jsx("text",{fg:theme.textMuted,children:t3("help.noResults")}):null,$jsx("scrollbox",{ref:(r6)=>{scrollRef.current=r6},flexShrink:1,flexGrow:1,stickyScroll:!1,verticalScrollbarOptions:{trackOptions:{backgroundColor:theme.backgroundDialog,foregroundColor:theme.borderActive}},children:$jsxs("box",{paddingBottom:1,gap:1,paddingRight:1,children:[filteredSections.map((section,sectionIndex)=>$jsxs("box",{gap:0,children:[$jsx("text",{fg:theme.accent,attributes:TextAttributes20.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}`)),legendSections.map((section)=>$jsxs("box",{gap:0,children:[$jsx("text",{fg:theme.accent,attributes:TextAttributes20.BOLD,children:t3(`help.marks.${section.group}`)}),section.rows.map((row)=>$jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,children:[$jsx("box",{width:18,children:$jsx("text",{fg:theme[row.tone],children:row.glyph})}),$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.text,children:t3(`help.mark.${row.mark}`)})})]},`mark-${row.mark}`))]},`marks-${section.group}`))]})})]})}HelpDialog.show=(dialog,currentScope)=>{let reachability=currentBindingReachability(),inputScope=reachability.inputPassthrough?"terminal":currentScope;dialog.replace(()=>$jsx(HelpDialog,{currentScope:inputScope,reachability}))};var EMPTY_HINT_SNAPSHOT={tokens:[],modal:!1};function useStatusKeyHintItems(opts){let t3=useT(),kv=useOptionalKV(),focus=useOptionalFocus(),dialog=useOptionalDialog(),keymapVersion2=useKeymapVersion(),hintsEnabled=keyHintsEnabled(kv?.get(KEY_HINTS_ENABLED_KEY,!0)),[snapshot,setSnapshot]=import_react53.useState(EMPTY_HINT_SNAPSHOT),shownRef=import_react53.useRef(snapshot),enabledRef=import_react53.useRef(hintsEnabled),dialogDepthRef=import_react53.useRef(dialog?.stack.length??0);enabledRef.current=hintsEnabled,dialogDepthRef.current=dialog?.stack.length??0;let refresh=import_react53.useCallback(()=>{let enabled=enabledRef.current,nextModal=modalActive()||dialogDepthRef.current>0,fresh=enabled&&!nextModal?statusHintTokens(currentBindingReachability(),currentPrefixConfiguration().key):null,prev=shownRef.current,nextTokens=fresh??(enabled?prev.tokens:[]);if(prev.modal===nextModal&&prev.tokens.length===nextTokens.length&&prev.tokens.every((tok,i2)=>tok.chord===nextTokens[i2]?.chord&&tok.msg===nextTokens[i2]?.msg))return;let next={tokens:nextTokens,modal:nextModal};shownRef.current=next,setSnapshot(next)},[]);import_react53.useEffect(()=>{let queued=!1,live=!0,unsubscribe=subscribeBindingStack(()=>{if(queued)return;queued=!0,queueMicrotask(()=>{if(queued=!1,live)refresh()})});return()=>{live=!1,unsubscribe()}},[refresh]),import_react53.useEffect(refresh,[keymapVersion2,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_react53.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_react57=__toESM(require_react_production(),1);var import_react54=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes21}from"@opentui/core";var FileTreeRowView=import_react54.memo(function(props){let{theme}=useTheme(),inks=useDiffInks(),selection=resolveRowSelectionChrome2(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:TextAttributes21.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 isUntrackedDir=row.fileCount!==void 0,marker=isUntrackedDir?row.expanded?"\u25BE ":"\u25B8 ":"",countSuffix=isUntrackedDir?` (${row.fileCount})`:"",indent=row.child?" ":"",pathBudget=props.pathBudget-displayWidth(marker)-displayWidth(countSuffix)-displayWidth(indent),tone=statusToken(row.status),statusColor=tone==="added"?inks.added:tone==="warning"?theme.warning:tone==="removed"?inks.removed: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:isUntrackedDir?theme.textMuted:theme.text,wrapMode:"none",flexGrow:1,children:`${indent}${marker}${truncatePathTail(row.path,pathBudget)}${countSuffix}`}),props.statWidths.added>0?$jsx("text",{fg:inks.added,wrapMode:"none",children:statCell(row.added,props.statWidths.added,"+")}):null,props.statWidths.deleted>0?$jsx("text",{fg:inks.removed,wrapMode:"none",children:statCell(row.deleted,props.statWidths.deleted,"-")}):null]})]})});var import_react56=__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_react56.useState({top:0,height:0}),sample=import_react56.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_react56.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_react57.useState(null),rowWindow=useRowWindow({scrollEl,rowCount:rows.length}),rowCount=rows.length,sample=rowWindow.sample;return import_react57.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 TextAttributes22}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:TextAttributes22.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:TextAttributes22.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?TextAttributes22.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 dims=useTerminalSize(),[tab,setTab]=import_react58.useState("all"),[scope,setScope]=import_react58.useState("working"),[scopeManual,setScopeManual]=import_react58.useState(!1),[base,setBase]=import_react58.useState(null),[cursorIndex,setCursorIndex]=import_react58.useState(0),[refreshTick,setRefreshTick]=import_react58.useState(0),[allFiles,setAllFiles]=import_react58.useState(null),[changes,setChanges]=import_react58.useState(null),[error,setError]=import_react58.useState(null),[expandedDirs,setExpandedDirs]=import_react58.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_react58.useRef(0),remoteRef=useLatest(props.remote),refetch=import_react58.useCallback(async(currentTab,path,signal)=>{let seq2=++fetchSeq.current;if(path==null){setAllFiles(null),setChanges(null),setError(null);return}setError(null);try{let remote=remoteRef.current;if(currentTab==="all"){let files=remote?await remoteFiles(remote.machine,remote.taskId):await listFiles(path,signal);if(signal?.aborted||seq2!==fetchSeq.current||pathRef.current!==path)return;rememberFileList(cacheKey(path,remote),files),setAllFiles((prev)=>sameFileList(prev,files)?prev:files)}else if(currentTab==="changes"){let wantBranch=scopeRef.current==="branch"&&baseRef.current!=null,entries=remote?(await remoteChanges(remote.machine,remote.taskId,wantBranch?"branch":"working")).entries:wantBranch?await statusFilesBranch(path,baseRef.current,signal):await statusFiles(path,signal);if(signal?.aborted||seq2!==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(seq2===fetchSeq.current&&pathRef.current===path)setError(message)}},[]);import_react58.useEffect(()=>{let path=props.worktreePath;setAllFiles(path!=null&&tabRef.current==="all"?cachedFileList(cacheKey(path,remoteRef.current)):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_react58.useEffect(()=>{let path=props.worktreePath;if(path==null){setBase(null);return}let disposed=!1,controller=new AbortController,remote=remoteRef.current;return(remote?remoteChanges(remote.machine,remote.taskId,"branch").then((r6)=>r6.base):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_react58.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_react58.useEffect(()=>{let path=props.worktreePath;if(path==null)return;if(readRoveEnv("FILETREE_WATCH")==="0")return;if(props.remote)return;return watchWorktree(path,()=>setRefreshTick((n2)=>n2+1))},[props.worktreePath,props.remote]),import_react58.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_react58.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_react58.useMemo(()=>allFiles==null?null:buildTree(allFiles),[allFiles]),prevRows=import_react58.useRef([]),rows=import_react58.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_react58.useEffect(()=>{if(rows.length===0)return;setCursorIndex((i2)=>i2>rows.length-1?rows.length-1:i2)},[rows]);let statWidths=import_react58.useMemo(()=>computeStatWidths(rows),[rows]),paneWidth=props.paneWidth??dims.width,pathBudget=import_react58.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_react58.useCallback((row)=>{if(row.kind==="dir"||row.path.endsWith("/"))setExpandedDirs((prev)=>toggleDir(prev,row.path));else onOpenFileRef.current(row.path)},[]),handleRowActivate=import_react58.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 loaded2=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:loaded2,tab}),props.worktreePath!=null?$jsx("box",{flexDirection:"row",justifyContent:"flex-end",paddingTop:1,flexShrink:0,children:$jsx(PaneKeyHint,{pane:"files"})}):null]})}function cacheKey(path,remote){return remote?`${remote.machine}:${path}`:path}var WORKTREE_TOOLS_MIN_WIDTH=22,WORKTREE_TOOLS_MAX_WIDTH=34;function useFilesPaneActions(actions){let latest=useLatest(actions);return import_react59.useMemo(()=>({onOpenFile:(relPath)=>latest.current.onOpenFile(relPath),onOpenDiff:(relPath,base)=>latest.current.onOpenDiff(relPath,base),onMention:(relPath)=>latest.current.onMention(relPath),onZenToggle:()=>latest.current.onZenToggle(),onCreatePR:()=>latest.current.onCreatePR()}),[])}var HostFilesPane=import_react59.memo(function(props){let{theme}=useTheme(),t3=useT(),focus=useFocus(),dims=useTerminalSize(),inactiveBorder=theme.borderActive,available=Math.max(WORKTREE_TOOLS_MIN_WIDTH,dims.width-props.sidebarWidth),width=Math.max(WORKTREE_TOOLS_MIN_WIDTH,Math.min(WORKTREE_TOOLS_MAX_WIDTH,Math.floor(available/3)));return $jsx(RenderProfiler,{id:"files",children:$jsx("box",{width,flexShrink:0,borderStyle:"rounded",borderColor:focus.focused==="files"?theme.focusAccent:inactiveBorder,onMouseUp:()=>focus.setFocused("files"),children:$jsx(PaneErrorBoundary,{region:"files",resetKeys:[props.worktree],children:props.remoteHost&&!props.remote?$jsxs("box",{flexDirection:"column",padding:1,gap:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("tasks.machine.filesElsewhere",{host:props.remoteHost})}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("tasks.machine.filesHint",{host:props.remoteHost})})]}):$jsx(FileTree,{worktreePath:props.worktree,paneWidth:width-2,prBaseRef:props.prBaseRef,remote:props.remote,focused:props.focused,onOpenFile:props.actions.onOpenFile,onOpenDiff:props.actions.onOpenDiff,onMention:props.actions.onMention,onZenToggle:props.actions.onZenToggle,onCreatePR:props.taskKind==="main"?void 0:props.actions.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((w4)=>({label:w4.label,percentText:`${w4.percent}%`,resetText:formatReset(w4.resetsAt,nowMs),tone:toneOf(w4.percent)}))}function narrowUsageChip(usage,nowMs){let w4=usage.windows.find((win)=>win.kind==="session")??usage.windows[0];if(!w4)return null;return{label:w4.label,percentText:`${w4.percent}%`,resetText:formatReset(w4.resetsAt,nowMs),tone:toneOf(w4.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((entry2)=>entry2.chips.length>0);if(entries.length===0)return null;if(!opts.forceCompact){let fulls=entries.map((entry2)=>({vendor:entry2.vendor,chips:entry2.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 entry2 of entries){let chip=narrowUsageChip(entry2.snapshot,opts.nowMs);if(!chip)continue;let gap=vendors.length>0?2:0,need=displayWidth(entry2.vendor)+1+displayWidth(chip.percentText);if(need+gap<=remaining){vendors.push({vendor:entry2.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(entry2.vendor,nameBudget,approxCharCells),percentText:chip.percentText,tone:chip.tone});break}return{form:"compact",vendors}}function contextChip(usage){if(!usage)return null;let window2=usage.contextWindowTokens;if(window2===void 0||window2<=0)return null;let percent=Math.min(100,Math.max(0,Math.round(usage.contextTokens/window2*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((w4,win)=>Math.max(w4,displayWidth(win.label)),2));return usage.windows.map((w4)=>({label:padEndCells(truncateEndCells(w4.label,labelWidth,charWidth),labelWidth),bar:ratioBar(w4.percent/100,USAGE_BAR_WIDTH),percentText:`${String(w4.percent).padStart(3)}%`,resetText:formatReset(w4.resetsAt,nowMs),tone:toneOf(w4.percent)}))}function ContextChip(props){let{theme}=useTheme(),chip=props.chip;if(!chip)return null;let toneColor3={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:toneColor3[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()),toneColor3={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:toneColor3[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:toneColor3[vendor.tone],wrapMode:"none",children:vendor.percentText})]},`${vendor.vendor}-${index}`))})}function WorkspaceFrame(props){let{theme}=useTheme(),dims=useTerminalSize(),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,onMouseDrag:props.onPaneDrag,onMouseUp:props.onPaneRelease,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]})})}var import_react62=__toESM(require_react_production(),1);var import_react60=__toESM(require_react_production(),1);var MIN_CHARS=2,DEBOUNCE_MS=300,LIMIT=30;function matchingTasks(tasks2,query){let q2=query.trim();if(!q2)return[];return tasks2.filter((task)=>task.kind!=="dir"&&fuzzyMatch(q2,task.title))}function useSaid(search,query){let[state,setState]=import_react60.useState({kind:"idle"}),seq2=import_react60.useRef(0),orchestrator=search?.orchestrator,debounceMs=search?.debounceMs??DEBOUNCE_MS;return import_react60.useEffect(()=>{let q2=query.trim(),mine=++seq2.current;if(!orchestrator||q2.length<MIN_CHARS){setState({kind:"idle"});return}let timer3=setTimeout(()=>{setState({kind:"searching"}),searchTasks(orchestrator.listTasks(),q2,LIMIT).then((result)=>mine===seq2.current&&setState({kind:"done",result}),(err)=>mine===seq2.current&&setState({kind:"failed",reason:err instanceof Error?err.message:String(err)}))},debounceMs);return()=>clearTimeout(timer3)},[query,orchestrator,debounceMs]),state}function useMatchingTasks(search,query){let tasks2=search?.tasks;return import_react60.useMemo(()=>tasks2?matchingTasks(tasks2,query):[],[tasks2,query])}function splitMarked(text,needle){let n2=needle.trim().toLowerCase();if(!n2)return[text];let lower=text.toLowerCase(),parts=[],from=0;for(let at2=lower.indexOf(n2);at2>=0;at2=lower.indexOf(n2,from))parts.push(text.slice(from,at2),text.slice(at2,at2+n2.length)),from=at2+n2.length;return parts.push(text.slice(from)),parts}function CommandPalette({actions,search}){let dialog=useDialog(),{theme}=useTheme(),t3=useT(),padX=useDialogPaddingX(),dimensions=useTerminalSize(),[query,setQuery]=import_react62.useState(""),[selected,setSelected]=import_react62.useState(0),prefix=currentPrefixConfiguration().key,commands=actions.map((action)=>({kind:"command",key:`c:${action.id}`,action,name:tKeys("desc",action.id),chord:action.prefix?`${prefix?formatChord(prefix):""} + ${formatChord(action.key)}`:formatChord(action.key)})).filter((row)=>matchesHelpAction(query,row.name,row.action.prefix?`${prefix} + ${row.action.key}`:row.action.key)),tasks2=useMatchingTasks(search,query).map((task)=>({kind:"task",key:`t:${task.id}`,name:task.title,taskId:task.id})),said=useSaid(search,query),hits=said.kind==="done"?said.result.matches.map((hit,i2)=>({kind:"said",key:`s:${hit.taskId}:${hit.at}:${i2}`,name:hit.title,taskId:hit.taskId,...hit.tabId?{tabId:hit.tabId}:{},role:hit.role,at:hit.at,snippet:hit.snippet})):[],rows=[...commands,...tasks2,...hits],extra=tasks2.length>0||said.kind!=="idle",visibleCount=Math.max(1,Math.min(10,dimensions.height-10-(extra?6:0))),index=Math.min(selected,Math.max(0,rows.length-1)),run=(row)=>{if(flushSync(()=>dialog.clear({refocus:!1})),row.kind==="command"){if(!row.action.run())dialog.replace(()=>$jsx("text",{fg:theme.warning,children:t3("help.unavailable")}))}else search?.openTask(row.taskId,row.kind==="said"?row.tabId:void 0)};useBindings(()=>({bindings:[{key:"up",cmd:()=>setSelected(Math.max(0,index-1))},{key:"down",cmd:()=>setSelected(Math.min(rows.length-1,index+1))},{key:"return",cmd:()=>{let row=rows[index];if(row)run(row)}}]}));let start=Math.max(0,index-visibleCount+1),now=Date.now(),head=(at2,row)=>{if(!extra||at2>0&&rows[at2-1]?.kind===row.kind)return null;let label={command:"search.commands",task:"search.tasks",said:"search.inConversations"};return $jsx("text",{fg:theme.textMuted,children:t3(label[row.kind])})};return $jsxs("box",{paddingLeft:padX,paddingRight:padX,paddingBottom:1,gap:1,children:[$jsx("text",{fg:theme.accent,children:t3("help.palette")}),$jsx("input",{focused:!0,value:query,placeholder:t3("help.search"),onInput:(value)=>{setQuery(value),setSelected(0)}}),$jsxs("box",{children:[rows.length===0&&said.kind==="idle"?$jsx("text",{fg:theme.textMuted,children:t3("help.noResults")}):rows.slice(start,start+visibleCount).map((row,offset)=>{let at2=start+offset,picked=at2===index;return $jsxs("box",{flexDirection:"column",children:[head(at2,row),$jsxs("box",{flexDirection:"column",backgroundColor:picked?theme.backgroundElement:void 0,onMouseUp:()=>run(row),children:[$jsxs("box",{flexDirection:"row",gap:2,children:[$jsx("text",{fg:theme.text,flexGrow:1,flexBasis:0,flexShrink:1,children:`${picked?"\u203A ":" "}${row.name}`}),row.kind==="command"&&$jsx("text",{fg:theme.primary,flexShrink:0,children:row.chord}),row.kind==="said"&&$jsx("text",{fg:theme.textMuted,flexShrink:0,children:`${t3(row.role==="user"?"search.you":"search.agent")} \xB7 ${relativeAge(Date.parse(row.at),now)}`})]}),row.kind==="said"&&$jsxs("text",{fg:theme.textMuted,children:[" ",splitMarked(row.snippet,query).map((part,i2)=>$jsx("span",{fg:i2%2===1?theme.accent:theme.textMuted,children:part},i2))]})]})]},row.key)}),said.kind!=="idle"&&hits.length===0&&$jsxs("box",{flexDirection:"column",children:[$jsx("text",{fg:theme.textMuted,children:t3("search.inConversations")}),said.kind==="searching"&&$jsx("text",{fg:theme.textMuted,children:t3("search.searching")}),said.kind==="failed"&&$jsx("text",{fg:theme.error,children:t3("search.failed",{reason:said.reason})}),said.kind==="done"&&$jsx("text",{fg:theme.textMuted,children:t3("search.none",{query:said.result.query})})]}),said.kind==="done"&&said.result.truncated&&$jsx("text",{fg:theme.textMuted,children:t3("search.truncated")}),said.kind==="done"&&said.result.skipped.length>0&&$jsx("text",{fg:theme.textMuted,children:t3("search.skipped",{count:said.result.skipped.length})})]}),$jsx("text",{fg:theme.textMuted,children:t3("help.run")})]})}CommandPalette.show=(dialog,search)=>{let actions=currentPaletteActions();dialog.replace(()=>$jsx(CommandPalette,{actions,...search?{search}:{}}))};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(current2,delta,opts){let reachable=PANE_CYCLE.filter((pane)=>pane!=="files"||opts.filesVisible),idx=reachable.indexOf(current2);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 pageEntries2=usePageEntries(),{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},pagesClosed=workspacePagesClosed(pages);useBindings(()=>({enabled:pagesClosed,bindings:[...bindByIds({"help.open":prefixAction(()=>HelpDialog.show(dialog,focus.focused)),"palette.open":prefixAction(()=>CommandPalette.show(dialog,deps.paletteSearch)),"focus.previous":prefixAction(()=>cyclePane(-1)),"focus.next":prefixAction(()=>cyclePane(1)),"workspace.zenToggle":prefixAction(()=>deps.toggleZen()),"attention.next":prefixAction(()=>deps.jumpToNextAttention()),"inbox.show":prefixAction(()=>deps.openInbox()),...Object.fromEntries(pageEntries2.flatMap((page)=>page.action?[[page.action,prefixAction(()=>deps.pages.openPage(page.id))]]:[])),"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":prefixAction(()=>deps.createTask())})})),useBindings(()=>({enabled:pagesClosed&&focus.focused!=="sidebar",bindings:bindByIds({"focus.sidebar":prefixAction(()=>focus.setFocused("sidebar"))})})),useBindings(()=>({enabled:pagesClosed&&deps.refresh?.available!==!0,bindings:bindByIds({"view.redraw":prefixAction(()=>{if(renderer)redrawScreen(renderer)})})})),useBindings(()=>({enabled:!pages.dialogOpen&&deps.refresh?.available===!0,bindings:bindByIds({"app.refresh":prefixAction(()=>deps.refresh?.run())})})),useBindings(()=>({enabled:pagesClosed&&focus.focused==="sidebar"&&!deps.searchActive,bindings:bindByIds({"app.quit":(_evt,slot)=>{if(slot===1){exitApp();return}quit()},"settings.open.sidebar":prefixAction(()=>deps.pages.openSettings()),"worktrees.open.sidebar":prefixAction(()=>deps.pages.openWorktrees()),"tasks.update":prefixAction(()=>deps.pages.openUpdate())})})),useBindings(()=>({enabled:pagesClosed&&focus.focused==="sidebar"&&!deps.searchActive,bindings:bindByIds({"task.new":prefixAction(()=>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":prefixAction(()=>focus.setFocused("workspace")),"sidebar.sort":prefixAction(()=>deps.toggleSortMode())})})),useBindings(()=>({enabled:settingsCloseKeysEnabled(pages),bindings:pageCloseBindings(deps.pages.closeSettings)})),usePluginKeybindings(pagesClosed)}var import_react83=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes39}from"@opentui/core";var import_react79=__toESM(require_react_production(),1);import{unlinkSync}from"fs";import{join}from"path";function hasRestartableDaemon(orchestrator){return orchestrator instanceof RemoteOrchestrator}function destroyRendererSafely(renderer,action){try{renderer?.destroy()}catch(err){console.error(`Rove: renderer.destroy() failed during ${action}:`,err)}}function removeTasksFileForReset(){try{unlinkSync(join(roveStateDir(),"tasks.json"))}catch(err){if(err.code!=="ENOENT")console.error("Rove: failed to delete tasks.json during reset:",err)}}async function confirmResetState(dialog,kv,renderer){if(await DialogConfirm.show(dialog,t("settings.reset.title"),t("settings.reset.body"),"cancel",void 0,{danger:!0})!==!0)return;if(!kv.clear()){await DialogConfirm.show(dialog,t("settings.reset.failedTitle"),t("settings.reset.failedBody"),"cancel");return}removeTasksFileForReset(),destroyRendererSafely(renderer,"reset"),process.stderr.write(`${t("settings.reset.done")}
69
- `),process.exit(0)}async function confirmRestartDaemon(dialog,orchestrator,renderer){if(!hasRestartableDaemon(orchestrator))return;if(await DialogConfirm.show(dialog,t("settings.restart.title"),t("settings.restart.body"),"cancel")!==!0)return;await orchestrator.restartDaemon(),relaunchSelf({renderer,notice:t("settings.restart.done")})}async function confirmTryChannel(dialog,renderer,channel){if(await DialogConfirm.show(dialog,t(`settings.general.updateTryTitle.${channel}`),t(`settings.general.updateTryBody.${channel}`),"cancel")!==!0)return;await runShellUpdater({renderer:renderer??null,t,targetLabel:channel,command:updateCommandFor(channel),onSuccess:()=>rememberReleaseChannel(channel)})}function reloadSettingsStatus(kv){let result=kv.reload();if(!result.ok){let error=result.error instanceof Error?result.error.message:String(result.error);return t("settings.dev.reloadFailed",{error})}return result.changed===0?t("settings.dev.reloadUnchanged"):t("settings.dev.reloadDone",{count:result.changed})}async function installEngineHooks(){try{let{ensureGlobalRoveHooks}=await import("./chunk-6q4br0pt.js");await ensureGlobalRoveHooks({quiet:!0})}catch{}}async function uninstallEngineHooks(){try{let{activityHookAdapters}=await import("./chunk-2kt0mfvf.js");await Promise.all(activityHookAdapters().map(async(adapter)=>{try{await adapter.removeActivityHooks(adapter.globalSettingsPath())}catch{}}))}catch{}}import{TextAttributes as TextAttributes24}from"@opentui/core";var FILLS=["\u25CB","\u25D4","\u25D1","\u25D5","\u25CF","\u25C9"];function effortMark(levels,level){let index=levels&&level?levels.indexOf(level.trim()):-1;if(!levels||index<0)return null;let fraction=levels.length>1?index/(levels.length-1):1;return{glyph:FILLS[Math.round(fraction*(FILLS.length-1)-0.000000001)]??FILLS[0],fraction}}function effortLabel(levels,level){let mark=effortMark(levels,level);return mark?`${mark.glyph} ${level}`:level}import{TextAttributes as TextAttributes23}from"@opentui/core";function Row(props){let{theme}=useTheme();return $jsxs("box",{ref:props.rowRef,flexDirection:"row",gap:1,paddingLeft:1,paddingRight:1,overflow:"hidden",backgroundColor:props.cursor?theme.primary:props.idleBackground,onMouseUp:props.onMouseUp,children:[$jsx("text",{fg:props.cursor?theme.selectedListItemText:props.fg,attributes:props.bold?TextAttributes23.BOLD:void 0,wrapMode:"none",children:props.children}),props.hint?$jsx("text",{fg:props.cursor?theme.selectedListItemText:theme.textMuted,wrapMode:"none",flexShrink:1,children:props.hint}):null]})}function SubSection(props){let{theme}=useTheme();return $jsxs("box",{flexDirection:"column",gap:0,paddingTop:props.paddingTop??1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes23.BOLD,children:props.title}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:props.hint}),props.children]})}function AutoRoutingSettingsSection(props){let{theme}=useTheme(),t3=useT(),rows=autoRoutingRows(),{table}=props.autoRouting,isBodyCursor=(row)=>props.level==="body"&&props.bodyRow===row;return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes24.BOLD,children:t3("settings.autoRouting.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.autoRouting.hint")}),table===null?$jsx("text",{fg:theme.warning,wrapMode:"word",children:t3("settings.autoRouting.unconfigured")}):null,$jsx("box",{flexDirection:"column",gap:0,children:rows.map((row)=>{if(row.kind!=="autoRoutingTier")return null;let tier=row.tier,i2=rowIndex(rows,row.id),target=table?.[tier],block=props.autoRouting.block(tier),label=`${t3(`tasks.tier.${tier}`)}`.padEnd(10),fields=target?[engineDisplayName(target.engine),target.model??t3("settings.autoRouting.engineDefault"),target.effort?effortLabel(engineEntry(target.engine).effortLevels,target.effort):t3("settings.autoRouting.engineDefault")].join(" \xB7 "):"\u2014";return $jsxs("box",{flexDirection:"column",gap:0,children:[$jsx(Row,{cursor:isBodyCursor(i2),rowRef:props.rowRef(i2),onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(i2),props.autoRouting.edit(tier)},fg:theme.text,bold:!0,hint:fields,children:label}),$jsx("box",{flexDirection:"row",gap:1,paddingLeft:3,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:1,children:t3(`tasks.tierDesc.${tier}`)})}),$jsx("box",{flexDirection:"row",gap:1,paddingLeft:3,overflow:"hidden",children:block===void 0?$jsx("text",{fg:theme.textMuted,children:t3("settings.accounts.checking")}):block===null?$jsx("text",{fg:theme.success,children:t3("settings.autoRouting.ready")}):$jsx("text",{fg:theme.warning,wrapMode:"none",flexShrink:1,children:t3("settings.autoRouting.unavailable",{reason:describeTierBlock(block)})})})]},row.id)})}),$jsx(ClassifierRows,{...props})]})}function ClassifierRows(props){let{theme}=useTheme(),t3=useT(),rows=autoRoutingRows(),c2=props.classifier,isBodyCursor=(row)=>props.level==="body"&&props.bodyRow===row,on=c2.mode!=="off",modeLabel=c2.mode==="off"?t3("settings.autoRouting.classifierOff"):c2.mode==="jev"?"jev":t3("settings.autoRouting.classifierCustomLabel"),modeHint=c2.mode==="off"?t3("settings.autoRouting.classifierOffHint"):c2.mode==="jev"?t3("settings.autoRouting.classifierJevHint"):t3("settings.autoRouting.classifierCustomHint");function open(id,run){let i2=rowIndex(rows,id);return{i:i2,onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(i2),run()}}}let status=(()=>{if(c2.mode==="off")return null;if(!c2.keyConfigured)return{ok:!0,text:t3("settings.autoRouting.keyCustomUnused")};if(c2.keySource==="env")return{ok:!0,text:t3("settings.autoRouting.keyPresentEnv",{env:c2.keyEnv})};if(c2.keySource==="file")return{ok:!0,text:t3("settings.autoRouting.keySaved")};return{ok:!1,text:t3("settings.autoRouting.keyMissing")}})(),mode=open("auto-routing-classifier",()=>c2.cycle()),endpoint=open("auto-routing-endpoint",()=>void c2.editEndpoint()),threshold=open("auto-routing-threshold",()=>void c2.editThreshold()),key=open("auto-routing-key",()=>void c2.editKey()),keyValue=c2.keySource==="env"?t3("settings.autoRouting.keyFromEnv",{env:c2.keyEnv}):c2.keySource==="file"?t3("settings.autoRouting.keyStored",{hint:c2.keyHint}):t3("settings.autoRouting.keyNone");return $jsxs(SubSection,{title:t3("settings.autoRouting.classifierTitle"),hint:t3("settings.autoRouting.classifierHint"),children:[$jsx("box",{paddingTop:1,paddingBottom:1,children:$jsx("text",{fg:on?theme.warning:theme.textMuted,wrapMode:"word",children:t3("settings.autoRouting.classifierDataFlow")})}),$jsx(Row,{cursor:isBodyCursor(mode.i),rowRef:props.rowRef(mode.i),onMouseUp:mode.onMouseUp,fg:theme.text,hint:modeHint,children:`${t3("settings.autoRouting.classifierLabel").padEnd(20)}${modeLabel}`}),$jsx(Row,{cursor:isBodyCursor(endpoint.i),rowRef:props.rowRef(endpoint.i),onMouseUp:endpoint.onMouseUp,fg:c2.mode==="custom"?theme.text:theme.textMuted,children:`${t3("settings.autoRouting.endpointLabel").padEnd(20)}${c2.endpoint||t3("settings.autoRouting.endpointUnset")}`}),$jsx(Row,{cursor:isBodyCursor(threshold.i),rowRef:props.rowRef(threshold.i),onMouseUp:threshold.onMouseUp,fg:theme.text,hint:t3("settings.autoRouting.thresholdHint"),children:`${t3("settings.autoRouting.thresholdLabel").padEnd(20)}${c2.threshold.toFixed(2)}`}),$jsx(Row,{cursor:isBodyCursor(key.i),rowRef:props.rowRef(key.i),onMouseUp:key.onMouseUp,fg:theme.text,children:`${t3("settings.autoRouting.keyLabel").padEnd(20)}${keyValue}`}),status?$jsx("box",{paddingTop:1,children:$jsx("text",{fg:status.ok?theme.success:theme.warning,wrapMode:"word",children:status.text})}):null]})}var import_react64=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes26}from"@opentui/core";function engineHealth(facts){if(facts.binaryFound===void 0)return{key:"settings.engines.status.checking",tone:"unknown"};if(facts.binaryFound===null)return{key:"settings.engines.status.unknown",tone:"unknown"};if(!facts.binaryFound)return facts.commandChosen?{key:"settings.engines.status.notOnPath",tone:"attention"}:{key:"settings.engines.status.notInstalled",tone:"absent"};if(facts.configIssue)return{key:"settings.engines.status.integrationBlocked",tone:"error"};if(facts.login==="no")return{key:"settings.engines.status.signIn",tone:"attention"};if(facts.hooks==="outdated")return{key:"settings.engines.status.integrationOutdated",tone:"attention"};if(facts.hooks==="not-installed")return{key:"settings.engines.status.integrationMissing",tone:"attention"};return{key:"settings.engines.status.ready",tone:"ready"}}function engineLogin(status){if(!status||status.account===null||status.accountError)return"unknown";return status.account.kind==="none"?"no":"yes"}import{TextAttributes as TextAttributes25}from"@opentui/core";function EngineDetails(props){let{theme}=useTheme(),t3=useT(),binary=props.commandText.split(/\s+/)[0]??props.commandText,facts=[{label:t3("settings.engines.detail.program"),lines:[programLine(props,binary,t3,theme)]},{label:t3("settings.engines.detail.command"),lines:[{text:t3(props.commandIsOwn?"settings.engines.detail.commandCustom":"settings.engines.detail.commandDefault",{command:props.commandText})}]},{label:t3("settings.engines.detail.signIn"),lines:[signInLine(props,t3,theme)]}];if(props.integration)facts.push({label:t3("settings.engines.detail.reporting"),lines:reportingLines(props,t3,theme)});if(props.integration?.skillDir){let{skillDir,skillState}=props.integration;facts.push({label:t3("settings.engines.detail.skill"),lines:[skillState==="installed"?{text:t3("settings.engines.detail.skillInstalled",{dir:tildify(skillDir)})}:{text:t3(skillState==="outdated"?"settings.engines.detail.skillOutdated":"settings.engines.detail.skillMissing"),fg:theme.warning}]})}if(props.protocol)facts.push({label:t3("settings.engines.detail.adapter"),lines:[{text:props.protocol.declared?t3("settings.engines.detail.adapterDeclared",{protocol:props.protocol.declared}):t3("settings.engines.detail.adapterGeneric"),fg:props.protocol.declared?void 0:theme.textMuted}]});let labelWidth=facts.reduce((max,f2)=>Math.max(max,displayWidth(f2.label)),0);return $jsxs("box",{flexDirection:"column",gap:0,paddingLeft:1,paddingRight:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes25.BOLD,wrapMode:"none",children:props.name}),facts.map((fact)=>$jsxs("box",{flexDirection:"row",gap:2,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:fact.label+" ".repeat(Math.max(0,labelWidth-displayWidth(fact.label)))}),$jsx("box",{flexDirection:"column",flexShrink:1,flexGrow:1,children:fact.lines.map((line)=>$jsx("text",{fg:line.fg??theme.text,wrapMode:"word",children:line.text},line.text))})]},fact.label))]})}function programLine(props,binary,t3,theme){let s2=props.status;if(!s2)return props.probing?{text:t3("settings.accounts.checking"),fg:theme.textMuted}:{text:t3("settings.engines.detail.programUnknown",{binary}),fg:theme.textMuted};if(s2.binary.found)return{text:t3("settings.engines.detail.programFound",{binary,path:tildify(s2.binary.path)})};return{text:t3("settings.engines.detail.programMissing",{binary}),fg:theme.warning}}function signInLine(props,t3,theme){let s2=props.status;if(!s2)return{text:props.probing?t3("settings.accounts.checking"):t3("settings.engines.detail.signInUnknown"),fg:theme.textMuted};if(s2.accountError)return{text:t3("settings.engines.detail.signInFailed",{error:s2.accountError}),fg:theme.warning};if(s2.account===null)return{text:t3("settings.engines.detail.signInUnknown"),fg:theme.textMuted};return accountLine(s2.account,t3,theme)}function accountLine(account,t3,theme){if(account.kind==="oauth"){if(!("email"in account))return{text:t3("settings.engines.detail.signedIn")};let who=account.email+(account.billingType?` (${account.billingType})`:"");return{text:t3("settings.engines.detail.signedInAs",{who})}}if(account.kind==="chatgpt"){let who=account.email+(account.plan?` (${account.plan})`:"");return{text:t3("settings.engines.detail.signedInAs",{who})}}if(account.kind==="apikey")return{text:t3("settings.engines.detail.apiKey")};if(account.kind==="token")return{text:t3("settings.engines.detail.token",{source:account.source})};return{text:t3("settings.engines.detail.signedOut"),fg:theme.warning}}function reportingLines(props,t3,theme){let row=props.integration;if(!row)return[];let lines=[];if(row.configIssue)lines.push({text:t3("settings.engines.detail.hooksBlocked",{file:tildify(row.hookFile),reason:row.configIssue}),fg:theme.error});else if(!row.hooksSupported)lines.push({text:t3("settings.engines.detail.hooksUnsupported"),fg:theme.textMuted});else if(row.hookState==="installed")lines.push({text:t3("settings.engines.detail.hooksInstalled")});else if(row.hookState==="outdated")lines.push({text:t3("settings.engines.detail.hooksOutdated"),fg:theme.warning});else if(props.status?.binary.found===!1)lines.push({text:t3("settings.engines.detail.hooksAwaitEngine"),fg:theme.textMuted});else lines.push({text:t3("settings.engines.detail.hooksMissing"),fg:theme.warning});if(lines.push({text:t3(row.markers?"settings.engines.detail.markersYes":"settings.engines.detail.markersNo")}),lines.push({text:t3(row.screen?"settings.engines.detail.screenYes":row.hooksSupported&&row.hookState==="installed"?"settings.engines.detail.screenNotNeeded":"settings.engines.detail.screenNo")}),row.setupCommand)lines.push({text:t3("settings.engines.hookTrustHint",{command:row.setupCommand}),fg:theme.warning});return lines}var NAME_MAX=22;function EngineSettingsSection(props){let{theme}=useTheme(),t3=useT(),addRowIndex=props.vendors.length,isBodyCursor=(row)=>props.level==="body"&&props.bodyRow===row,byVendor=new Map((props.statuses??[]).map((s2)=>[s2.vendor,s2])),integrationByVendor=new Map((props.integrations??[]).map((row)=>[row.vendor,row])),lastFocused=import_react64.useRef(void 0),cursorVendor=props.level==="body"?props.vendors[props.bodyRow]:void 0;if(cursorVendor)lastFocused.current=cursorVendor;let focused=lastFocused.current&&props.vendors.includes(lastFocused.current)?lastFocused.current:props.vendors[0],health=(vendor)=>{let status=byVendor.get(vendor),integration=integrationByVendor.get(vendor);return engineHealth({binaryFound:props.statuses===null?void 0:status?.binary.found??null,login:engineLogin(status),hooks:integration?integration.hooksSupported?integration.hookState:"unsupported":"unsupported",configIssue:integration?.configIssue,commandChosen:props.isCustom(vendor)||props.hasCommandOverride(vendor)})},toneColor3=(tone)=>tone==="ready"?theme.success:tone==="attention"?theme.warning:tone==="error"?theme.error:theme.textMuted,nameText=(vendor)=>props.displayName(vendor),subText=(vendor)=>{let from=props.renamedFrom(vendor);if(from)return` (${from})`;return props.isCustom(vendor)?` (${t3("settings.engines.customTag")})`:""},nameWidth=Math.min(NAME_MAX,props.vendors.reduce((max,v3)=>Math.max(max,displayWidth(nameText(v3)+subText(v3))),0)),rows=props.vendors.map((vendor)=>({vendor,health:health(vendor)})),statusWidth=rows.reduce((max,r6)=>Math.max(max,displayWidth(t3(r6.health.key))),0),pad=(text,width)=>text+" ".repeat(Math.max(0,width-displayWidth(text))),availableLabel=t3("settings.engines.available"),offLabel=t3("settings.engines.off"),markWidth=Math.max(displayWidth(availableLabel),displayWidth(offLabel)),defaultLabel=t3("settings.engines.defaultMark"),present=(vendor)=>byVendor.get(vendor)?.binary.found!==!1,installCount=props.needsHookInstall.filter(present).length,removeCount=props.hooksInstalled.length,hookable=(props.integrations??[]).filter((row)=>row.hooksSupported&&present(row.vendor)),hookTotal=hookable.length,hookCurrent=hookable.filter((row)=>row.hookState==="installed").length,skillable=(props.integrations??[]).filter((row)=>row.skillDir),skillCurrent=skillable.filter((row)=>row.skillState==="installed").length,skillNeeded=skillable.length-skillCurrent;return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes26.BOLD,children:t3("settings.engines.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.engines.hint")}),$jsxs("box",{flexDirection:"column",gap:0,children:[rows.map(({vendor,health:h2},i2)=>{let isCursor=isBodyCursor(i2),enabled=props.isEnabled(vendor),isDefault=props.isDefaultEngine(vendor),on=(idle)=>isCursor?theme.selectedListItemText:idle,name=nameText(vendor),sub=subText(vendor),subFits=displayWidth(name+sub)<=nameWidth?sub:"";return $jsxs("box",{ref:props.rowRef(i2),flexDirection:"row",gap:2,paddingLeft:1,paddingRight:1,overflow:"hidden",backgroundColor:isCursor?theme.primary:void 0,onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(i2),props.editEngine(vendor)},children:[$jsxs("box",{flexDirection:"row",flexShrink:1,overflow:"hidden",children:[$jsx("text",{fg:on(enabled?theme.text:theme.textMuted),attributes:TextAttributes26.BOLD,wrapMode:"none",children:name}),displayWidth(name)<nameWidth||subFits?$jsx("text",{fg:on(theme.textMuted),wrapMode:"none",children:pad(subFits,nameWidth-displayWidth(name))}):null]}),$jsxs("box",{flexDirection:"row",gap:1,flexShrink:0,children:[$jsx("text",{fg:on(toneColor3(h2.tone)),wrapMode:"none",children:"\u25CF"}),$jsx("text",{fg:on(enabled?theme.text:theme.textMuted),wrapMode:"none",children:pad(t3(h2.key),statusWidth)})]}),$jsx("text",{fg:on(enabled?theme.text:theme.textMuted),wrapMode:"none",flexShrink:0,onMouseUp:(evt)=>{evt.stopPropagation(),props.setLevel("body"),props.setBodyRow(i2),props.toggleEngine(vendor)},children:pad(enabled?availableLabel:offLabel,markWidth)}),$jsx("text",{fg:on(isDefault?theme.accent:theme.textMuted),attributes:isDefault?TextAttributes26.BOLD:0,wrapMode:"none",flexShrink:0,onMouseUp:(evt)=>{evt.stopPropagation(),props.setLevel("body"),props.setBodyRow(i2),props.chooseDefault(vendor)},children:pad(isDefault?defaultLabel:"",displayWidth(defaultLabel))})]},vendor)}),$jsx("box",{ref:props.rowRef(addRowIndex),flexDirection:"row",paddingLeft:1,paddingRight:1,backgroundColor:isBodyCursor(addRowIndex)?theme.primary:void 0,onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(addRowIndex),props.onAddEngine()},children:$jsx("text",{fg:isBodyCursor(addRowIndex)?theme.selectedListItemText:theme.primary,wrapMode:"none",children:t3("settings.engines.addEngine")})})]}),focused?$jsx(EngineDetails,{name:props.displayName(focused),status:byVendor.get(focused)??null,probing:props.statuses===null,integration:integrationByVendor.get(focused)??null,commandText:props.commandText(focused),commandIsOwn:props.isCustom(focused)||props.hasCommandOverride(focused),protocol:props.isCustom(focused)?{declared:props.engineProtocol(focused)??null}:void 0}):null,$jsxs("box",{flexDirection:"column",gap:0,children:[$jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes26.BOLD,wrapMode:"none",children:t3("settings.engines.integrations.title")}),props.integrations?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("settings.engines.integrations.summary",{installed:String(hookCurrent),total:String(hookTotal)})}):null]}),$jsx("box",{paddingLeft:1,paddingRight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.engines.integrations.hint")})}),$jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,paddingRight:1,children:[$jsx(IntegrationButton,{rowRef:props.rowRef(addRowIndex+1),cursor:isBodyCursor(addRowIndex+1),live:installCount>0,label:installCount>0?t3("settings.engines.integrations.install",{count:String(installCount)}):t3("settings.engines.integrations.upToDate"),onPress:()=>{props.setLevel("body"),props.setBodyRow(addRowIndex+1),props.onInstallHooks()}}),$jsx(IntegrationButton,{rowRef:props.rowRef(addRowIndex+2),cursor:isBodyCursor(addRowIndex+2),live:removeCount>0,label:removeCount>0?t3("settings.engines.integrations.remove",{count:String(removeCount)}):t3("settings.engines.integrations.noneInstalled"),onPress:()=>{props.setLevel("body"),props.setBodyRow(addRowIndex+2),props.onUninstallHooks()}})]})]}),$jsxs("box",{flexDirection:"column",gap:0,children:[$jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes26.BOLD,wrapMode:"none",children:t3("settings.engines.skill.title")}),props.integrations?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("settings.engines.integrations.summary",{installed:String(skillCurrent),total:String(skillable.length)})}):null]}),$jsx("box",{paddingLeft:1,paddingRight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.engines.skill.hint")})}),$jsx("box",{flexDirection:"row",paddingLeft:1,paddingRight:1,children:$jsx(IntegrationButton,{rowRef:props.rowRef(addRowIndex+3),cursor:isBodyCursor(addRowIndex+3),live:skillNeeded>0,label:skillNeeded>0?t3("settings.engines.skill.install",{count:String(skillNeeded)}):skillable.length>0?t3("settings.engines.integrations.upToDate"):t3("settings.engines.skill.noEngines"),onPress:()=>{props.setLevel("body"),props.setBodyRow(addRowIndex+3),props.onInstallSkill()}})}),props.skillError?$jsx("box",{paddingLeft:1,paddingRight:1,children:$jsx("text",{fg:theme.error,wrapMode:"word",children:t3("settings.engines.skill.failed",{reason:props.skillError})})}):null]}),$jsx("box",{paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.engines.keys")})})]})}function IntegrationButton(props){let{theme}=useTheme();return $jsx("box",{ref:props.rowRef,flexDirection:"row",paddingLeft:1,paddingRight:1,backgroundColor:props.cursor?theme.primary:theme.backgroundElement,onMouseUp:props.onPress,children:$jsx("text",{fg:props.cursor?theme.selectedListItemText:props.live?theme.text:theme.textMuted,wrapMode:"none",children:props.label})})}import{TextAttributes as TextAttributes33}from"@opentui/core";var import_react70=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes32}from"@opentui/core";function appearanceChoiceLabel(choice,t3){switch(choice.kind){case"theme":return choice.value;case"themeMode":return t3({dark:"settings.appearance.modeDark",light:"settings.appearance.modeLight",auto:"settings.appearance.modeAuto"}[choice.value]);case"transparent":return t3(choice.value?"settings.appearance.enabled":"settings.appearance.disabled");case"focusAccent":return t3(`settings.general.accent${choice.value.charAt(0).toUpperCase()}${choice.value.slice(1)}`);case"splitStyle":return t3({box:"settings.general.splitBox",line:"settings.general.splitLine",rail:"settings.general.splitRail",rule:"settings.general.splitRule"}[choice.value]);case"railFold":return t3({glyphs:"settings.general.railFoldGlyphs",initials:"settings.general.railFoldInitials",hairline:"settings.general.railFoldHairline"}[choice.value]);case"workingBorder":return t3(choice.value==="flow"?"settings.appearance.borderFlow":"settings.appearance.borderStill");case"taskColors":return t3(choice.value==="on"?"settings.appearance.enabled":"settings.appearance.disabled");case"glyphSet":return t3({braille:"settings.appearance.glyphsBraille",starburst:"settings.appearance.glyphsStarburst",ascii:"settings.appearance.glyphsAscii"}[choice.value]);case"colorblind":return t3(choice.value==="on"?"settings.appearance.enabled":"settings.appearance.disabled");case"runningTitle":return t3(choice.value==="shimmer"?"settings.appearance.titleShimmer":"settings.appearance.titleStill")}}import{TextAttributes as TextAttributes31}from"@opentui/core";import{TextAttributes as TextAttributes27}from"@opentui/core";var SHIMMER_CELLS_PER_TICK=2.4,SHIMMER_HALF_WIDTH=5,QUIET_CELLS=24,SHIMMER_CREST=0.65,CYCLE_CELLS=Math.round(SPINNER_TICK_CYCLE*SHIMMER_CELLS_PER_TICK);function shimmerLoop(cells){let loop=cells+2*SHIMMER_HALF_WIDTH+QUIET_CELLS;while(CYCLE_CELLS%loop!==0&&loop<CYCLE_CELLS)loop++;return loop}function shimmerIntensity(index,cells,tick3){let loop=shimmerLoop(cells),centre=tick3*SHIMMER_CELLS_PER_TICK%loop-SHIMMER_HALF_WIDTH,dist=Math.abs(index+0.5-centre);if(dist>=SHIMMER_HALF_WIDTH)return 0;return 0.5+0.5*Math.cos(Math.PI*dist/SHIMMER_HALF_WIDTH)}function shimmerInk(muted,accent,intensity){if(intensity<=0)return muted;if(muted.intent!=="rgb"||accent.intent!=="rgb")return intensity>=SHIMMER_CREST?accent:muted;return mixInk(accent,muted,intensity)}function ShimmerLabel(props){let glyphs=[],cells=0;for(let ch of props.label){let width=charWidth(ch.codePointAt(0)??0),last=glyphs[glyphs.length-1];if(width===0&&last)last.text+=ch;else glyphs.push({text:ch,cell:cells,width});cells+=width}return glyphs.map((glyph,i2)=>{let intensity=shimmerIntensity(glyph.cell+(glyph.width-1)/2,cells,props.tick);return $jsx("span",{fg:shimmerInk(props.muted,props.accent,intensity),attributes:intensity>=SHIMMER_CREST?TextAttributes27.BOLD:void 0,children:glyph.text},i2)})}var import_react68=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes30}from"@opentui/core";var RECENT_ROW_ID="~recent",SCRATCH_SECTION_ID="~scratch",ARCHIVED_ROW_ID="~archived";function routinesRowId(projectKey){return`~routines:${projectKey}`}function projectKeyOfRoutinesRow(id){return id.startsWith("~routines:")?id.slice(10):null}function tabRowId(taskId,tabId){return`${taskId}::${tabId}`}function parseRowId(rowId){let at2=rowId.indexOf("::");if(at2<0)return{taskId:rowId,tabId:null};return{taskId:rowId.slice(0,at2),tabId:rowId.slice(at2+2)}}var UNGROUPED_SECTION_LABEL="Ungrouped";function isRoutineTask(task){return task.routine!==void 0}function isClosedDownProject(tasks2,tabsByTask2){let only=tasks2.length===1?tasks2[0]:void 0;if(!only||only.kind!=="main"&&only.kind!=="dir")return!1;return tabsByTask2.get(only.id)?.length===0}function idleMainIds(input,tasks2){let parents=new Set;for(let task of tasks2)if(task.parentTaskId!==void 0&&task.routine===void 0)parents.add(task.parentTaskId);let idle=new Set;for(let task of tasks2){if(task.kind!=="main"||input.keepTaskIds?.has(task.id)||parents.has(task.id))continue;let tabs=input.tabsByTask.get(task.id),local=(task.origin?.machineId??"local")==="local";if(tabs?tabs.length===0:local&&input.tabsDaemonBacked===!0)idle.add(task.id)}return idle}function isListed(task){let phase=task.deletion?.phase;return phase!=="queued"&&phase!=="running"}function archivedTasks(tasks2){return tasks2.filter((task)=>task.archived===!0&&isListed(task))}function buildSidebarGroups(input){let tasks2=input.tasks.filter((task)=>isListed(task)&&task.archived!==!0),{tabsByTask:tabsByTask2}=input,sortMode=input.sortMode??"default",compare=sortMode==="recent"?compareNewest:sortMode==="attention"?compareTaskGroup(input.activityOf??(()=>{return})):sortMode==="name"?compareName:null,scratchTasks=tasks2.filter(isNoProjectTask);if(compare)scratchTasks.sort(compare);let keyOf=sidebarProjectKeyResolver(tasks2),byProject=new Map;for(let task of tasks2){if(isNoProjectTask(task))continue;let key=keyOf(task),entry2=byProject.get(key)??{repo:task.repo,machineId:task.origin?.machineId??"local",homeMain:!1,mains:[],rest:[]};if(!entry2.repoId&&task.repoId)entry2.repoId=task.repoId;if(sidebarProjectKeyOfTask(task)===key&&!entry2.homeMain){if(entry2.repo=task.repo,entry2.machineId=task.origin?.machineId??"local",entry2.homeMain=task.kind==="main",entry2.homeMain){entry2.mains.unshift(task),byProject.set(key,entry2);continue}}if(task.kind==="main")entry2.mains.push(task);else entry2.rest.push(task);byProject.set(key,entry2)}let orderedKeys=[],seen=new Set;for(let task of tasks2){if(task.kind!=="main")continue;let key=keyOf(task);if(!seen.has(key))seen.add(key),orderedKeys.push(key)}for(let key of byProject.keys())if(!seen.has(key))seen.add(key),orderedKeys.push(key);let ordered=new Map;for(let[key,entry2]of byProject){if(compare)entry2.rest.sort(compare);ordered.set(key,[...entry2.mains,...entry2.rest])}let idle=idleMainIds(input,tasks2),visibleKeys=orderedKeys.filter((key)=>{let list=ordered.get(key);return list?!isClosedDownProject(list,tabsByTask2):!1}),labelled=new Map;for(let key of visibleKeys){let entry2=byProject.get(key);if(entry2)labelled.set(key,{repo:entry2.repo,...entry2.repoId?{repoId:entry2.repoId}:{}})}let projects=[...labelled.values()],groups=[];if(scratchTasks.length>0){let own=scratchTasks.filter((task)=>!isRoutineTask(task)),routines=scratchTasks.filter(isRoutineTask);groups.push({key:SCRATCH_SECTION_ID,repo:"",label:UNGROUPED_SECTION_LABEL,machineId:"local",tasks:[...own,...routines],routineCount:routines.length})}for(let key of visibleKeys){let entry2=byProject.get(key),list=ordered.get(key),project=labelled.get(key);if(!entry2||!list||!project)continue;let kept=list.filter((task)=>!idle.has(task.id)),shown=kept.length>0?kept:list,own=shown.filter((task)=>!isRoutineTask(task)),routines=shown.filter(isRoutineTask);groups.push({key,repo:entry2.repo,label:sidebarRepoLabel(project,projects),machineId:entry2.machineId,tasks:[...own,...routines],routineCount:routines.length})}return groups}function ownTasks(group){return group.tasks.slice(0,group.tasks.length-group.routineCount)}function rowHaystacks(row,liveBranch){if(row.kind==="project")return[row.label];if(row.kind==="routines"||row.kind==="archived")return[];let task=row.task,title=task.kind==="dir"?"":task.title,liveBranchName=liveBranch?.(task),liveTitle=row.kind==="worktree"?row.title:void 0;return[worktreeRowLabel(task,{liveBranch:liveBranchName,liveTitle}),liveBranchName||task.branch,title,repoBasename(task.repo)]}function matchesRow(query,row,liveBranch){return rowHaystacks(row,liveBranch).some((field)=>field!==""&&fuzzyMatch(query,field))}function filterTreeRows(rows,query,liveBranch){let q2=query.trim();if(q2==="")return[...rows];let projectOf=new Map,taskRows=new Map,header=null;for(let row of rows){if(row.kind==="project")header=row.id;else if(header!==null)projectOf.set(row.id,header);if(row.kind==="worktree")taskRows.set(row.id,row)}let parentRowId=(row)=>{let parent=row.kind==="worktree"?row.task.parentTaskId:void 0;return parent!==void 0&&taskRows.has(parent)?parent:void 0},selfMatch=new Set,keep=new Set;for(let row of rows){if(!matchesRow(q2,row,liveBranch))continue;if(selfMatch.add(row.id),keep.add(row.id),row.kind==="project"||row.kind==="routines"||row.kind==="archived")continue;let project=projectOf.get(row.id);if(project!==void 0)keep.add(project);for(let up=parentRowId(row);up!==void 0&&!keep.has(up);){keep.add(up);let parentRow=taskRows.get(up);up=parentRow?parentRowId(parentRow):void 0}}let underMatchedParent=(row)=>{let seen=new Set;for(let up=parentRowId(row);up!==void 0&&!seen.has(up);){if(selfMatch.has(up))return!0;seen.add(up);let parentRow=taskRows.get(up);up=parentRow?parentRowId(parentRow):void 0}return!1},out=[];for(let row of rows){if(row.kind==="project"){if(keep.has(row.id))out.push(row);continue}if(row.kind==="routines"||row.kind==="archived")continue;let project=projectOf.get(row.id);if(project!==void 0&&selfMatch.has(project)||keep.has(row.id)||underMatchedParent(row))out.push(row)}return out}function tabRowActivity(args){return args.tabActivities?.get(args.tabId)}function withRecentRow(rows,recent){if(!recent)return[...rows];return[{kind:"recent",id:RECENT_ROW_ID,task:recent,depth:1},...rows]}var MAX_TREE_DEPTH=3,AUTO_FOLD_CHILDREN=5;function childMarkerOf(task){if(task.parentTaskId===void 0)return null;return isSharedChild(task)?"shared":"worktree"}function loopsBack(task,byId){let seen=new Set([task.id]);for(let at2=task.parentTaskId;at2!==void 0;at2=byId.get(at2)?.parentTaskId){if(seen.has(at2))return at2===task.id;seen.add(at2)}return!1}function indexChildren(groups){let byId=new Map;for(let group of groups)for(let task of group.tasks)byId.set(task.id,task);let children=new Map,nested=new Set;for(let task of byId.values()){let parent=task.parentTaskId;if(parent===void 0||task.routine!==void 0||!byId.has(parent)||loopsBack(task,byId))continue;nested.add(task.id);let siblings=children.get(parent);if(siblings)siblings.push(task);else children.set(parent,[task])}return{children,nested}}function descendantIds(children,id,out=[]){for(let child of children.get(id)??[])out.push(child.id),descendantIds(children,child.id,out);return out}function isFolded(id,childCount,descendants,ctx){if(ctx.collapsed?.has(id))return!0;if(ctx.opened?.has(id)||childCount<=AUTO_FOLD_CHILDREN)return!1;return ctx.selectedId===void 0||!descendants.includes(ctx.selectedId)}function pushTask(rows,task,generation,ctx){let kids=ctx.children.get(task.id),ids=kids?descendantIds(ctx.children,task.id):[],collapsed=kids!==void 0&&ctx.collapsed!==void 0&&isFolded(task.id,kids.length,ids,ctx),level=generation+1,title=ctx.titles?.get(task.id);if(rows.push({kind:"worktree",id:task.id,task,depth:Math.min(level,MAX_TREE_DEPTH),...level>MAX_TREE_DEPTH?{level}:{},...kids?{fold:{count:ids.length,collapsed,descendantIds:ids}}:{},...title?{title}:{}}),collapsed||!kids)return;for(let child of kids)pushTask(rows,child,generation+1,ctx)}function buildRowsFromGroups(input){let ctx={...indexChildren(input.groups),collapsed:input.collapsedTasks,opened:input.openedTasks,selectedId:input.selectedTaskId,titles:input.conversationTitles},rows=[];for(let group of input.groups){let ownCount=group.tasks.length-group.routineCount,top=ownTasks(group).filter((task)=>!ctx.nested.has(task.id));if(top.length===0&&group.routineCount===0)continue;rows.push({kind:"project",id:group.key,repo:group.repo,label:group.label,machineId:group.machineId,depth:0});for(let task of top)pushTask(rows,task,0,ctx);if(group.routineCount>0){let expanded=input.expandedRoutines?.has(group.key)===!0,routines=group.tasks.slice(ownCount);if(rows.push({kind:"routines",id:routinesRowId(group.key),projectKey:group.key,count:group.routineCount,tasks:routines,expanded,depth:1}),expanded)for(let task of routines)pushTask(rows,task,0,ctx)}}return pushArchived(rows,input),rows}function pushArchived(rows,input){let archived=input.archived??[];if(archived.length===0)return;let expanded=input.archivedExpanded===!0;if(rows.push({kind:"archived",id:ARCHIVED_ROW_ID,count:archived.length,expanded,depth:0}),!expanded)return;let ctx={...indexChildren([{key:ARCHIVED_ROW_ID,repo:"",label:"",machineId:"local",tasks:archived,routineCount:0}]),collapsed:input.collapsedTasks,opened:input.openedTasks,selectedId:input.selectedTaskId,titles:input.conversationTitles};for(let task of archived)if(!ctx.nested.has(task.id))pushTask(rows,task,0,ctx)}function treeFlatIds(rows){let ids=[];for(let row of rows)if(row.kind!=="project")ids.push(row.id);return ids}function mainTaskIdOfProject(tasks2,projectKey){for(let task of tasks2){if(task.kind!=="main")continue;if(sidebarProjectKeyOfTask(task)===projectKey)return String(task.id)}return null}var import_react65=__toESM(require_react_production(),1);var EMPTY={},rowStatusCell=createStateCell(EMPTY,"row.status"),transport2=null,rev=-1,local=EMPTY,remote=EMPTY,viewing;function publish2(){let prev=rowStatusCell.get(),next={};for(let[taskId,status]of Object.entries(remote))if(!(taskId in local))next[taskId]=status;for(let[taskId,status]of Object.entries(local))next[taskId]=status;let changed=Object.keys(prev).length!==Object.keys(next).length;for(let[taskId,status]of Object.entries(next)){let old=prev[taskId];if(old!==void 0&&JSON.stringify(old)===JSON.stringify(status))next[taskId]=old;else changed=!0}if(changed)rowStatusCell.set(next)}function acceptRowStatus(payload,force=!1){if(!force&&payload.rev<rev)return;rev=payload.rev,local=payload.tasks,publish2()}function remoteRowStatus(activity,tabActivity){let out={};for(let taskId of new Set([...activity.keys(),...tabActivity?.keys()??[]])){let tabs={};for(let[tabId,entry3]of tabActivity?.get(taskId)??[])tabs[tabId]=tabStatus({activity:{state:entry3.state,at:entry3.at},viewed:!1});let entry2=activity.get(taskId),tabless=entry2&&Object.keys(tabs).length===0?tabStatus({activity:{state:entry2.state,at:entry2.at},viewed:!1}):void 0;out[taskId]={task:taskStatus(tabs,tabless?{tabless}:{}),tabs}}return out}function acceptRemoteActivity(activity,tabActivity){remote=remoteRowStatus(activity,tabActivity),publish2()}function followRemoteActivity(live){let take=()=>{let{activity,tabActivity}=live.get();acceptRemoteActivity(activity,tabActivity)};take();let off=live.subscribe(take);return()=>{off(),acceptRemoteActivity(new Map)}}function taskRowStatus(map,taskId){return map[taskId]?.task}function tabRowStatus(map,taskId,tabId){return map[taskId]?.tabs[tabId]}var read=()=>rowStatusCell.get();function useRowStatusMap(){return import_react65.useSyncExternalStore(rowStatusCell.subscribe,read,read)}function useTaskRowStatus(taskId){let pick=()=>taskRowStatus(rowStatusCell.get(),taskId);return import_react65.useSyncExternalStore(rowStatusCell.subscribe,pick,pick)}function useTabRowStatus(taskId,tabId){let pick=()=>tabRowStatus(rowStatusCell.get(),taskId,tabId);return import_react65.useSyncExternalStore(rowStatusCell.subscribe,pick,pick)}function sendViewing(){if(!transport2||viewing===void 0)return;transport2.viewing(viewing.taskId,viewing.tabId).catch((err)=>logClientError("row-status",err))}function reportViewing(taskId,tabId){let next={taskId,tabId:taskId===null?null:tabId};if(viewing&&viewing.taskId===next.taskId&&viewing.tabId===next.tabId)return;viewing=next,sendViewing()}function reportAnswered(taskId,tabId){transport2?.answered(taskId,tabId).catch((err)=>logClientError("row-status",err))}function noteAnswerInput(data,taskId,tabId){if(data!=="\r"&&!data.endsWith("\r"))return;if(tabRowStatus(rowStatusCell.get(),taskId,tabId)?.kind!=="needs-input")return;reportAnswered(taskId,tabId)}async function reloadRowStatus(){let current2=transport2;if(!current2)return;sendViewing();try{acceptRowStatus(await current2.list(),!0)}catch(err){logClientError("row-status",err)}}function attachRowStatusTransport(next){if(transport2=next,rev=-1,!next)return()=>{};let off=next.onChanged((payload)=>acceptRowStatus(payload));return reloadRowStatus(),()=>{if(off(),transport2===next)transport2=null}}function useRowStatusSync(channel,connection){import_react65.useEffect(()=>{if(!channel)return;let detach=attachRowStatusTransport(channel),last=connection(),off=connection.subscribe(()=>{let now=connection();if(now==="online"&&last!=="online")reloadRowStatus();last=now});return()=>{off(),detach()}},[channel,connection])}function useViewingReport(taskId,tabId){import_react65.useEffect(()=>{reportViewing(taskId,tabId)},[taskId,tabId]),import_react65.useEffect(()=>()=>reportViewing(null,null),[])}import{TextAttributes as TextAttributes28}from"@opentui/core";function CollapseButton(props){let{theme}=useTheme(),onMouseUp=(evt)=>{evt.stopPropagation(),props.onToggle()},glyph=$jsx("text",{fg:theme.textMuted,attributes:TextAttributes28.BOLD,wrapMode:"none",children:props.collapsed?"\u203A\u203A":"\u2039\u2039"});if(props.inline)return $jsx("box",{flexShrink:0,onMouseUp,children:glyph});return $jsx("box",{position:"absolute",bottom:0,right:1,flexShrink:0,onMouseUp,children:glyph})}var import_react67=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes29}from"@opentui/core";import{stat}from"fs/promises";import{join as join2}from"path";var BRANCH_POLL_TIMEOUT_MS=2000,BRANCH_SLOW_RETRY_MS=30000,BRANCH_MIN_POLL_INTERVAL_MS=1500,headCache=new Map;async function headFingerprint(repo){try{let st2=await stat(join2(repo,".git","HEAD"));return`${st2.mtimeMs}:${st2.size}`}catch{return null}}async function resolveBranchHead(repo,signal,spawn3=spawnCapture){let fingerprint=await headFingerprint(repo);if(fingerprint!==null){let cached=headCache.get(repo);if(cached&&cached.fingerprint===fingerprint)return cached.value}let value="",resolved=!1;recordSpawn("sidebar.gitHead",["git","symbolic-ref","--short","HEAD"],repo);let ref=await spawn3("git",["symbolic-ref","--short","HEAD"],{cwd:repo,env:readOnlyGitProcessEnv(),signal}),name=ref.status===0?ref.stdout.trim():"";if(name&&name!=="HEAD")value=name,resolved=!0;else if((await spawn3("git",["rev-parse","--verify","HEAD"],{cwd:repo,env:readOnlyGitProcessEnv(),signal})).status===0)value="(detached)",resolved=!0;if(resolved&&fingerprint!==null)headCache.set(repo,{fingerprint,value});return value}var poller2=createBackgroundPoller({initial:"",timeoutMs:BRANCH_POLL_TIMEOUT_MS,slowRetryMs:BRANCH_SLOW_RETRY_MS,minIntervalMs:BRANCH_MIN_POLL_INTERVAL_MS,run:(repo,signal)=>resolveBranchHead(repo,signal)});function currentBranch(repo){return poller2.read(repo)}function pollCurrentBranch(repo){poller2.poll(repo)}function machineStateKey(state){switch(state){case"online":return null;case"connecting":return"tasks.machine.connecting";case"unsupported":return"tasks.machine.unsupported";case"mismatch":return"tasks.machine.mismatch";default:return"tasks.machine.offline"}}function remoteRowCaption(mark,t3){let where=t3("tasks.machine.runsOn",{host:mark.host}),word=machineStateKey(mark.state);if(word)return`${where} \xB7 ${t3(word)}`;return mark.version?`${where} \xB7 v${mark.version}`:where}function remoteMarkLive(mark){return mark.state==="online"}function applyMachineLayer(rows,machines){if(machines.length===0)return rows;let byAlias=new Map(machines.map((entry2)=>[entry2.alias,entry2])),kept=[],header=-1,dropped=!1,closeHeader=()=>{if(header>=0&&dropped&&header===kept.length-1)kept.pop()};for(let row of rows){if(row.kind==="project"){closeHeader(),header=kept.length,dropped=!1,kept.push(row);continue}if(row.kind==="routines"||row.kind==="recent"||row.kind==="archived"){kept.push(row);continue}let alias=row.task.origin?.machineId??"local";if(alias==="local"){kept.push(row);continue}let entry2=byAlias.get(alias);if(!entry2){dropped=!0;continue}kept.push({...row,remote:{host:entry2.hostLabel||row.task.origin?.hostLabel||alias,state:entry2.state,...entry2.version?{version:entry2.version}:{}}})}return closeHeader(),kept}var import_react66=__toESM(require_react_production(),1);var NO_SUBSCRIBE=()=>()=>{};function mostUrgentStatus(map,taskIds){let children={};for(let id of taskIds){let status=taskRowStatus(map,id);if(status)children[id]={...status,alive:!0,restored:!1,tracked:!0}}return Object.keys(children).length===0?void 0:taskStatus(children)}function useMostUrgentStatus(taskIds,enabled){let read2=()=>{let status=enabled?mostUrgentStatus(rowStatusCell.get(),taskIds):void 0;return status?`${status.kind}|${status.reason??""}`:""},key=import_react66.useSyncExternalStore(enabled?rowStatusCell.subscribe:NO_SUBSCRIBE,read2,read2);return import_react66.useMemo(()=>{if(key==="")return;let[kind,reason]=key.split("|");return{kind,since:0,...reason?{reason}:{}}},[key])}import{MouseButton as MouseButton2}from"@opentui/core";var indentOf=(depth)=>depth>0?" ".repeat(1+(depth-1)*2):"";function treeLabelBudget(shared2,reserved){let width=shared2.width??SIDEBAR_WIDTH;return Math.max(6,width-3-reserved)}function clusterCells(text){let cells=1;for(let ch of text)cells+=charWidth(ch.codePointAt(0)??0);return cells}function MoveChip(props){let{theme}=useTheme(),t3=useT();if(props.shared.movingRowId!==props.rowId)return null;return $jsx("text",{fg:theme.info,wrapMode:"none",flexShrink:0,children:t3("tasks.moveChip").trim()})}function RowShell(props){let{theme}=useTheme(),shared2=props.shared,selection=resolveRowSelectionChrome2(theme,{cursor:shared2.cursorIndex===props.flatIndex,selected:shared2.activeRowId===props.rowId});return $jsxs("box",{ref:(renderable)=>{if(!renderable)return;return shared2.rowEls.set(props.flatIndex,renderable),()=>{if(shared2.rowEls.get(props.flatIndex)===renderable)shared2.rowEls.delete(props.flatIndex)}},width:"100%",flexDirection:"row",gap:0,backgroundColor:selection.backgroundColor,onMouseUp:(evt)=>{if(evt.stopPropagation(),evt.button===MouseButton2.RIGHT&&shared2.onContextMenu){shared2.onContextMenu(props.flatIndex,props.rowId,evt.x,evt.y);return}shared2.onPress(props.flatIndex,props.rowId)},children:[$jsx("text",{fg:selection.markerColor,wrapMode:"none",children:selection.marker}),props.depth>0?$jsx("text",{wrapMode:"none",flexShrink:0,children:indentOf(props.depth)}):null,props.children]})}var REMOTE_TITLE_CELLS=12,SHARED_MARK="\u2442",WORKTREE_MARK="\u2387",FOLD_OPEN="\u25BE",FOLD_CLOSED="\u25B8";function statusAgeLabel(status){if(!status||status.since<=0)return null;if(status.kind!=="running"&&status.kind!=="attention"&&status.kind!=="needs-input")return null;return relativeAge(status.since)}function conversationActivity(task,tabStates){let alias=task.ptyAlias,tabs=tabStates?.get(alias?.taskId??task.id);if(!tabs)return;if(alias)return tabRowActivity({tabId:alias.tabId,tabActivities:tabs});let latest;for(let activity of tabs.values())if(!latest||activity.at>latest.at)latest=activity;return latest}function useStateCell(args){let{theme}=useTheme(),baseView=useTabRowBaseView({task:args.task,status:args.status,lifecycle:args.lifecycle}),frame2=useSpinnerFrame(baseView.loading),rowView=withSpinnerFrame(baseView,()=>frame2),pulsing=useDonePulse(completionStampOf(args.activity)),fg=pulsing?theme.success:rowView.loading&&rowView.tone==="primary"?breathColor(theme.primary,theme.textMuted,frame2):toneColor2(theme,rowView.tone);return{rowView,fg,pulsing,frame:frame2}}function useTaskStateCell(task,shared2){let alias=task.ptyAlias,rollup=useTaskRowStatus(task.id),aliased=useTabRowStatus(alias?.taskId??task.id,alias?.tabId??""),status=alias&&rollup?.kind!=="busy"?aliased:rollup,cell=useStateCell({task,status,lifecycle:shared2.engineLifecycle?.get(task.id),activity:conversationActivity(task,shared2.engineTabState)});return{status,...cell}}function FoldCluster(props){let{theme}=useTheme(),glyphs=useGlyphs(),{fold}=props,urgent=useMostUrgentStatus(fold.descendantIds,fold.collapsed),mark=rowStatusGlyph(urgent,glyphs),frame2=useSpinnerFrame(fold.collapsed&&mark.spinning);return $jsxs("box",{flexDirection:"row",gap:1,flexShrink:0,onMouseUp:(evt)=>{evt.stopPropagation(),props.shared.onToggleFold?.(props.task.id)},children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:fold.collapsed?FOLD_CLOSED:FOLD_OPEN}),fold.collapsed?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:String(fold.count)}):null,fold.collapsed&&urgent?$jsx("text",{fg:toneColor2(theme,sidebarTone(mark.tone)),wrapMode:"none",children:mark.spinning?breathGlyph(glyphs.spinner,frame2):mark.glyph}):null]})}function WorktreeTreeRow(props){let{theme}=useTheme(),t3=useT(),glyphs=useGlyphs(),kv=useOptionalKV(),shared2=props.shared,task=props.task,chip=sidebarPrChip(task,glyphs),livePath=rowLiveBranchPath(task);usePollOnClock(livePath,pollCurrentBranch);let label=worktreeRowLabel(task,{liveTitle:props.title,...livePath?{liveBranch:currentBranch(livePath)}:{}}),moving=shared2.movingRowId===props.rowId,{status,rowView,fg,pulsing,frame:frame2}=useTaskStateCell(task,shared2),age=statusAgeLabel(status);useClockTick(age!==null);let deletionPhase=task.deletion?.phase,deleting=deletionPhase==="queued"||deletionPhase==="running",deleteFailed=deletionPhase==="error",checkoutPercent=status?.kind==="busy"&&status.reason==="job"?shared2.taskJobs?.get(task.id)?.progress:void 0,checkoutText=checkoutPercent===void 0?null:`${checkoutPercent}%`,deletionWord=deleting||deleteFailed?t3(deleteFailed?"tasks.subtitle.deleteFailed":"tasks.subtitle.deleting"):null;useClockTick((shared2.rowTokens?.get(task.id)?.length??0)>0);let tokens=liveRowTokens(shared2.rowTokens,task.id,Date.now()),remote2=props.remote,remoteLive=remote2?remoteMarkLive(remote2):!0,caption=remote2&&shared2.cursorIndex===props.flatIndex?remoteRowCaption(remote2,t3):null,marker=childMarkerOf(task),extraRepoText=task.extraRepos?.length?`+${task.extraRepos.length}`:null,fold=props.fold,reserved=2+2*((props.depth??1)-1)+tokens.reduce((cells,token)=>cells+clusterCells(token.text),0)+(deletionWord?clusterCells(deletionWord):0)+(checkoutText?clusterCells(checkoutText):0)+(age?clusterCells(age):0)+(props.level!==void 0?clusterCells(String(props.level)):0)+(marker?clusterCells(SHARED_MARK):0)+(extraRepoText?clusterCells(extraRepoText):0)+(fold?clusterCells(fold.collapsed?FOLD_CLOSED:FOLD_OPEN)+(fold.collapsed?clusterCells(String(fold.count))+clusterCells(glyphs.idle):0):0)+(remote2?clusterCells(glyphs.remote):0)+(task.pinned===!0?2:0)+(chip?2:0)+(moving?clusterCells(t3("tasks.moveChip").trim()):0),budget=treeLabelBudget(shared2,reserved),captionCells=caption?Math.max(0,budget-Math.min(displayWidth(label),REMOTE_TITLE_CELLS)-1):0,remoteText=remote2?captionCells>2?`${glyphs.remote} ${truncateEndCells(caption??"",captionCells,charWidth)}`:glyphs.remote:null,shimmer=rowView.loading&&!pulsing&&normalizeRunningTitle(kv?.get(RUNNING_TITLE_KEY,DEFAULT_RUNNING_TITLE))==="shimmer",clipped=truncateEndCells(label,budget-(remoteText?displayWidth(remoteText)-1:0),charWidth);return $jsxs(RowShell,{rowId:props.rowId,flatIndex:props.flatIndex,depth:props.depth??1,shared:shared2,children:[$jsx("text",{fg,attributes:pulsing?TextAttributes29.BOLD:void 0,wrapMode:"none",width:2,flexShrink:0,children:`${rowView.stateGlyph} `}),$jsxs("box",{flexDirection:"row",flexGrow:1,paddingRight:1,gap:1,children:[$jsx("text",{fg:task.origin?.stale||!remoteLive?theme.textMuted:theme.text,attributes:pulsing?TextAttributes29.BOLD:void 0,wrapMode:"none",flexBasis:0,flexGrow:1,flexShrink:1,children:shimmer?$jsx(ShimmerLabel,{label:clipped,tick:frame2,muted:theme.textMuted,accent:theme.primary}):clipped}),task.pinned===!0?$jsx("text",{fg:theme.warning,wrapMode:"none",flexShrink:0,children:"\u25B4"}):null,chip?$jsx("text",{fg:toneColor2(theme,chip.tone),wrapMode:"none",flexShrink:0,children:chip.glyph}):null,tokens.map((token)=>$jsx("text",{fg:token.tone?toneColor2(theme,rowTokenTone(token.tone)):theme.textMuted,wrapMode:"none",flexShrink:0,children:token.text},`${token.source}\x00${token.key}`)),deletionWord?$jsx("text",{fg:deleteFailed?theme.error:theme.textMuted,wrapMode:"none",flexShrink:0,children:deletionWord}):null,$jsx(MoveChip,{rowId:props.rowId,shared:shared2}),checkoutText?$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:checkoutText}):null,age?$jsx("text",{fg:theme.textMuted,attributes:TextAttributes29.DIM,wrapMode:"none",flexShrink:0,children:age}):null,props.level!==void 0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:String(props.level)}):null,extraRepoText?$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:extraRepoText}):null,marker?$jsx("text",{fg:marker==="shared"?theme.info:theme.textMuted,wrapMode:"none",flexShrink:0,children:marker==="shared"?SHARED_MARK:WORKTREE_MARK}):null,fold?$jsx(FoldCluster,{task,fold,shared:shared2}):null,remoteText?$jsx("text",{fg:remoteLive?theme.textMuted:theme.warning,wrapMode:"none",flexShrink:0,children:remoteText}):null]})]})}function useTabRowBaseView(args){let t3=useT(),glyphs=useGlyphs(),{task,status,lifecycle}=args;return import_react67.useMemo(()=>{return buildSidebarRowView({task,status,lifecycle,spinnerFrame:0,subtitleBudget:0,truncateBranch:truncateBranchLabel,glyphs})},[task,status,lifecycle,t3,glyphs])}function RecentJumpRow(props){let{theme}=useTheme(),t3=useT();return $jsxs(RowShell,{rowId:props.rowId,flatIndex:props.flatIndex,depth:1,shared:props.shared,children:[$jsx("text",{fg:theme.accent,wrapMode:"none",width:2,flexShrink:0,children:"\u21A9 "}),$jsx("text",{fg:theme.text,wrapMode:"none",flexShrink:1,children:t3("tasks.recentJump",{title:props.task.title})})]})}var DEFAULT_COLLAPSED_RAIL_STYLE="glyphs",COLLAPSED_RAIL_STYLES=["glyphs","initials","hairline"],COLLAPSED_RAIL_WIDTH={hairline:2,glyphs:4,initials:7};function railInitials(title){let words=title.trim().split(/[\s_\-/.]+/).filter(Boolean);if(words.length===0)return"\xB7\xB7";if(words.length===1)return words[0].slice(0,2).padEnd(2," ");return`${words[0][0]??""}${words[1][0]??""}`}function useRailSections(props){let treeRows=import_react68.useMemo(()=>buildRowsFromGroups({groups:props.groups}),[props.groups]),tasks2=import_react68.useMemo(()=>treeRows.flatMap((row)=>row.kind==="worktree"?[row.task]:[]),[treeRows]),statuses=useRowStatusMap(),spinning=tasks2.some((task)=>rowIsLoading(taskRowStatus(statuses,task.id))),frame2=useSpinnerFrame(spinning),glyphs=useGlyphs(),sections=[];for(let row of treeRows){if(row.kind==="project"){sections.push({key:row.id,label:row.label,rows:[]});continue}if(row.kind!=="worktree")continue;let base=buildSidebarRowView({task:row.task,status:taskRowStatus(statuses,row.task.id),spinnerFrame:frame2,subtitleBudget:0,truncateBranch:(branch)=>branch,glyphs}),view=withSpinnerFrame(base,()=>frame2);sections[sections.length-1]?.rows.push({task:row.task,glyph:view.stateGlyph,tone:view.tone,breath:spinning&&view.loading?frame2:void 0,selected:row.task.id===props.selectedId,depth:row.depth,marker:childMarkerOf(row.task)})}return sections}function projectHeading(label,width){let initial=(new Intl.Segmenter().segment(label.trim()).containing(0)?.segment??"\xB7").toLowerCase(),cells=displayWidth(initial),head=cells>0&&cells<=width?initial:"\xB7";return head+"\u2500".repeat(width-displayWidth(head))}function CollapsedRail(props){let{theme}=useTheme(),sections=useRailSections(props),width=COLLAPSED_RAIL_WIDTH[props.style];return $jsxs("box",{width,flexShrink:0,flexDirection:"column",backgroundColor:theme.backgroundPanel,children:[sections.map((section)=>$jsxs(import_react68.Fragment,{children:[$jsx("text",{fg:theme.textMuted,attributes:TextAttributes30.BOLD,wrapMode:"none",flexShrink:0,children:projectHeading(section.label,width)}),section.rows.map((row)=>$jsx(RailRowView,{row,style:props.style,onSelect:props.onSelect},row.task.id))]},section.key)),$jsx(CollapseButton,{collapsed:!0,onToggle:props.onExpand})]})}function RailRowView(props){let{theme}=useTheme(),{row}=props,fg=row.breath!==void 0&&row.tone==="primary"?breathColor(theme.primary,theme.textMuted,row.breath):toneColor2(theme,row.tone),chrome=resolveRowSelectionChrome2(theme,{cursor:row.selected});return $jsxs("box",{flexShrink:0,flexDirection:"row",backgroundColor:chrome.backgroundColor,onMouseUp:()=>props.onSelect(row.task.id),children:[props.style==="hairline"?null:$jsx("text",{fg:chrome.markerColor??fg,wrapMode:"none",flexShrink:0,children:row.selected?chrome.marker:" "}),$jsx(RailCell,{row,style:props.style,fg})]})}function RailCell(props){let{theme}=useTheme(),{row,fg}=props,bold=row.selected?TextAttributes30.BOLD:void 0,indent=" ".repeat(Math.min(row.depth-1,props.style==="initials"?2:1)),mark=row.marker?$jsx("text",{fg:row.marker==="shared"?theme.info:theme.textMuted,wrapMode:"none",flexShrink:0,children:row.marker==="shared"?SHARED_MARK:WORKTREE_MARK}):null;switch(props.style){case"hairline":return $jsx("text",{fg,wrapMode:"none",children:row.selected?"\u2588 ":"\u258E "});case"glyphs":return $jsxs("box",{flexDirection:"row",flexShrink:0,children:[$jsx("text",{fg,attributes:bold,wrapMode:"none",flexShrink:0,children:`${indent}${row.glyph}`}),mark,$jsx("text",{wrapMode:"none",flexShrink:0,children:" ".repeat(Math.max(0,2-indent.length-(mark?1:0)))})]});default:return $jsxs("box",{flexDirection:"row",flexShrink:0,children:[$jsx("text",{fg,wrapMode:"none",flexShrink:0,children:`${indent}${row.glyph}${mark?"":" "}`}),mark,$jsx("text",{fg:row.selected?theme.text:theme.textMuted,attributes:bold,wrapMode:"none",flexShrink:0,children:railInitials(row.task.title??"")})]})}}import{RGBA as RGBA3}from"@opentui/core";var TITLE_LABEL_CELLS=32,UNFOCUSED_SHARE=0.55,CLEAR=RGBA3.fromInts(0,0,0,0);function runningPaneFlow(accent,inactive,focused,tick3,partnerDeg){let ramp=flowPalette(accent,partnerDeg),palette=focused?ramp:ramp.map((ink)=>mixInk(ink,inactive,UNFOCUSED_SHARE));return function(buffer){let cells=perimeter(this.width,this.height),{char,attributes}=buffer.buffers;cells.forEach(([dx,dy],index)=>{let x2=this.x+dx,y3=this.y+dy;if(x2<0||y3<0||x2>=buffer.width||y3>=buffer.height)return;let cell=y3*buffer.width+x2,code=char[cell]??0;if(code<=32||code>1114111)return;let ink=flowInk(palette,flowPhase(index,cells.length,tick3));if(!ink)return;buffer.setCellWithAlphaBlending(x2,y3,String.fromCodePoint(code),ink,CLEAR,attributes[cell]??0)})}}function runningPaneTitle(label,word){return` ${truncateEndCells(label,TITLE_LABEL_CELLS,charWidth)} \xB7 ${word} `}function AppearancePreview(props){let{current:current2}=props,theme=useTheme().preview(current2),t3=useT(),size=useTerminalSize(),narrow=size.width<75,short=size.height<30,fold=current2.railFoldStyle,{spinner,done,idle}=GLYPH_SETS[current2.glyphSet],tick3=useSpinnerFrame(!0),working=breathGlyph(spinner,tick3),workingInk=breathColor(theme.primary,theme.textMuted,tick3),folded=[{id:"ui",label:{glyphs:`\u258C${working}`,initials:`\u258C${working} UI`,hairline:"\u2588"}[fold]},{id:"api",label:{glyphs:` ${done}`,initials:` ${done} API`,hairline:"\u258E"}[fold]},{id:"review",label:{glyphs:` ${idle}`,initials:` ${idle} QA`,hairline:"\u258E"}[fold]}],marked=current2.taskColors==="on",flowing=current2.workingBorder==="flow",workingTaskInk=marked?taskColor("preview-ui",theme):void 0,inks=diffInks(theme,current2.colorblind==="on"),pane=(divider,edge,name,nameInk)=>paneBoxProps(paneChrome(current2.splitStyle,divider),{edge,name,nameInk}),namesOnRule=paneChrome(current2.splitStyle,void 0).nameOnRule,tasksInk=theme.textMuted;return $jsxs("box",{flexDirection:"column",flexShrink:0,border:!0,borderColor:theme.border,backgroundColor:theme.background,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1,backgroundColor:theme.backgroundPanel,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes31.BOLD,children:t3("settings.appearance.preview")}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:current2.themeName})]}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs("box",{width:COLLAPSED_RAIL_WIDTH[fold],flexShrink:0,flexDirection:"column",backgroundColor:theme.backgroundPanel,children:[$jsx("text",{fg:props.active==="railFold"?theme.focusAccent:theme.textMuted,children:"\u2039"}),folded.map((row,i2)=>$jsx("text",{fg:i2===0?workingInk:i2===1?theme.success:theme.textMuted,wrapMode:"none",children:row.label},row.id))]}),$jsxs("box",{flexGrow:2,flexBasis:0,flexShrink:1,flexDirection:"column",...pane(void 0,theme.border,t3("settings.appearance.tasks"),theme.textMuted),paddingLeft:1,paddingRight:1,backgroundColor:theme.backgroundPanel,children:[!namesOnRule&&$jsx("text",{fg:tasksInk,children:t3("settings.appearance.tasks")}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:"demo / workspace"}),$jsxs("box",{flexDirection:"row",children:[$jsx("text",{fg:theme.focusAccent,attributes:TextAttributes31.BOLD,wrapMode:"none",children:"\u258C "}),$jsx("text",{fg:workingInk,wrapMode:"none",children:`${working} `}),$jsx("text",{fg:theme.text,attributes:TextAttributes31.BOLD,wrapMode:"none",children:current2.runningTitle==="shimmer"?$jsx(ShimmerLabel,{label:"UI polish",tick:tick3,muted:theme.textMuted,accent:theme.primary}):"UI polish"})]}),$jsxs("box",{flexDirection:"row",children:[$jsx("text",{wrapMode:"none",children:" "}),$jsxs("text",{fg:theme.text,wrapMode:"none",children:["API tests ",done]})]}),!short&&$jsxs("box",{flexDirection:"row",children:[$jsx("text",{wrapMode:"none",children:" "}),$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:["Review ",idle]})]})]}),$jsxs("box",{flexGrow:5,flexBasis:0,flexShrink:1,flexDirection:"column",...pane("left",theme.focusAccent,t3("settings.appearance.terminal"),theme.focusAccent),...flowing?{renderAfter:runningPaneFlow(workingTaskInk??theme.focusAccent,theme.border,!0,tick3,workingTaskInk?TASK_PARTNER_HUE_DEG:void 0),...namesOnRule?{}:{title:runningPaneTitle("UI polish",t3("workspace.inbox.state.running"))}}:{},paddingLeft:1,paddingRight:1,children:[!namesOnRule&&$jsxs("text",{fg:theme.focusAccent,attributes:TextAttributes31.BOLD,wrapMode:"none",children:["\u258C ",t3("settings.appearance.terminal")]}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:"UI polish / main"}),!short&&$jsx("text",{fg:theme.text,wrapMode:"none",children:"$ bun test"}),$jsxs("text",{fg:theme.success,wrapMode:"none",children:["\u2713 ",t3("settings.appearance.testsPassed")]}),!short&&$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:"2 pass \xB7 0 fail"}),$jsx("text",{fg:theme.text,wrapMode:"none",children:"$ \u258C"})]}),!narrow&&$jsxs("box",{flexGrow:2,flexBasis:0,flexShrink:1,flexDirection:"column",...pane("left",theme.border,t3("settings.appearance.files"),theme.textMuted),paddingLeft:1,paddingRight:1,children:[!namesOnRule&&$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("settings.appearance.files")}),$jsx("text",{fg:theme.text,wrapMode:"none",children:"\u25BE src"}),$jsxs("text",{fg:inks.added,wrapMode:"none",children:[" ","app.ts +8"]}),$jsxs("text",{fg:inks.removed,wrapMode:"none",children:[" ","ui.tsx \u22123"]}),!short&&$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:[" ","README.md"]})]})]}),$jsx("text",{fg:theme.textMuted,bg:theme.backgroundPanel,wrapMode:"none",children:` \u25CF main ${t3(current2.transparentBackground?"settings.appearance.transparent":"settings.appearance.opaque")}`})]})}function AppearanceSettingsSection(props){let{theme}=useTheme(),t3=useT();return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes32.BOLD,children:t3("settings.general.appearance")}),$jsx(AppearancePreview,{current:props.appearance.current}),$jsx("text",{fg:theme.textMuted,children:t3("settings.appearance.openHint")}),$jsx("box",{flexDirection:"column",children:APPEARANCE_SETTINGS.map((setting)=>{let index=rowIndex(props.rows,`appearance:${setting}`);return $jsx(Row,{cursor:props.level==="body"&&props.bodyRow===index,rowRef:props.rowRef(index),onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(index),props.appearance.open(setting)},fg:theme.text,children:`${t3(`settings.general.${setting}`)}: ${appearanceChoiceLabel(currentAppearanceChoice(props.appearance.current,setting),t3)} \u203A`},setting)})})]})}function SettingsSectionSidebar(props){let{theme}=useTheme(),t3=useT();return $jsx("box",{flexDirection:"column",flexShrink:0,width:SECTIONS_SIDEBAR_WIDTH,gap:1,children:SECTIONS.map((s2,i2)=>{let isSection=i2===props.cursor,isSidebarFocused=isSection&&props.level==="sidebar";return $jsx("box",{paddingLeft:1,paddingRight:1,backgroundColor:isSidebarFocused?theme.primary:void 0,onMouseUp:()=>props.switchSection(s2.id),children:$jsx("text",{fg:isSidebarFocused?theme.selectedListItemText:isSection?theme.accent:theme.textMuted,attributes:isSection?TextAttributes33.BOLD:void 0,wrapMode:"none",children:t3(`settings.sections.${s2.id}`)})},s2.id)})})}function UsageDashboard(props){let{theme}=useTheme(),t3=useT(),toneColor3={ok:theme.success,warn:theme.warning,crit:theme.error},now=Date.now();return $jsx("box",{flexDirection:"column",flexShrink:0,alignSelf:"flex-start",gap:0,children:[...props.usage.entries()].map(([vendor,usage])=>$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes33.BOLD,wrapMode:"none",children:`${engineDisplayName(vendor).toUpperCase()} ${t3("settings.general.usage")}`}),usageRows(usage,now).map((row)=>$jsxs("box",{flexDirection:"row",gap:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:row.label}),$jsx("text",{fg:toneColor3[row.tone],wrapMode:"none",children:`${row.bar} ${row.percentText}`}),row.resetText?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:row.resetText}):null]},row.label))]},vendor))})}function GeneralSettingsSection(props){let{prefs}=props,themeCtx=useTheme(),{theme}=themeCtx,t3=useT(),kv=useKV(),dialog=useDialog(),renderer=useRenderer(),rows=import_react70.useMemo(()=>generalRows(),[]),rowIdx=(id)=>rowIndex(rows,id),isBodyCursor=(row)=>props.level==="body"&&props.bodyRow===row,activate=(row,action)=>()=>{props.setLevel("body"),props.setBodyRow(row),action()},{labelColumn,showHint}=generalLabelLayout(useTerminalSize().width,useDialogPaddingX()),hint=(key)=>showHint?t3(key):void 0,pad=(label)=>label+" ".repeat(Math.max(0,labelColumn-displayWidth(label))),check=(on)=>on?"[x]":"[ ]",radio=(on)=>on?"(\u25CF)":"( )",toastRow=rowIdx("toast"),soundRow=rowIdx("sound"),soundVolumeRow=rowIdx("sound-volume"),crossTaskRow=rowIdx("cross-task"),finishedAlertsRow=rowIdx("finished-alerts"),keyHintsRow=rowIdx("key-hints"),zenDefaultOnRow=rowIdx("zen-default-on"),updateChannelRow=rowIdx("update-channel"),updateTryRow=rowIdx("update-try"),updateCheckRow=rowIdx("update-check"),tryChannel=tryOutChannel(),editorKindRow=rowIdx("editor-kind"),editorCustomRow=rowIdx("editor-custom"),worktreeBaseRow=rowIdx("worktree-base"),worktreeCustomRow=rowIdx("worktree-custom"),scrollbackRow=rowIdx("scrollback-rows"),tabStripHideSingleRow=rowIdx("tab-strip-hide-single");return $jsxs("box",{flexDirection:"row",gap:2,children:[$jsxs("box",{flexDirection:"column",gap:1,flexGrow:1,flexShrink:1,children:[$jsx(SubSection,{title:t3("settings.general.language"),hint:t3("settings.general.languageHint"),children:LOCALES.map((loc)=>{let langRow=rowIdx(languageRowId(loc.id)),isSelected=props.currentLocale===loc.id;return $jsx(Row,{cursor:isBodyCursor(langRow),rowRef:props.rowRef(langRow),onMouseUp:activate(langRow,()=>props.selectLanguage(loc.id)),fg:isSelected?theme.accent:theme.text,bold:isBodyCursor(langRow)||isSelected,children:`${radio(isSelected)} ${loc.label}`},loc.id)})}),$jsx(AppearanceSettingsSection,{...props,rows,appearance:props.appearance}),$jsxs(SubSection,{title:t3("settings.general.notifications"),hint:t3("settings.general.notificationsHint"),children:[$jsx(Row,{cursor:isBodyCursor(toastRow),rowRef:props.rowRef(toastRow),onMouseUp:activate(toastRow,prefs.toggleToast),fg:prefs.toastEnabled()?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.toastHint"),children:pad(`${check(prefs.toastEnabled())} ${t3("settings.general.toast")}`)}),$jsx(Row,{cursor:isBodyCursor(soundRow),rowRef:props.rowRef(soundRow),onMouseUp:activate(soundRow,prefs.toggleSound),fg:prefs.soundEnabled()?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.soundHint"),children:pad(`${check(prefs.soundEnabled())} ${t3("settings.general.sound")}`)}),$jsx(Row,{cursor:isBodyCursor(soundVolumeRow),rowRef:props.rowRef(soundVolumeRow),onMouseUp:activate(soundVolumeRow,prefs.cycleSoundVolume),fg:prefs.soundEnabled()?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.soundVolumeHint"),children:pad(t3("settings.general.soundVolume",{percent:String(Math.round(prefs.soundVolume()*100))}))}),$jsx(Row,{cursor:isBodyCursor(crossTaskRow),rowRef:props.rowRef(crossTaskRow),onMouseUp:activate(crossTaskRow,prefs.toggleCrossTask),fg:prefs.crossTaskEnabled()?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.crossTaskHint"),children:pad(`${check(prefs.crossTaskEnabled())} ${t3("settings.general.crossTask")}`)}),$jsx(Row,{cursor:isBodyCursor(finishedAlertsRow),rowRef:props.rowRef(finishedAlertsRow),onMouseUp:activate(finishedAlertsRow,prefs.toggleFinishedAlerts),fg:prefs.finishedAlertsEnabled()?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.finishedAlertsHint"),children:pad(`${check(prefs.finishedAlertsEnabled())} ${t3("settings.general.finishedAlerts")}`)})]}),$jsx(SubSection,{title:t3("settings.general.keyHints"),hint:t3("settings.general.keyHintsHint"),children:$jsx(Row,{cursor:isBodyCursor(keyHintsRow),rowRef:props.rowRef(keyHintsRow),onMouseUp:activate(keyHintsRow,()=>toggleKeyHints(kv)),fg:keyHintsToggleOn(kv)?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.keyHintsShowHint"),children:pad(`${check(keyHintsToggleOn(kv))} ${t3("settings.general.keyHintsShow")}`)})}),$jsx(SubSection,{title:t3("settings.general.zen"),hint:t3("settings.general.zenHint"),children:$jsx(Row,{cursor:isBodyCursor(zenDefaultOnRow),rowRef:props.rowRef(zenDefaultOnRow),onMouseUp:activate(zenDefaultOnRow,prefs.toggleZenDefaultOn),fg:prefs.zenDefaultOn()?theme.accent:theme.textMuted,bold:!0,children:`${check(prefs.zenDefaultOn())} ${t3("settings.general.zenDefaultOn")}`})}),$jsxs(SubSection,{title:t3("settings.general.updates"),hint:t3("settings.general.updatesHint"),children:[$jsx(Row,{cursor:isBodyCursor(updateChannelRow),rowRef:props.rowRef(updateChannelRow),onMouseUp:activate(updateChannelRow,prefs.toggleUpdateChannel),fg:theme.accent,bold:!0,hint:hint("settings.general.updateChannelHint"),children:pad(t3("settings.general.updateChannel",{channel:t3(`settings.general.updateChannelName.${prefs.updateChannel()}`)}))}),$jsx(Row,{cursor:isBodyCursor(updateTryRow),rowRef:props.rowRef(updateTryRow),onMouseUp:activate(updateTryRow,()=>void confirmTryChannel(dialog,renderer,tryChannel)),fg:theme.text,bold:isBodyCursor(updateTryRow),hint:hint("settings.general.updateTryHint"),children:pad(t3(`settings.general.updateTry.${tryChannel}`))}),$jsx(Row,{cursor:isBodyCursor(updateCheckRow),rowRef:props.rowRef(updateCheckRow),onMouseUp:activate(updateCheckRow,()=>props.onCheckUpdate?.()),fg:theme.text,bold:isBodyCursor(updateCheckRow),hint:hint("settings.general.updateCheckHint"),children:pad(t3("settings.general.updateCheck"))})]}),$jsxs(SubSection,{title:t3("settings.general.editor"),hint:t3("settings.general.editorHint"),children:[$jsx(Row,{cursor:isBodyCursor(editorKindRow),rowRef:props.rowRef(editorKindRow),onMouseUp:activate(editorKindRow,prefs.cycleEditorKind),fg:theme.accent,bold:!0,hint:hint("settings.general.editorRowHint"),children:pad(t3("settings.general.editorRow",{kind:prefs.editorKind()}))}),$jsx(Row,{cursor:isBodyCursor(editorCustomRow),rowRef:props.rowRef(editorCustomRow),onMouseUp:activate(editorCustomRow,()=>void prefs.editEditorCustom()),fg:prefs.editorKind()==="custom"?theme.text:theme.textMuted,children:t3("settings.general.editorCustom",{cmd:prefs.editorCustomCommand().trim()||t3("settings.general.editorCustomUnset")})})]}),$jsxs(SubSection,{title:t3("settings.general.worktree"),hint:t3("settings.general.worktreeHint"),children:[$jsx(Row,{cursor:isBodyCursor(worktreeBaseRow),rowRef:props.rowRef(worktreeBaseRow),onMouseUp:activate(worktreeBaseRow,prefs.cycleWorktreeBase),fg:theme.accent,bold:!0,hint:hint("settings.general.worktreeBaseHint"),children:pad(t3("settings.general.worktreeBase",{kind:prefs.worktreeKindLabel()}))}),$jsx(Row,{cursor:isBodyCursor(worktreeCustomRow),rowRef:props.rowRef(worktreeCustomRow),onMouseUp:activate(worktreeCustomRow,()=>void prefs.editWorktreeCustom()),fg:prefs.worktreeKind()==="custom"?theme.text:theme.textMuted,children:t3("settings.general.worktreeCustom",{path:prefs.worktreeCustomPath()||t3("settings.general.worktreeCustomUnset")})})]}),$jsxs(SubSection,{title:t3("settings.general.terminal"),hint:t3("settings.general.terminalHint"),children:[$jsx(Row,{cursor:isBodyCursor(scrollbackRow),rowRef:props.rowRef(scrollbackRow),onMouseUp:activate(scrollbackRow,()=>void prefs.editScrollbackRows()),fg:theme.accent,bold:!0,hint:hint("settings.general.scrollbackRowHint"),children:pad(t3("settings.general.scrollbackRow",{rows:String(prefs.scrollbackRows())}))}),$jsx(Row,{cursor:isBodyCursor(tabStripHideSingleRow),rowRef:props.rowRef(tabStripHideSingleRow),onMouseUp:activate(tabStripHideSingleRow,prefs.cycleTabStripMode),fg:theme.accent,bold:!0,children:t3("settings.general.tabStripRow",{mode:t3(`settings.general.tabStripMode.${prefs.tabStripMode()}`)})})]})]}),props.usage&&props.usage.size>0?$jsx(UsageDashboard,{usage:props.usage}):null]})}import{TextAttributes as TextAttributes34}from"@opentui/core";function MarketRow(props){let{theme}=useTheme(),t3=useT(),{row}=props,installed=row.installedId!==null;return $jsxs("box",{flexDirection:"column",gap:0,children:[$jsxs("box",{ref:props.rowRef,flexDirection:"row",gap:1,paddingLeft:1,paddingRight:1,backgroundColor:props.cursor?theme.primary:void 0,onMouseUp:props.onActivate,children:[$jsx("text",{fg:props.cursor?theme.selectedListItemText:installed?theme.textMuted:theme.accent,attributes:TextAttributes34.BOLD,wrapMode:"none",children:row.ref}),$jsx("text",{fg:props.cursor?theme.selectedListItemText:theme.textMuted,wrapMode:"none",children:installed?t3("settings.marketplace.installedTag"):row.stars!==null?`\u2605${row.stars}`:row.firstParty?t3("settings.marketplace.firstParty"):""})]}),row.desc?$jsx("box",{flexDirection:"row",paddingLeft:5,paddingRight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:row.desc})}):null]})}function MarketplaceSettingsSection(props){let{theme}=useTheme(),t3=useT();return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes34.BOLD,children:t3("settings.marketplace.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.marketplace.hint")}),props.offline?$jsx("text",{fg:theme.warning,wrapMode:"word",children:t3("settings.marketplace.offline")}):null,props.status?$jsx("text",{fg:theme.accent,wrapMode:"word",children:props.status}):null,props.loading?$jsx("text",{fg:theme.textMuted,children:t3("settings.marketplace.loading")}):props.rows.length===0?$jsx("text",{fg:theme.textMuted,children:t3("settings.marketplace.empty")}):$jsx("box",{flexDirection:"column",gap:0,children:props.rows.map((row,i2)=>$jsx(MarketRow,{row,cursor:props.level==="body"&&props.bodyRow===i2,rowRef:props.rowRef(i2),onActivate:()=>{props.setLevel("body"),props.setBodyRow(i2),props.install(row.ref)}},row.ref))})]})}var import_react71=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes35}from"@opentui/core";function FeedbackSettingsSection(props){let{theme}=useTheme(),t3=useT(),editing=props.level==="body",titleFocused=editing&&props.bodyRow===0,bodyFocused=editing&&props.bodyRow===1,sendFocused=editing&&props.bodyRow===2,labelFg=(focused)=>focused?theme.primary:theme.textMuted,labelAttrs=(focused)=>focused?TextAttributes35.BOLD|TextAttributes35.UNDERLINE:void 0,bodyEl=import_react71.useRef(null);return import_react71.useEffect(()=>{if(props.body===""&&bodyEl.current&&bodyEl.current.plainText!=="")bodyEl.current.setText("")},[props.body]),$jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.feedback.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.feedback.hint")}),$jsxs("box",{flexDirection:"column",gap:1,children:[$jsxs("box",{gap:0,children:[$jsx("text",{fg:labelFg(titleFocused),attributes:labelAttrs(titleFocused),children:t3("settings.feedback.titleLabel")}),$jsx("input",{value:props.title,placeholder:t3("settings.feedback.titlePlaceholder"),focused:titleFocused,onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(0)},onInput:(v3)=>props.setTitle(stripNewlines2(v3)),onSubmit:()=>props.onTitleSubmit()})]}),$jsxs("box",{gap:0,children:[$jsx("text",{fg:labelFg(bodyFocused),attributes:labelAttrs(bodyFocused),children:t3("settings.feedback.descriptionLabel")}),$jsx("textarea",{ref:(el)=>{bodyEl.current=el},initialValue:props.body,placeholder:t3("settings.feedback.descriptionPlaceholder"),focused:bodyFocused,height:4,wrapMode:"word",onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(1)},onContentChange:()=>props.setBody(bodyEl.current?.plainText??"")})]}),$jsx("box",{flexDirection:"row",paddingLeft:1,paddingRight:1,backgroundColor:sendFocused?theme.primary:theme.backgroundElement,onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(2),props.submit()},children:$jsx("text",{fg:sendFocused?theme.selectedListItemText:theme.accent,attributes:TextAttributes35.BOLD,children:t3("settings.feedback.send")})})]}),props.status?$jsx("text",{fg:props.status.startsWith("error:")?theme.warning:theme.success,wrapMode:"word",children:props.status}):null]})}function DevSettingsSection(props){let{prefs}=props,{theme}=useTheme(),t3=useT(),rows=devRows(props.hasDaemon),isBodyCursor=(row)=>props.level==="body"&&props.bodyRow===row,activate=(row,action)=>()=>{props.setLevel("body"),props.setBodyRow(row),action()},toggleRow=(id,enabled,hintKey,labelKey,act)=>{let row=rowIndex(rows,id);return $jsxs("box",{flexDirection:"column",gap:0,paddingTop:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3(hintKey)}),$jsx(Row,{cursor:isBodyCursor(row),rowRef:props.rowRef(row),onMouseUp:activate(row,act),fg:theme.text,bold:enabled,idleBackground:theme.backgroundElement,children:`${enabled?"[x]":"[ ]"} ${t3(labelKey)}`})]})};return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.dev.reset")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.dev.resetHint")}),$jsx(Row,{cursor:isBodyCursor(0),rowRef:props.rowRef(0),onMouseUp:activate(0,props.confirmReset),fg:theme.warning,bold:!0,idleBackground:theme.backgroundElement,children:t3("settings.dev.resetButton")}),props.hasDaemon?$jsx(SubSection,{title:t3("settings.dev.restart"),hint:t3("settings.dev.restartHint"),children:$jsx(Row,{cursor:isBodyCursor(1),rowRef:props.rowRef(1),onMouseUp:activate(1,props.confirmRestartDaemon),fg:theme.accent,bold:!0,idleBackground:theme.backgroundElement,children:t3("settings.dev.restartButton")})}):null,$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.dev.doctorHint")}),$jsxs(SubSection,{title:t3("settings.dev.reload"),hint:t3("settings.dev.reloadHint"),children:[$jsx(Row,{cursor:isBodyCursor(rowIndex(rows,"dev-reload")),rowRef:props.rowRef(rowIndex(rows,"dev-reload")),onMouseUp:activate(rowIndex(rows,"dev-reload"),props.reloadSettings),fg:theme.accent,bold:!0,idleBackground:theme.backgroundElement,children:t3("settings.dev.reloadButton")}),props.reloadStatus?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:props.reloadStatus}):null]}),$jsxs("box",{flexDirection:"column",gap:0,paddingTop:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.dev.experimental")}),toggleRow("remote-projects",prefs.remoteProjectsEnabled(),"settings.dev.remoteHint","settings.dev.remote",prefs.toggleRemoteProjects),toggleRow("auto-status",prefs.autoStatusOn(),"settings.dev.autoStatusHint","settings.dev.autoStatus",prefs.toggleAutoStatus),toggleRow("dispatcher",prefs.dispatcherOn(),"settings.dev.dispatcherHint","settings.dev.dispatcher",prefs.toggleDispatcher)]})]})}function KeybindingsSettingsSection(props){let{theme}=useTheme(),t3=useT();useKeymapVersion();let report=userKeybindingsReport(),rows=keybindingRows(report.exists),prefix=currentPrefixConfiguration(),fixedIds=Object.keys(FIXED_BINDING_IDS).sort(),appliedIdWidth=Math.min(28,report.applied.reduce((max,o2)=>Math.max(max,o2.id.length),0));return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.keybindings.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.keybindings.hint")}),$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.keybindings.configFile")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:tildify(report.path)+(report.exists?"":t3("settings.keybindings.notCreated"))})]}),$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.keybindings.tapPresentation")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.keybindings.tapPresentationHint")}),PREFIX_TAP_PRESENTATIONS.map((presentation)=>{let row=rowIndex(rows,prefixTapPresentationRowId(presentation)),selected=props.prefs.prefixTapPresentation()===presentation;return $jsx(Row,{cursor:props.level==="body"&&props.bodyRow===row,rowRef:props.rowRef(row),onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(row),props.prefs.selectPrefixTapPresentation(presentation)},fg:selected?theme.accent:theme.text,bold:selected||props.level==="body"&&props.bodyRow===row,children:`${selected?"(\u25CF)":"( )"} ${t3(presentation==="local"?"settings.keybindings.tapPresentationLocal":"settings.keybindings.tapPresentationGuide")}`},presentation)})]}),$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.keybindings.prefixTitle",{prefix:prefix.key??t3("settings.keybindings.prefixDisabled")})}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.keybindings.prefixHint",{prefix:prefix.key??t3("settings.keybindings.prefixDisabled"),timeout:prefix.timeoutMs})})]}),!report.exists?$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.keybindings.createHint")}),$jsx(Row,{cursor:props.level==="body"&&props.bodyRow===rowIndex(rows,"keys-create"),rowRef:props.rowRef(rowIndex(rows,"keys-create")),onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(rowIndex(rows,"keys-create")),props.onCreateFile()},fg:theme.text,idleBackground:theme.backgroundElement,children:t3("settings.keybindings.createFile")})]}):$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.keybindings.overridesApplied")}),report.applied.length===0?$jsx("text",{fg:theme.textMuted,children:t3("settings.keybindings.none")}):null,report.applied.map((o2)=>$jsx("text",{fg:theme.text,wrapMode:"none",children:`${o2.id.padEnd(appliedIdWidth)} ${o2.keys.length>0?o2.keys.join(" / "):t3("settings.keybindings.unbound")} (${t3("settings.keybindings.defaultKeys",{keys:o2.defaultKeys.join(" / ")})})`},o2.id))]}),report.warnings.length>0?$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.warning,attributes:TextAttributes35.BOLD,children:t3("settings.keybindings.warnings")}),report.warnings.map((w4)=>$jsx("text",{fg:theme.warning,wrapMode:"word",children:`! ${w4}`},w4))]}):null,fixedIds.length>0?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.keybindings.fixed",{ids:fixedIds.join(", ")})}):null]})}import{TextAttributes as TextAttributes36}from"@opentui/core";function toggleRowOffsets(plugins){let offsets=[],next=0;for(let plugin of plugins)offsets.push(next),next+=1+plugin.settings.length;return offsets}function SettingRow(props){let{theme}=useTheme(),t3=useT(),{setting}=props,value=setting.type==="boolean"?isBooleanOn(setting.value)?t3("settings.general.on"):t3("settings.general.off"):displaySettingValue(setting)||t3("settings.plugins.settingUnset");return $jsxs("box",{ref:props.rowRef,flexDirection:"row",gap:1,paddingLeft:5,paddingRight:1,backgroundColor:props.cursor?theme.primary:void 0,onMouseUp:props.onActivate,children:[$jsx("text",{fg:props.cursor?theme.selectedListItemText:theme.text,wrapMode:"none",children:setting.label}),$jsx("text",{fg:props.cursor?theme.selectedListItemText:setting.defaulted?theme.textMuted:theme.accent,wrapMode:"none",children:value})]})}function PluginSettingsSection(props){let{theme}=useTheme(),t3=useT(),now=Date.now(),isBodyCursor=(row)=>props.level==="body"&&props.bodyRow===row,offsets=toggleRowOffsets(props.plugins);return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes36.BOLD,children:t3("settings.plugins.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3(props.plugins.some((plugin)=>!plugin.builtIn)?"settings.plugins.hint":"settings.plugins.empty")}),props.plugins.length===0?null:$jsx("box",{flexDirection:"column",gap:0,children:props.plugins.map((plugin,i2)=>{let toggleRow=offsets[i2]??0,isCursor=isBodyCursor(toggleRow);return $jsxs("box",{flexDirection:"column",gap:0,children:[$jsxs("box",{ref:props.rowRef(toggleRow),flexDirection:"row",gap:1,paddingLeft:1,paddingRight:1,backgroundColor:isCursor?theme.primary:void 0,onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(toggleRow),props.toggle(plugin.id)},children:[$jsx("text",{fg:isCursor?theme.selectedListItemText:plugin.enabled?theme.accent:theme.textMuted,attributes:TextAttributes36.BOLD,wrapMode:"none",children:`${plugin.enabled?"[x]":"[ ]"} ${plugin.id}`}),$jsx("text",{fg:isCursor?theme.selectedListItemText:theme.textMuted,wrapMode:"none",children:plugin.builtIn?t3(plugin.enabled?"settings.plugins.sourceBuiltInInstalled":"settings.plugins.sourceBuiltIn"):`v${plugin.version} ${plugin.linked?t3("settings.plugins.sourceLink",{path:plugin.source}):t3("settings.plugins.sourceGithub",{spec:plugin.source})}`}),plugin.updateAvailable?$jsx("text",{fg:theme.warning,wrapMode:"none",children:t3("settings.plugins.updateAvailable")}):null]}),plugin.builtIn?null:$jsxs("box",{flexDirection:"row",gap:1,paddingLeft:5,paddingRight:1,children:[$jsx("text",{fg:plugin.declares?theme.textMuted:theme.warning,wrapMode:"none",children:plugin.declares?plugin.declares.engines>0?t3("settings.plugins.declaresWithEngines",{actions:String(plugin.declares.actions),events:String(plugin.declares.events),panes:String(plugin.declares.panes),engines:String(plugin.declares.engines)}):t3("settings.plugins.declares",{actions:String(plugin.declares.actions),events:String(plugin.declares.events),panes:String(plugin.declares.panes)}):t3("settings.plugins.manifestUnreadable")}),plugin.declares&&plugin.declares.pages>0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("settings.plugins.declaresPages",{pages:String(plugin.declares.pages)})}):null,$jsx("text",{fg:!plugin.platformOk||plugin.lastRun?.running?theme.warning:plugin.lastRun?.ok===!1?theme.error:theme.textMuted,wrapMode:"none",children:!plugin.platformOk?t3("settings.plugins.unsupportedPlatform"):plugin.lastRun?t3("settings.plugins.lastRun",{label:plugin.lastRun.label,status:plugin.lastRun.running?t3("settings.plugins.runRunning"):plugin.lastRun.ok?t3("settings.plugins.runOk"):plugin.lastRun.spawnError?t3("settings.plugins.runFailed"):t3("settings.plugins.runExit",{code:String(plugin.lastRun.exitCode)}),ago:relativeAge(plugin.lastRun.at,now)}):plugin.hooksDeclared?t3("settings.plugins.neverRun"):t3("settings.plugins.noHooks")})]}),plugin.pageErrors.map((detail)=>$jsx("text",{fg:theme.warning,paddingLeft:5,wrapMode:"word",children:t3("settings.plugins.pageFailed",{detail})},detail)),plugin.settings.map((setting,s2)=>$jsx(SettingRow,{setting,cursor:isBodyCursor(toggleRow+1+s2),rowRef:props.rowRef(toggleRow+1+s2),onActivate:()=>{props.setLevel("body"),props.setBodyRow(toggleRow+1+s2),props.editSetting(plugin.id,setting.key)}},setting.key))]},plugin.id)})})]})}var import_react72=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes37}from"@opentui/core";function AppearancePicker(props){let dialog=useDialog(),{theme}=useTheme(),t3=useT(),options=appearanceChoices(props.setting,props.themes),saved=currentAppearanceChoice(props.current,props.setting),[cursor,setCursor]=import_react72.useState(()=>Math.max(0,options.findIndex((option)=>option.value===saved.value))),selected=options[cursor],follow=useCursorFollow3(cursor);function commit(choice){if(!choice)return;props.onCommit(choice),dialog.pop()}function move(delta){if(options.length)setCursor((cursor+delta+options.length)%options.length)}return useBindings(()=>({bindings:[{key:"j",cmd:()=>move(1)},{key:"down",cmd:()=>move(1)},{key:"k",cmd:()=>move(-1)},{key:"up",cmd:()=>move(-1)},{key:"return",cmd:()=>commit(selected)}]})),$jsxs("box",{paddingLeft:useDialogPaddingX(),paddingRight:useDialogPaddingX(),paddingBottom:1,gap:1,flexShrink:1,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",flexShrink:0,children:[$jsxs("text",{fg:theme.text,attributes:TextAttributes37.BOLD,children:[t3("settings.general.appearance")," / ",t3(`settings.general.${props.setting}`)]}),$jsx("text",{fg:theme.textMuted,onMouseUp:()=>dialog.pop(),children:t3("settings.esc")})]}),$jsx(AppearancePreview,{current:selected?applyAppearanceChoice(props.current,selected):props.current,active:props.setting}),$jsx("text",{fg:theme.textMuted,flexShrink:0,children:t3("settings.appearance.chooseHint")}),$jsx("scrollbox",{ref:follow.scrollRef,flexShrink:1,maxHeight:8,children:options.map((option,index)=>$jsx(Row,{cursor:cursor===index,rowRef:follow.rowRef(index),onMouseUp:()=>commit(option),fg:theme.text,bold:option.value===saved.value,children:`${option.value===saved.value?"(\u25CF)":"( )"} ${appearanceChoiceLabel(option,t3)}`},String(option.value)))})]})}function useAppearanceSettings(kv,dialog,prefs){let theme=useTheme(),current2={themeName:theme.selected,themeMode:theme.modePreference,transparentBackground:theme.transparentBackground,focusAccent:theme.focusAccent,splitStyle:prefs.splitStyle(),railFoldStyle:prefs.railFoldStyle(),workingBorder:prefs.workingBorder(),taskColors:prefs.taskColors(),glyphSet:prefs.glyphSet(),colorblind:prefs.colorblind(),runningTitle:prefs.runningTitle()};function commit(choice){switch(choice.kind){case"theme":if(theme.set(choice.value))kv.set("activeTheme",choice.value);break;case"themeMode":theme.setMode(choice.value),kv.set("themeMode",choice.value);break;case"transparent":theme.setTransparentBackground(choice.value),kv.set("transparentBackground",choice.value);break;case"focusAccent":theme.setFocusAccent(choice.value),kv.set("focusAccent",choice.value);break;case"splitStyle":prefs.selectSplitStyle(choice.value);break;case"railFold":prefs.selectRailFoldStyle(choice.value);break;case"workingBorder":prefs.selectWorkingBorder(choice.value);break;case"taskColors":prefs.selectTaskColors(choice.value);break;case"glyphSet":prefs.selectGlyphSet(choice.value);break;case"colorblind":prefs.selectColorblind(choice.value);break;case"runningTitle":prefs.selectRunningTitle(choice.value);break}}function open(setting){dialog.setSize("xlarge"),dialog.push(()=>$jsx(AppearancePicker,{setting,current:current2,themes:theme.all().slice().sort(),onCommit:commit}))}return{current:current2,open}}var import_react74=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes38}from"@opentui/core";var import_react73=__toESM(require_react_production(),1);function engineAcceptsModel(vendor){return engineEntry(vendor).modelArgv!==void 0}var lists2=new Map;function modelsFor(vendor){let list=engineEntry(vendor).listModels;if(!list)return null;let pending=lists2.get(vendor);if(!pending)pending=list().catch((err)=>{throw lists2.delete(vendor),err}),lists2.set(vendor,pending);return pending}function filterModels(models,query){let q2=query.trim().toLowerCase();if(!q2)return models;return models.filter((m3)=>m3.id.toLowerCase().includes(q2)||m3.label?.toLowerCase().includes(q2))}function useModelField(opts){let[query,setQuery]=import_react73.useState(()=>opts.vendor===opts.initialVendor?opts.initial??"":""),[cursor,setCursor]=import_react73.useState(-1),[models,setModels]=import_react73.useState([]),[status,setStatus]=import_react73.useState("none");import_react73.useEffect(()=>{setQuery(opts.vendor===opts.initialVendor?opts.initial??"":""),setCursor(-1);let pending=modelsFor(opts.vendor);if(!pending){setModels([]),setStatus("none");return}let live=!0;return setStatus("loading"),pending.then((list)=>{if(!live)return;setModels(list),setStatus("loaded")},()=>{if(!live)return;setModels([]),setStatus("failed")}),()=>{live=!1}},[opts.vendor,opts.seedKey]);let suggestions=import_react73.useMemo(()=>filterModels(models,query),[models,query]),value=cursor>=0?suggestions[cursor]?.id??query:query,window2=windowAround(suggestions.map((m3)=>m3.id),Math.max(0,cursor),opts.pickerRows);function setText(v3){setQuery(stripNewlines2(v3)),setCursor(-1)}function moveCursor(delta){if(suggestions.length===0)return;setCursor((c2)=>clampCursor2(c2+delta,suggestions.length))}function pickAt(absoluteIndex){if(suggestions[absoluteIndex])setCursor(absoluteIndex)}return{value,query,cursor,suggestions,window:window2,status,setText,moveCursor,pickAt}}function ModelSection(props){let{theme}=useTheme(),t3=useT(),{field}=props,rows=field.suggestions.slice(field.window.start,field.window.start+field.window.items.length).map((m3,i2)=>({key:`${field.window.start+i2}:${m3.id}`,body:m3.id,accent:!1,...m3.label&&m3.label!==m3.id?{dim:m3.label}:{}}));return $jsxs($Fragment,{children:[$jsx(DialogSection2,{label:t3("tasks.engineModel.label"),focused:props.focused,hint:props.hint,onPress:props.onFocus,children:$jsx(DialogField2,{focused:props.focused,children:$jsx("input",{value:field.value,placeholder:t3("tasks.engineModel.placeholder"),focused:props.focused,onMouseUp:props.onFocus,onInput:(v3)=>field.setText(v3),onSubmit:props.onSubmit})})}),props.focused&&field.status==="loading"?$jsx("box",{paddingLeft:2,paddingBottom:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("tasks.engineModel.loading")})}):null,props.focused&&field.window.total>0?$jsx(PickerList,{window:field.window,cursor:Math.max(0,field.cursor),rows,onPick:field.pickAt,paddingBottom:1}):null]})}var NO_EFFORT="";function effortLevelsOf(vendor){return engineEntry(vendor).effortLevels??[]}function seedEffort(vendor,current2){let trimmed=current2?.trim();return trimmed&&effortLevelsOf(vendor).includes(trimmed)?trimmed:NO_EFFORT}function EnginePickerDialogView(props){let dialog=useDialog(),{theme}=useTheme(),t3=useT(),padX=useDialogPaddingX(),{engines}=props,[cursor,setCursor]=import_react74.useState(()=>Math.max(0,engines.indexOf(props.current))),[effort,setEffort]=import_react74.useState(()=>seedEffort(props.current,props.currentEffort)),[field,setField]=import_react74.useState("engine"),window2={items:[...engines],start:0,total:engines.length},cursorEngine=engines[cursor]??props.current,levels=effortLevelsOf(cursorEngine),effortChoices=levels.length>0?[NO_EFFORT,...levels]:[],modelRow=engineAcceptsModel(cursorEngine),model=useModelField({vendor:cursorEngine,pickerRows:pickerVisibleRows(useTerminalSize().height),initial:props.currentModel,initialVendor:props.current}),modelFocused=modelRow&&field==="model";function move(delta){setCursor((c2)=>{let next=clampCursor2(c2+delta,engines.length);return setEffort((e2)=>seedEffort(engines[next]??props.current,e2)),next})}function stepEffort(delta){if(effortChoices.length===0)return;let i2=effortChoices.indexOf(effort);setEffort(effortChoices[clampCursor2((i2<0?0:i2)+delta,effortChoices.length)]??NO_EFFORT)}function commit(engine){let applicable=effortLevelsOf(engine);props.onSubmit({vendor:engine,...applicable.length>0?{effort:seedEffort(engine,effort)}:{},...engineAcceptsModel(engine)?{model:model.value.trim()}:{}}),dialog.clear()}let rows=engines.map((engine,i2)=>({key:`${i2}:${engine}`,body:engineDisplayName(engine),accent:engine===props.current,dim:engine===props.current?t3("tasks.changeEngine.current"):void 0}));useBindings(()=>({bindings:[{key:"up",cmd:()=>modelFocused?model.moveCursor(-1):move(-1)},{key:"down",cmd:()=>modelFocused?model.moveCursor(1):move(1)},...modelFocused?[]:[{key:"left",cmd:()=>stepEffort(-1)},{key:"right",cmd:()=>stepEffort(1)},{key:"h",cmd:()=>stepEffort(-1)},{key:"l",cmd:()=>stepEffort(1)},{key:"return",cmd:()=>commit(engines[cursor]??props.current)}],...modelRow?[{key:"tab",cmd:()=>setField((f2)=>f2==="engine"?"model":"engine")}]:[]]}));let footer=[t3("tasks.changeEngine.footer.engine"),...modelRow?[t3("tasks.changeEngine.footer.model")]:[],...effortChoices.length>0?[t3("tasks.changeEngine.footer.effort")]:[],t3("tasks.changeEngine.footer.set"),t3("tasks.changeEngine.footer.cancel")].join(" \xB7 ");return $jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:1,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",children:[$jsx("text",{attributes:TextAttributes38.BOLD,fg:theme.text,children:t3("tasks.changeEngine.title")}),$jsx("text",{fg:theme.textMuted,onMouseUp:()=>props.onCancel(),children:"esc"})]}),$jsx(PickerList,{window:window2,cursor,rows,onPick:(absoluteIndex)=>commit(engines[absoluteIndex]??props.current),paddingBottom:effortChoices.length>0||modelRow?0:1,focused:!modelFocused}),modelRow?$jsx(ModelSection,{field:model,focused:modelFocused,hint:"tab",onFocus:()=>setField("model"),onSubmit:()=>commit(cursorEngine)}):null,effortChoices.length>0?$jsx(DialogSection2,{label:t3("tasks.changeEngine.effortLabel"),focused:!1,hint:"\u2190/\u2192",children:$jsx(ChipRow2,{choices:effortChoices,selected:effort,display:(choice)=>choice===NO_EFFORT?t3("tasks.changeEngine.noEffort"):effortLabel(levels,choice),onPick:(choice)=>setEffort(choice)})}):null,$jsx("box",{paddingBottom:1,children:$jsx("text",{fg:theme.textMuted,children:footer})})]})}function show6(dialog,opts){return showDialog(dialog,(resolve2)=>$jsx(EnginePickerDialogView,{engines:opts.engines,current:opts.current,currentEffort:opts.currentEffort,currentModel:opts.currentModel,onSubmit:(v3)=>resolve2(v3),onCancel:()=>resolve2(void 0)}))}var EnginePickerDialog={show:show6};function useAutoRoutingSettings(kv,dialog,engineList,statuses){let table=readAutoRoutingTable((key)=>kv.get(key)),engineIds=new Set(engineList());function block(tier){if(!table)return;if(statuses===null)return;let byVendor=new Map(statuses.map((s2)=>[s2.vendor,s2]));return tierBlock(table[tier],{engineIds,accountKind:(engine)=>byVendor.get(engine)?.account?.kind??null})}async function edit(tier){let current2=table?.[tier],engines=engineList(),pick=await EnginePickerDialog.show(dialog,{engines:engines.length>0?engines:current2?[current2.engine]:[],current:current2?.engine??engines[0]??"claude",currentEffort:current2?.effort,currentModel:current2?.model});if(!pick)return;kv.set(autoRoutingKey(tier,"engine"),pick.vendor),kv.set(autoRoutingKey(tier,"model"),pick.model??""),kv.set(autoRoutingKey(tier,"effort"),pick.effort??"")}return{table,block,edit}}var MODE_KEY="autoRouting.classifier",ENDPOINT_KEY="autoRouting.classifierEndpoint",THRESHOLD_KEY="autoRouting.classifierThreshold",LOOPBACK=/^(?:localhost|127\.\d+\.\d+\.\d+|\[?::1\]?|.+\.localhost)$/i;function stringAt(kv,key){let v3=kv.get(key,"");return typeof v3==="string"?v3.trim():""}function acceptableEndpoint(url){let parsed;try{parsed=new URL(url)}catch{return!1}if(parsed.protocol==="https:")return!0;return parsed.protocol==="http:"&&LOOPBACK.test(parsed.hostname)}function useClassifierSettings(kv,dialog,visible,env=process.env){let t3=useT(),config=readClassifierConfig((key2)=>kv.get(key2)),mode=config.mode.kind==="url"?"custom":config.mode.kind==="jev"?"jev":"off",remembered=stringAt(kv,ENDPOINT_KEY),endpoint=displayEndpoint(config.mode.kind,stringAt(kv,MODE_KEY),remembered);function cycle(){if(mode==="off"){kv.set(MODE_KEY,"jev");return}if(mode==="jev"){kv.set(MODE_KEY,remembered||"off");return}if(endpoint)kv.set(ENDPOINT_KEY,endpoint);kv.set(MODE_KEY,"off")}async function editEndpoint(){let next=await RenameTaskDialog.show(dialog,endpoint,{dialogTitle:t3("settings.autoRouting.endpointTitle"),fieldLabel:t3("settings.autoRouting.endpointField"),submitLabel:t3("settings.action.save"),placeholder:"https://tiers.internal/pick",allowEmpty:!0});if(next===void 0)return;let url=next.trim();if(!url){if(kv.set(ENDPOINT_KEY,""),mode==="custom")kv.set(MODE_KEY,"off");return}if(!acceptableEndpoint(url)){await DialogConfirm.show(dialog,t3("settings.autoRouting.endpointInvalidTitle"),t3("settings.autoRouting.endpointInvalidBody"),"cancel");return}if(kv.set(ENDPOINT_KEY,url),mode==="custom")kv.set(MODE_KEY,url)}async function editThreshold(){let next=await RenameTaskDialog.show(dialog,config.threshold.toFixed(2),{dialogTitle:t3("settings.autoRouting.thresholdTitle"),fieldLabel:t3("settings.autoRouting.thresholdField"),submitLabel:t3("settings.action.save"),placeholder:"0.50"});if(next===void 0)return;let n2=Number.parseFloat(next.trim());if(!Number.isFinite(n2)||n2<0||n2>1){await DialogConfirm.show(dialog,t3("settings.autoRouting.thresholdInvalidTitle"),t3("settings.autoRouting.thresholdInvalidBody"),"cancel");return}kv.set(THRESHOLD_KEY,n2)}async function editKey(){if(!config.keyEnv){await DialogConfirm.show(dialog,t3("settings.autoRouting.keyNoVariableTitle"),t3("settings.autoRouting.keyNoVariableBody"),"cancel");return}let next=await RenameTaskDialog.show(dialog,"",{dialogTitle:t3("settings.autoRouting.keyTitle",{env:config.keyEnv}),fieldLabel:config.keyEnv,submitLabel:t3("settings.action.save"),placeholder:t3("settings.autoRouting.keyPlaceholder"),allowEmpty:!0});if(next===void 0)return;try{writeSecret(config.keyEnv,next.trim())}catch(err){await DialogConfirm.show(dialog,t3("settings.autoRouting.keyWriteFailedTitle"),t3("settings.autoRouting.keyWriteFailedBody",{reason:err instanceof Error?err.message:String(err)}),"cancel")}}let key=visible&&config.keyEnv?secretStatus(config.keyEnv,env):{source:"none",hint:""};return{mode,endpoint,threshold:config.threshold,keyEnv:config.keyEnv??"",keySource:key.source,keyHint:key.hint,keyConfigured:config.keyEnv!==void 0,cycle,editEndpoint,editThreshold,editKey}}var import_react76=__toESM(require_react_production(),1);var import_react75=__toESM(require_react_production(),1);var NO_ENGINE_PROTOCOL="",CHOICES=[...ENGINE_PROTOCOLS,NO_ENGINE_PROTOCOL];function EngineProtocolPickerDialogView(props){let dialog=useDialog(),t3=useT(),padX=useDialogPaddingX(),[cursor,setCursor]=import_react75.useState(0),window2={items:[...CHOICES],start:0,total:CHOICES.length};function commit(protocol){if(protocol===void 0)return;props.onSubmit(protocol),dialog.clear()}let rows=CHOICES.map((protocol,i2)=>({key:`${i2}:${protocol||"none"}`,body:protocol?engineEntry(protocol).displayName:t3("settings.engines.protocolNone"),dim:protocol||void 0}));return useBindings(()=>({bindings:[{key:"up",cmd:()=>setCursor((c2)=>clampCursor2(c2-1,CHOICES.length))},{key:"down",cmd:()=>setCursor((c2)=>clampCursor2(c2+1,CHOICES.length))},{key:"return",cmd:()=>commit(CHOICES[cursor])}]})),$jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:1,children:[$jsx(DialogHeader2,{title:t3("settings.engines.protocolTitle",{id:props.engineId}),onClose:()=>props.onCancel()}),$jsx(PickerList,{window:window2,cursor,rows,onPick:(absoluteIndex)=>commit(CHOICES[absoluteIndex]),paddingBottom:1}),$jsx(DialogFooter2,{children:t3("settings.engines.protocolFooter")})]})}function show7(dialog,opts){return showDialog(dialog,(resolve2)=>$jsx(EngineProtocolPickerDialogView,{engineId:opts.engineId,onSubmit:(v3)=>resolve2(v3),onCancel:()=>resolve2(void 0)}))}var EngineProtocolPickerDialog={show:show7};function useEngineSettings(kv,dialog,onEngineListShrunk){let[detected,setDetected]=import_react76.useState([]);import_react76.useEffect(()=>{installedEngineIds().then(setDetected)},[]);function customEngines(){let raw=kv.get("customEngineIds",[]);return Array.isArray(raw)?raw.filter((s2)=>typeof s2==="string"&&s2.trim().length>0):[]}function engineList(){return[...new Set([...ALL_VENDORS,...customEngines(),...detected])]}function isCustomEngine(vendor){return customEngines().includes(vendor)}function disabledEngines(){let raw=kv.get("disabledEngineIds",[]);return Array.isArray(raw)?raw.filter((s2)=>typeof s2==="string"&&s2.trim().length>0):[]}function isEngineEnabled(vendor){return!disabledEngines().includes(vendor)}function toggleEngineEnabled(vendor){let off=disabledEngines();if(off.includes(vendor)){kv.set("disabledEngineIds",off.filter((id)=>id!==vendor));return}let nextDefault=engineList().find((id)=>id!==vendor&&!off.includes(id));if(defaultEngine===vendor){if(!nextDefault)return;setEngineDefault(nextDefault)}kv.set("disabledEngineIds",[...off,vendor])}function engineOverride(vendor){let v3=kv.get(engineCommandKey(vendor),"");return typeof v3==="string"?v3.trim():""}function engineCommandText(vendor){return engineOverride(vendor)||defaultEngineCommand(vendor).join(" ")}function engineHasCommandOverride(vendor){return engineOverride(vendor).length>0}function engineRenamedFromName(vendor){return engineRenamedFrom(vendor,engineNameOverride(vendor))}function engineIsDefault(vendor){return!isCustomEngine(vendor)&&engineOverride(vendor).length===0&&!engineNameIsCustom(vendor)}function engineNameOverride(vendor){let v3=kv.get(engineNameKey(vendor),"");return typeof v3==="string"?v3.trim():""}function engineNameIsCustom(vendor){return engineNameOverride(vendor).length>0}function engineProtocol(vendor){let raw=kv.get(engineProtocolKey(vendor),""),declared=typeof raw==="string"?raw.trim():"";return declared&&ENGINE_PROTOCOLS.includes(declared)?declared:void 0}function engineName(vendor){return engineNameOverride(vendor)||engineEntry(vendor).displayName}let[defaultEngine,setDefaultEngineState]=import_react76.useState(()=>getGlobalDefaultVendor()??DEFAULT_TASK_VENDOR);function setEngineDefault(vendor){setGlobalDefaultVendor(vendor),kv.set("defaultVendor",vendor),setDefaultEngineState(vendor)}function chooseDefaultEngine(vendor){let off=disabledEngines();if(off.includes(vendor))kv.set("disabledEngineIds",off.filter((id)=>id!==vendor));setEngineDefault(vendor)}async function editEngine(vendor){let next=await RenameTaskDialog.show(dialog,engineCommandText(vendor),{dialogTitle:t("settings.engines.launchCommandTitle",{name:engineName(vendor)}),fieldLabel:t("settings.field.command"),submitLabel:t("settings.action.save"),allowEmpty:!0});if(next===void 0)return;kv.set(engineCommandKey(vendor),next.trim())}async function renameEngine(vendor){let next=await RenameTaskDialog.show(dialog,engineName(vendor),{dialogTitle:t("settings.engines.displayNameTitle",{name:engineName(vendor)}),fieldLabel:t("settings.field.name"),submitLabel:t("settings.action.save"),allowEmpty:!0});if(next===void 0)return;kv.set(engineNameKey(vendor),next.trim())}function resetEngine(vendor){if(kv.set(engineCommandKey(vendor),""),kv.set(engineNameKey(vendor),""),isCustomEngine(vendor))kv.set(engineProtocolKey(vendor),""),kv.set("customEngineIds",customEngines().filter((id)=>id!==vendor)),onEngineListShrunk(engineList().length)}async function addEngineFlow(){let idRaw=await RenameTaskDialog.show(dialog,"",{dialogTitle:t("settings.engines.addTitle"),fieldLabel:t("settings.field.id"),submitLabel:t("settings.action.next"),placeholder:t("settings.engines.idPlaceholder")});if(idRaw===void 0)return;let id=idRaw.trim().toLowerCase();if(!id||isBuiltinVendor(id)||customEngines().includes(id))return;let command=await RenameTaskDialog.show(dialog,"",{dialogTitle:t("settings.engines.addStepTitle",{id}),fieldLabel:t("settings.field.command"),submitLabel:t("settings.action.next"),placeholder:t("settings.engines.commandPlaceholder")});if(command===void 0)return;let protocol=await EngineProtocolPickerDialog.show(dialog,{engineId:id});if(protocol===void 0)return;let name=await RenameTaskDialog.show(dialog,id,{dialogTitle:t("settings.engines.addStepTitle",{id}),fieldLabel:t("settings.field.name"),submitLabel:t("settings.action.add"),allowEmpty:!0});if(kv.set("customEngineIds",[...customEngines(),id]),command.trim())kv.set(engineCommandKey(id),command.trim());if(protocol&&ENGINE_PROTOCOLS.includes(protocol))kv.set(engineProtocolKey(id),protocol);let typedName=name?.trim()??"";kv.set(engineNameKey(id),typedName&&typedName!==id?typedName:humanizeSlug(id))}return{engineList,isCustomEngine,isEngineEnabled,toggleEngineEnabled,engineName,engineProtocol,engineCommandText,engineHasCommandOverride,engineRenamedFromName,engineIsDefault,defaultEngine,setEngineDefault,chooseDefaultEngine,editEngine,renameEngine,resetEngine,addEngineFlow}}var import_react77=__toESM(require_react_production(),1);function installedSpecIds(plugins){let map=new Map;for(let plugin of plugins){if(plugin.linked)continue;map.set(plugin.source.toLowerCase().replace(/^sma1lboy\/rove-plugins\//,"sma1lboy/rove-plugins/"),plugin.id)}return map}function marketplaceRowViews(entries,plugins){let installed=installedSpecIds(plugins);return entries.map((entry2)=>({ref:entry2.ref,desc:entry2.desc,stars:entry2.stars??null,firstParty:entry2.firstParty===!0,installedId:installed.get(entry2.ref.toLowerCase())??null}))}function useAccountProbes(section,vendors){let[statuses,setStatuses]=import_react77.useState(null),key=vendors.join(",");return import_react77.useEffect(()=>{if(section!=="engines"&&section!=="autoRouting")return;let cancelled=!1;return detectEngineStatuses(key?key.split(","):[]).then((s2)=>{if(!cancelled)setStatuses(s2)}),()=>{cancelled=!0}},[section,key]),statuses}function useEngineIntegrations(section,vendors){let[rows,setRows]=import_react77.useState(null),key=vendors.join(","),read2=import_react77.useCallback(()=>{setRows(engineIntegrations(key?key.split(","):[]))},[key]);return import_react77.useEffect(()=>{if(section!=="engines")return;read2()},[section,read2]),{rows,reprobe:read2}}function builtInPlugins(){return BUNDLED_PLUGINS.map((plugin)=>({id:plugin.id,description:plugin.description,pages:plugin.pages.length,enabled:isBundledPluginInstalled(plugin.id)}))}function usePluginSettings(section,dialog){let[rows,setRows]=import_react77.useState([]),t3=useT();import_react77.useEffect(()=>{if(section!=="plugins")return;setRows(readPluginRows(builtInPlugins()))},[section]);function store(pluginId,key,value){try{setPluginSetting(pluginId,key,value)}catch{}setRows(readPluginRows(builtInPlugins()))}return{rows,refresh:()=>setRows(readPluginRows(builtInPlugins())),toggle:(id)=>{let row=rows.find((p3)=>p3.id===id);if(!row)return;let bundled=BUNDLED_PLUGINS.find((plugin)=>plugin.id===id);if(row.builtIn&&bundled){try{setBundledPluginInstalled(bundled.id,!row.enabled)}catch{}registerBundledPlugins(),setRows(readPluginRows(builtInPlugins()));return}try{setPluginEnabled(id,!row.enabled)}catch{}setRows(readPluginRows(builtInPlugins())),loadPluginPages().then(()=>setRows(readPluginRows(builtInPlugins())))},editSetting:async(pluginId,key)=>{let setting=rows.find((p3)=>p3.id===pluginId)?.settings.find((s2)=>s2.key===key);if(!setting)return;if(setting.type==="enum"){store(pluginId,key,nextEnumValue(setting.options,setting.value));return}if(setting.type==="boolean"){store(pluginId,key,toggledBooleanValue(setting));return}let initial=setting.type==="secret"?"":setting.value,next=await RenameTaskDialog.show(dialog,initial,{dialogTitle:setting.label,fieldLabel:key,submitLabel:t3("settings.action.save"),allowEmpty:!0,placeholder:setting.type==="secret"&&setting.value!==""?"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022":setting.defaultValue});if(next===void 0)return;if(setting.type!=="number"){store(pluginId,key,next.trim());return}let numeric=normalizeNumberInput(next);if(numeric===null){await DialogConfirm.show(dialog,t3("settings.plugins.settingInvalidTitle"),t3("settings.plugins.settingInvalidBody",{label:setting.label}),"cancel");return}store(pluginId,key,numeric)}}}function useMarketplace(section,dialog,plugins){let t3=useT(),[entries,setEntries]=import_react77.useState(null),[offline,setOffline]=import_react77.useState(!1),[status,setStatus]=import_react77.useState(""),busy=import_react77.useRef(!1);import_react77.useEffect(()=>{if(section!=="marketplace")return;let cancelled=!1;return setEntries(null),fetchMarketplace().then((result)=>{if(cancelled)return;setEntries(result.entries),setOffline(result.offline)}),()=>{cancelled=!0}},[section]);function previewMessage(preview){let lines=[`${preview.name} (${preview.id}) v${preview.version}`];if(preview.description)lines.push(preview.description);if(lines.push(t3("settings.marketplace.previewSource",{source:preview.source}),""),preview.commands.length===0)lines.push(t3("settings.marketplace.previewNoCommands"));else{lines.push(t3("settings.marketplace.previewCommands"));for(let command of preview.commands)lines.push(` ${command}`)}for(let warning of preview.warnings)lines.push(t3("settings.marketplace.previewWarning",{warning}));return lines.push("",t3("settings.marketplace.previewTrust")),lines.join(`
70
- `)}return{rows:marketplaceRowViews(entries??[],plugins.rows),loading:entries===null,offline,status,install:async(ref)=>{if(busy.current)return;let already=installedSpecIds(plugins.rows).get(ref.toLowerCase());if(already){setStatus(t3("settings.marketplace.alreadyInstalled",{id:already}));return}busy.current=!0,setStatus(t3("settings.marketplace.preparing",{ref}));try{let prepared=await preparePluginInstall(ref);if(await DialogConfirm.show(dialog,t3("settings.marketplace.confirmTitle",{name:prepared.preview.name}),previewMessage(prepared.preview),void 0,t3("settings.marketplace.confirmInstall"),{danger:!0,size:"medium"})!==!0){prepared.discard(),setStatus(t3("settings.marketplace.cancelled"));return}setStatus(t3("settings.marketplace.installing",{name:prepared.preview.name}));let id=await prepared.commit();reloadPluginEngines(),plugins.refresh(),setStatus(t3("settings.marketplace.installed",{id,version:prepared.preview.version}))}catch(err){setStatus(t3("settings.marketplace.failed",{error:errorMessage(err)}))}finally{busy.current=!1}}}}import{accessSync,constants as fsConstants,mkdirSync}from"fs";function useSettingsPrefs(kv,dialog){let t3=useT();function toastEnabled(){return kv.get("notifications.toast.enabled",!0)!==!1}function soundEnabled(){return kv.get("notifications.sound.enabled",!0)!==!1}function toggleToast(){kv.set("notifications.toast.enabled",!toastEnabled())}function toggleSound(){kv.set("notifications.sound.enabled",!soundEnabled())}function soundVolume(){return normalizeSoundVolume(kv.get(SOUND_VOLUME_KEY,DEFAULT_SOUND_VOLUME))}function cycleSoundVolume(){kv.set(SOUND_VOLUME_KEY,nextSoundVolume(soundVolume()))}function crossTaskEnabled(){return kv.get("notifications.crossTask.enabled",!0)!==!1}function toggleCrossTask(){kv.set("notifications.crossTask.enabled",!crossTaskEnabled())}function finishedAlertsEnabled(){return kv.get(FINISHED_ALERTS_KEY,!0)!==!1}function toggleFinishedAlerts(){kv.set(FINISHED_ALERTS_KEY,!finishedAlertsEnabled())}function prefixTapPresentation(){return normalizePrefixTapPresentation(kv.get(PREFIX_TAP_PRESENTATION_KEY))}function selectPrefixTapPresentation(next){kv.set(PREFIX_TAP_PRESENTATION_KEY,next)}function splitStyle(){return normalizeSplitStyle(kv.get(SPLIT_STYLE_KEY))}function selectSplitStyle(style){kv.set(SPLIT_STYLE_KEY,style)}function zenDefaultOn(){return kv.get(ZEN_ACTIVE_KEY,ZEN_DEFAULT)===!0}function toggleZenDefaultOn(){kv.set(ZEN_ACTIVE_KEY,!zenDefaultOn())}function updateChannel(){return normalizeReleaseChannel(kv.get(UPDATE_CHANNEL_KEY))??channelOf()}function toggleUpdateChannel(){kv.set(UPDATE_CHANNEL_KEY,updateChannel()==="nightly"?"latest":"nightly")}function tabStripMode(){return resolveTabStripMode(kv.get(TAB_STRIP_MODE_KEY,void 0),kv.get(TAB_STRIP_HIDE_SINGLE_KEY,void 0))}function cycleTabStripMode(){let next=TAB_STRIP_MODES[(TAB_STRIP_MODES.indexOf(tabStripMode())+1)%TAB_STRIP_MODES.length];kv.set(TAB_STRIP_MODE_KEY,next)}function remoteProjectsEnabled(){return kv.get("experimental.remoteProjects",!1)===!0}function toggleRemoteProjects(){kv.set("experimental.remoteProjects",!remoteProjectsEnabled())}function autoStatusOn(){return kv.get(AUTO_STATUS_KEY,!1)===!0}function toggleAutoStatus(){kv.set(AUTO_STATUS_KEY,!autoStatusOn())}function dispatcherOn(){return kv.get(DISPATCHER_KEY,!1)===!0}function toggleDispatcher(){kv.set(DISPATCHER_KEY,!dispatcherOn())}function railFoldStyle(){let raw=kv.get(RAIL_FOLD_STYLE_KEY,DEFAULT_COLLAPSED_RAIL_STYLE);return COLLAPSED_RAIL_STYLES.includes(raw)?raw:DEFAULT_COLLAPSED_RAIL_STYLE}function selectRailFoldStyle(style){kv.set(RAIL_FOLD_STYLE_KEY,style)}function workingBorder(){return normalizeWorkingBorder(kv.get(WORKING_BORDER_KEY,DEFAULT_WORKING_BORDER))}function selectWorkingBorder(style){kv.set(WORKING_BORDER_KEY,style)}function taskColors(){return normalizeTaskColors(kv.get(TASK_COLORS_KEY,DEFAULT_TASK_COLORS))}function selectTaskColors(value){kv.set(TASK_COLORS_KEY,value)}function glyphSet(){return normalizeGlyphSet(kv.get(GLYPH_SET_KEY,DEFAULT_GLYPH_SET))}function selectGlyphSet(name){kv.set(GLYPH_SET_KEY,name)}function colorblind(){return normalizeColorblind(kv.get(COLORBLIND_KEY,DEFAULT_COLORBLIND))}function selectColorblind(mode){kv.set(COLORBLIND_KEY,mode)}function runningTitle(){return normalizeRunningTitle(kv.get(RUNNING_TITLE_KEY,DEFAULT_RUNNING_TITLE))}function selectRunningTitle(style){kv.set(RUNNING_TITLE_KEY,style)}function editorKind(){return normalizeEditorKind(kv.get(EDITOR_KIND_KEY,DEFAULT_EDITOR_KIND))}function cycleEditorKind(){let i2=EDITOR_KINDS.indexOf(editorKind()),next=EDITOR_KINDS[(i2+1)%EDITOR_KINDS.length];if(next)kv.set(EDITOR_KIND_KEY,next)}function editorCustomCommand(){let v3=kv.get(EDITOR_CUSTOM_KEY,"");return typeof v3==="string"?v3:""}async function editEditorCustom(){let next=await RenameTaskDialog.show(dialog,editorCustomCommand(),{dialogTitle:t3("settings.general.editorCustomTitle"),fieldLabel:t3("settings.field.command"),submitLabel:t3("settings.action.save"),allowEmpty:!0});if(next===void 0)return;let cmd=next.trim();if(kv.set(EDITOR_CUSTOM_KEY,cmd),cmd)kv.set(EDITOR_KIND_KEY,"custom")}function scrollbackRows(){return normalizeScrollbackRows(kv.get(SCROLLBACK_ROWS_KEY,DEFAULT_SCROLLBACK_ROWS))}async function editScrollbackRows(){let next=await RenameTaskDialog.show(dialog,String(scrollbackRows()),{dialogTitle:t3("settings.general.scrollbackTitle"),fieldLabel:t3("settings.general.scrollbackField"),submitLabel:t3("settings.action.save"),placeholder:String(DEFAULT_SCROLLBACK_ROWS)});if(next===void 0)return;let n2=Number.parseInt(next.trim(),10);if(!Number.isFinite(n2)){await DialogConfirm.show(dialog,t3("settings.general.scrollbackInvalidTitle"),t3("settings.general.scrollbackInvalidBody"),"cancel");return}kv.set(SCROLLBACK_ROWS_KEY,normalizeScrollbackRows(n2))}function worktreeBasePath(){let v3=kv.get(WORKTREE_BASE_KEY,"");return typeof v3==="string"?v3:""}let worktreeKind=()=>worktreeBaseKindOf(worktreeBasePath());function worktreeKindLabel(){let kind=worktreeKind();if(kind==="default")return t3("settings.general.worktreeKindDefault");if(kind==="nextToProject")return t3("settings.general.worktreeKindNext");return t3("settings.general.worktreeKindCustom")}function worktreeCustomPath(){let v3=kv.get(WORKTREE_BASE_CUSTOM_KEY,"");return(typeof v3==="string"?v3.trim():"")||(worktreeKind()==="custom"?worktreeBasePath().trim():"")}function cycleWorktreeBase(){let kind=worktreeKind();if(kind==="default")kv.set(WORKTREE_BASE_KEY,PROJECT_SIBLING_BASE);else if(kind==="nextToProject")kv.set(WORKTREE_BASE_KEY,worktreeCustomPath());else kv.set(WORKTREE_BASE_CUSTOM_KEY,worktreeBasePath().trim()),kv.set(WORKTREE_BASE_KEY,"")}async function editWorktreeCustom(){let next=await RenameTaskDialog.show(dialog,worktreeCustomPath(),{dialogTitle:t3("settings.general.worktreeBaseTitle"),fieldLabel:t3("settings.general.worktreeBaseField"),submitLabel:t3("settings.action.save"),placeholder:`${PROJECT_DIR_TOKEN}/../worktrees`,allowEmpty:!0});if(next===void 0)return;let raw=next.trim();if(raw.includes(PROJECT_DIR_TOKEN)){if(!hasProjectDirToken(raw)){await DialogConfirm.show(dialog,t3("settings.general.worktreeBaseInvalidTitle"),t3("settings.general.worktreeBaseTokenBody",{token:PROJECT_DIR_TOKEN}),"cancel");return}}else if(raw){let resolved=normalizeWorktreeBase(raw)??raw;try{mkdirSync(resolved,{recursive:!0}),accessSync(resolved,fsConstants.W_OK)}catch(err){await DialogConfirm.show(dialog,t3("settings.general.worktreeBaseInvalidTitle"),t3("settings.general.worktreeBaseUnusableBody",{path:resolved,error:errorMessage(err)}),"cancel");return}}if(kv.set(WORKTREE_BASE_CUSTOM_KEY,raw),raw)kv.set(WORKTREE_BASE_KEY,raw);else if(worktreeKind()==="custom")kv.set(WORKTREE_BASE_KEY,"")}return{toastEnabled,toggleToast,soundEnabled,soundVolume,cycleSoundVolume,toggleSound,crossTaskEnabled,finishedAlertsEnabled,toggleFinishedAlerts,toggleCrossTask,prefixTapPresentation,selectPrefixTapPresentation,splitStyle,selectSplitStyle,zenDefaultOn,toggleZenDefaultOn,updateChannel,toggleUpdateChannel,railFoldStyle,selectRailFoldStyle,workingBorder,selectWorkingBorder,taskColors,selectTaskColors,glyphSet,selectGlyphSet,colorblind,selectColorblind,runningTitle,selectRunningTitle,remoteProjectsEnabled,toggleRemoteProjects,autoStatusOn,toggleAutoStatus,dispatcherOn,toggleDispatcher,editorKind,cycleEditorKind,editorCustomCommand,editEditorCustom,scrollbackRows,editScrollbackRows,tabStripMode,cycleTabStripMode,worktreeKind,worktreeKindLabel,worktreeCustomPath,cycleWorktreeBase,editWorktreeCustom}}var EMPTY_USAGE_SIGNAL=createStateCell(null);function SettingsDialog(props){let dialog=useDialog(),themeCtx=useTheme(),renderer=useRenderer(),{theme}=themeCtx,t3=useT(),padX=useDialogPaddingX(),[level,setLevel]=import_react79.useState("sidebar"),[section,setSection]=import_react79.useState(props.initialSection??"general"),[cursor,setCursor]=import_react79.useState(()=>Math.max(0,SECTIONS.findIndex((s2)=>s2.id===section))),[bodyRow,setBodyRow]=import_react79.useState(0),[feedbackTitle,setFeedbackTitle]=import_react79.useState(""),[feedbackBody,setFeedbackBody]=import_react79.useState(""),[feedbackStatus,setFeedbackStatus]=import_react79.useState(""),[reloadStatus,setReloadStatus]=import_react79.useState(""),hasDaemon=hasRestartableDaemon(props.orchestrator),remote2=props.orchestrator instanceof RemoteOrchestrator?props.orchestrator:null,prefs=useSettingsPrefs(props.kv,dialog),appearance=useAppearanceSettings(props.kv,dialog,prefs),engines=useEngineSettings(props.kv,dialog,(max)=>setBodyRow((r6)=>Math.max(0,Math.min(r6,max)))),usage=useAccessor(remote2?remote2.usageSnapshotSignal():EMPTY_USAGE_SIGNAL),engineStatuses=useAccountProbes(section,engines.engineList()),integrations=useEngineIntegrations(section,engines.engineList()),needsHookInstall=enginesNeedingHookInstall(integrations.rows??[]),hooksInstalled=enginesWithHooksInstalled(integrations.rows??[]);async function runHookInstall(){await installEngineHooks(),integrations.reprobe()}async function runHookUninstall(){await uninstallEngineHooks(),integrations.reprobe()}let[skillError,setSkillError]=import_react79.useState(null);function runSkillInstall(){setSkillError(installSkillNow()),integrations.reprobe()}let autoRouting=useAutoRoutingSettings(props.kv,dialog,engines.engineList,engineStatuses),classifier=useClassifierSettings(props.kv,dialog,section==="autoRouting"),[keysFileExists,setKeysFileExists]=import_react79.useState(()=>userKeybindingsReport().exists);function createKeysFile(){try{createKeybindingsFile(userKeybindingsReport().path),reloadUserKeybindings()}catch{}setKeysFileExists(userKeybindingsReport().exists)}let plugins=usePluginSettings(section,dialog),marketplace=useMarketplace(section,dialog,plugins);function bodyRows(){return sectionRows(section,{engineList:engines.engineList(),plugins:plugins.rows.map((p3)=>({id:p3.id,settingKeys:p3.settings.map((s2)=>s2.key)})),marketplace:marketplace.rows.map((r6)=>r6.ref),hasDaemon,keybindingsFileExists:keysFileExists})}function bodyRowCount(){return bodyRows().length}function selectLanguage(locale){if(currentLang()===locale)return;setLocaleLang(locale),props.kv.set(LOCALE_KEY,locale)}function currentEngineRow(){if(section!=="engines"||level!=="body")return null;let row=rowAt(bodyRows(),bodyRow);return row?.kind==="engine"?row.vendor:null}async function sendFeedback(){setFeedbackStatus("submitting...");try{let result=submitFeedback({title:feedbackTitle,body:feedbackBody});setFeedbackStatus(`sent: ${result.url}`),setFeedbackTitle(""),setFeedbackBody(""),setBodyRow(0)}catch(err){setFeedbackStatus(`error: ${errorMessage(err)}
71
- ${failureHint(err)}`)}}let editingFeedback=section==="feedback"&&level==="body";function feedbackFieldStep(delta){let next=bodyRow+delta;if(next<0||next>2){setLevel("sidebar");return}setBodyRow(next)}function enterBody(){if(level!=="sidebar"||bodyRowCount()===0)return;setLevel("body"),setBodyRow(0)}function moveCursor(delta){if(level==="sidebar"){let next=(cursor+delta+SECTIONS.length)%SECTIONS.length;setCursor(next);let nextSection=SECTIONS[next];if(nextSection)setSection(nextSection.id),setBodyRow(0);return}let len=bodyRowCount();if(len===0)return;setBodyRow((bodyRow+delta+len)%len)}function switchSection(id){setSection(id),setCursor(SECTIONS.findIndex((s2)=>s2.id===id)),setBodyRow(0),setLevel("sidebar")}let rowActivators={appearance:(row)=>appearance.open(row.setting),language:(row)=>selectLanguage(row.locale),toast:()=>prefs.toggleToast(),sound:()=>prefs.toggleSound(),soundVolume:()=>prefs.cycleSoundVolume(),crossTask:()=>prefs.toggleCrossTask(),finishedAlerts:()=>prefs.toggleFinishedAlerts(),keyHints:()=>toggleKeyHints(props.kv),prefixTapPresentation:(row)=>prefs.selectPrefixTapPresentation(row.presentation),zenDefaultOn:()=>prefs.toggleZenDefaultOn(),updateChannel:()=>prefs.toggleUpdateChannel(),updateTry:()=>void confirmTryChannel(dialog,renderer,tryOutChannel()),updateCheck:()=>props.onCheckUpdate?.(),editorKind:()=>prefs.cycleEditorKind(),editorCustom:()=>void prefs.editEditorCustom(),worktreeBase:()=>prefs.cycleWorktreeBase(),worktreeCustom:()=>void prefs.editWorktreeCustom(),scrollbackRows:()=>void prefs.editScrollbackRows(),tabStripHideSingle:()=>prefs.cycleTabStripMode(),engine:(row)=>void engines.editEngine(row.vendor),engineAdd:()=>void engines.addEngineFlow(),engineHooksInstall:()=>void runHookInstall(),engineHooksUninstall:()=>void runHookUninstall(),engineSkillInstall:()=>runSkillInstall(),autoRoutingTier:(row)=>void autoRouting.edit(row.tier),autoRoutingClassifier:()=>classifier.cycle(),autoRoutingClassifierEndpoint:()=>void classifier.editEndpoint(),autoRoutingClassifierThreshold:()=>void classifier.editThreshold(),autoRoutingClassifierKey:()=>void classifier.editKey(),keysCreate:()=>createKeysFile(),pluginToggle:(row)=>plugins.toggle(row.pluginId),pluginSetting:(row)=>void plugins.editSetting(row.pluginId,row.key),pluginInstall:(row)=>void marketplace.install(row.ref),feedbackTitle:()=>setBodyRow(0),feedbackBody:()=>setBodyRow(1),feedbackSend:()=>void sendFeedback(),devReset:()=>void confirmResetState(dialog,props.kv,renderer),devRestartDaemon:()=>void confirmRestartDaemon(dialog,props.orchestrator,renderer),devReloadSettings:()=>setReloadStatus(reloadSettingsStatus(props.kv)),devRemoteProjects:()=>prefs.toggleRemoteProjects(),devAutoStatus:()=>prefs.toggleAutoStatus(),devDispatcher:()=>prefs.toggleDispatcher()};function activateBodyRow(){let row=rowAt(bodyRows(),bodyRow);if(!row)return;rowActivators[row.kind](row)}useBindings(()=>({enabled:dialog.stack.length===0&&!editingFeedback,bindings:[{key:"down",cmd:()=>moveCursor(1)},{key:"up",cmd:()=>moveCursor(-1)},{key:"j",cmd:()=>moveCursor(1)},{key:"k",cmd:()=>moveCursor(-1)},{key:"tab",cmd:()=>moveCursor(1)},{key:"right",cmd:enterBody},{key:"l",cmd:enterBody},{key:"left",cmd:()=>setLevel("sidebar")},{key:"h",cmd:()=>setLevel("sidebar")},{key:"return",cmd:()=>{if(level==="sidebar"){enterBody();return}activateBodyRow()}},{key:"r",cmd:()=>{let v3=currentEngineRow();if(v3)engines.renameEngine(v3)}},{key:"x",cmd:()=>{let v3=currentEngineRow();if(v3)engines.resetEngine(v3)}},{key:"d",cmd:()=>{let v3=currentEngineRow();if(v3)engines.chooseDefaultEngine(v3)}},{key:"space",cmd:()=>{let v3=currentEngineRow();if(v3)engines.toggleEngineEnabled(v3)}}]})),useBindings(()=>({enabled:editingFeedback,bindings:[{key:"tab",cmd:()=>feedbackFieldStep(1)},{key:"shift+tab",cmd:()=>feedbackFieldStep(-1)}]})),useBindings(()=>({enabled:editingFeedback&&bodyRow===2,bindings:[{key:"return",cmd:()=>void sendFeedback()}]}));let follow=useCursorFollow3(level==="body"?bodyRow:-1),cursorProps={level,bodyRow,setLevel,setBodyRow,rowRef:follow.rowRef},navHint=$jsx("box",{paddingTop:0,children:$jsx("text",{fg:theme.textMuted,children:editingFeedback?t3("settings.nav.feedback"):t3("settings.nav.default")})}),body=$jsxs("box",{paddingLeft:padX,paddingRight:padX,paddingBottom:1,gap:1,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",children:[$jsx("text",{attributes:TextAttributes39.BOLD,fg:theme.text,children:t3("settings.title")}),$jsx("text",{fg:theme.textMuted,onMouseUp:()=>props.onClose(),children:t3("settings.esc")})]}),$jsxs("box",{flexDirection:"row",gap:2,children:[$jsx(SettingsSectionSidebar,{level,cursor,switchSection}),$jsxs("box",{flexGrow:1,flexShrink:1,flexDirection:"column",gap:1,children:[section==="general"?$jsx(GeneralSettingsSection,{...cursorProps,prefs,appearance,currentLocale:currentLang(),selectLanguage,onCheckUpdate:props.onCheckUpdate,usage}):null,section==="engines"?$jsx(EngineSettingsSection,{...cursorProps,vendors:engines.engineList(),statuses:engineStatuses,isCustom:engines.isCustomEngine,engineProtocol:engines.engineProtocol,isEnabled:engines.isEngineEnabled,toggleEngine:engines.toggleEngineEnabled,chooseDefault:engines.chooseDefaultEngine,displayName:engines.engineName,renamedFrom:engines.engineRenamedFromName,commandText:engines.engineCommandText,hasCommandOverride:engines.engineHasCommandOverride,isDefaultEngine:(v3)=>engines.defaultEngine===v3,editEngine:(v3)=>void engines.editEngine(v3),onAddEngine:()=>void engines.addEngineFlow(),integrations:integrations.rows,needsHookInstall,hooksInstalled,onInstallHooks:()=>void runHookInstall(),onUninstallHooks:()=>void runHookUninstall(),skillError,onInstallSkill:runSkillInstall}):null,section==="autoRouting"?$jsx(AutoRoutingSettingsSection,{...cursorProps,autoRouting,classifier}):null,section==="plugins"?$jsx(PluginSettingsSection,{...cursorProps,plugins:plugins.rows,toggle:plugins.toggle,editSetting:(id,key)=>void plugins.editSetting(id,key)}):null,section==="marketplace"?$jsx(MarketplaceSettingsSection,{...cursorProps,rows:marketplace.rows,loading:marketplace.loading,offline:marketplace.offline,status:marketplace.status,install:(ref)=>void marketplace.install(ref)}):null,section==="keys"?$jsx(KeybindingsSettingsSection,{...cursorProps,prefs,onCreateFile:createKeysFile}):null,section==="feedback"?$jsx(FeedbackSettingsSection,{...cursorProps,title:feedbackTitle,setTitle:(v3)=>{setFeedbackTitle(v3),setFeedbackStatus("")},body:feedbackBody,setBody:(v3)=>{setFeedbackBody(v3),setFeedbackStatus("")},status:feedbackStatus,onTitleSubmit:()=>setBodyRow(1),submit:()=>void sendFeedback()}):null,section==="dev"?$jsx(DevSettingsSection,{...cursorProps,prefs,hasDaemon,confirmReset:()=>void confirmResetState(dialog,props.kv,renderer),confirmRestartDaemon:()=>void confirmRestartDaemon(dialog,props.orchestrator,renderer),reloadSettings:()=>setReloadStatus(reloadSettingsStatus(props.kv)),reloadStatus}):null]})]})]});return $jsxs("box",{flexDirection:"column",flexGrow:1,children:[$jsx("scrollbox",{ref:follow.scrollRef,flexGrow:1,flexShrink:1,flexBasis:0,verticalScrollbarOptions:{trackOptions:{foregroundColor:"transparent"}},children:body}),$jsx("box",{paddingLeft:padX,paddingRight:padX,children:navHint})]})}import{TextAttributes as TextAttributes40}from"@opentui/core";var import_react81=__toESM(require_react_production(),1);function systemOpenArgv(absPath,platform=process.platform){if(platform==="darwin")return["open",absPath];if(platform==="win32")return["cmd","/c","start","",absPath];return["xdg-open",absPath]}function openWithSystemViewer(absPath){let[cmd,...args]=systemOpenArgv(absPath);return spawnDetached(cmd??"",args)}function UpdatePage(props){let{theme}=useTheme(),t3=useT(),renderer=useRenderer(),[info,setInfo]=import_react81.useState(null),[checked,setChecked]=import_react81.useState(!1),[releaseNotes,setReleaseNotes]=import_react81.useState([]),[loadingNotes,setLoadingNotes]=import_react81.useState(!0),[selected,setSelected]=import_react81.useState("close"),[status,setStatus]=import_react81.useState(null),[channel]=import_react81.useState(()=>preferredReleaseChannel()),command=updateCommandFor(channel),latest=info?.latest??CURRENT_VERSION,latestUnknown=checked&&info===null,hasUpdate=info?.hasUpdate===!0,upToDate=checked&&info!==null&&!hasUpdate,releaseUrl=releaseNotes[0]?.url??releasePageUrl(latest),actions=[...hasUpdate?[{id:"update",key:"U",label:t3("update.actions.updateNow"),detail:command}]:[],{id:"release",key:"R",label:t3("update.actions.openRelease"),detail:releaseUrl??t3("update.releaseUrlUnavailable")},{id:"close",key:"Q",label:t3("update.actions.close"),detail:t3("update.actions.closeDetail")}];import_react81.useEffect(()=>{load()},[]);async function load(){let next=await checkLatestVersion({force:!0,channel});if(setInfo(next),setChecked(!0),next?.hasUpdate)setSelected("update");let fetched=next?.hasUpdate?await fetchReleaseNotesRange({current:CURRENT_VERSION,latest:next.latest,locale:currentLang()}):[];setReleaseNotes(fetched),setLoadingNotes(!1)}function move(delta){let ids=actions.map((a2)=>a2.id),next=(ids.indexOf(selected)+delta+ids.length)%ids.length;setSelected(ids[next]??"close")}function activate(id=selected){if(id==="close"){props.onClose();return}if(id==="update"&&!hasUpdate)return;if(id==="release"){setStatus(openWithSystemViewer(releaseUrl)?t3("update.statusReleaseOpened"):t3("update.statusReleaseError"));return}runUpdater()}async function runUpdater(){setStatus(t3("update.statusRunningUpdater")),await new Promise((resolve2)=>setTimeout(resolve2,30)),await runShellUpdater({renderer,t:t3,targetLabel:latest,command})}return useBindings(()=>({bindings:[{key:"up",cmd:()=>move(-1)},{key:"down",cmd:()=>move(1)},{key:"k",cmd:()=>move(-1)},{key:"j",cmd:()=>move(1)},{key:"return",cmd:()=>activate()},{key:"u",cmd:()=>activate("update")},{key:"r",cmd:()=>activate("release")},...pageCloseBindings(()=>activate("close"))]})),$jsxs("box",{flexDirection:"column",flexGrow:1,backgroundColor:theme.background,paddingTop:1,paddingLeft:2,paddingRight:2,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",flexShrink:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes40.BOLD,wrapMode:"none",children:t3("update.pageTitle")}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",onMouseUp:()=>activate("close"),children:t3("update.closeHint")})]}),$jsxs("box",{flexDirection:"row",gap:2,flexShrink:0,paddingTop:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("update.current")}),$jsxs("text",{fg:theme.text,attributes:TextAttributes40.BOLD,wrapMode:"none",children:["v",CURRENT_VERSION]}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("update.latest")}),latestUnknown?$jsx("text",{fg:theme.textMuted,attributes:TextAttributes40.BOLD,wrapMode:"none",children:t3("update.latestUnknown")}):$jsxs("text",{fg:hasUpdate?theme.warning:theme.success,attributes:TextAttributes40.BOLD,wrapMode:"none",children:["v",latest]})]}),latestUnknown?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("update.registryRetry")}):null,upToDate?$jsx("box",{flexShrink:0,paddingTop:1,children:$jsx("text",{fg:theme.success,wrapMode:"word",children:t3("update.upToDate")})}):null,$jsx("box",{flexDirection:"column",flexShrink:0,paddingTop:1,gap:0,children:actions.map((action)=>{let cursor=selected===action.id,chrome=resolveRowSelectionChrome2(theme,{cursor});return $jsxs("box",{flexDirection:"row",gap:0,backgroundColor:chrome.backgroundColor,onMouseUp:()=>activate(action.id),children:[$jsx("text",{fg:chrome.markerColor,wrapMode:"none",children:chrome.marker}),$jsxs("box",{flexDirection:"row",gap:1,flexGrow:1,paddingLeft:1,paddingRight:1,children:[$jsx("box",{width:4,flexShrink:0,children:$jsxs("text",{fg:theme.accent,attributes:TextAttributes40.BOLD,wrapMode:"none",children:["[",action.key,"]"]})}),$jsx("box",{width:14,flexShrink:0,children:$jsx("text",{fg:theme.text,attributes:cursor?TextAttributes40.BOLD:void 0,wrapMode:"none",children:action.label})}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:action.detail})]})]},action.id)})}),status?$jsx("text",{fg:theme.info,wrapMode:"word",children:status}):null,hasUpdate?$jsx("box",{flexShrink:0,paddingTop:1,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes40.DIM,wrapMode:"none",children:t3("update.changesSectionHeader",{from:CURRENT_VERSION,to:latest})})}):null,$jsx("scrollbox",{flexGrow:1,flexShrink:1,stickyScroll:!1,verticalScrollbarOptions:{trackOptions:{foregroundColor:"transparent"}},children:$jsxs("box",{flexDirection:"column",paddingRight:1,paddingBottom:1,gap:0,children:[loadingNotes?$jsx("text",{fg:theme.textMuted,children:t3("update.loadingNotes")}):null,!loadingNotes&&hasUpdate&&releaseNotes.length===0?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("update.notesUnavailable")}):null,releaseNotes.map((release)=>$jsxs("box",{flexDirection:"column",paddingBottom:1,gap:0,children:[$jsxs("text",{fg:theme.text,attributes:TextAttributes40.BOLD,wrapMode:"none",children:["v",release.version]}),$jsx(ReleaseNotesBody,{body:release.body})]},release.version))]})})]})}import{TextAttributes as TextAttributes41}from"@opentui/core";var import_react82=__toESM(require_react_production(),1);var LAND_CONFLICT_RE=/LAND_CONFLICT/,MAIN_DIRTY_RE=/MAIN_CHECKOUT_DIRTY/;async function landTaskAction(deps,taskId,branchLabel){let{t:t3}=deps,preflight;try{preflight=await deps.orchestrator.landPreflight(taskId)}catch(err){return deps.notifyError(t3("worktrees.land.failed",{error:err instanceof Error?err.message:String(err)})),console.error("[rove land] preflight failed:",err),!1}if(preflight.refusal){if(preflight.refusal==="MAIN_CHECKOUT_DIRTY")deps.notifyNeedsInput(t3("worktrees.land.dirtyBase"));else deps.notifyError(t3("worktrees.land.failed",{error:preflight.message??preflight.refusal}));return!1}let body=t3(preflight.ahead===1?"worktrees.land.confirmBodyOne":"worktrees.land.confirmBody",{branch:branchLabel,landedOn:preflight.landedOn,commits:preflight.ahead??"?"});if(!await deps.confirm(body))return!1;try{let res=await deps.orchestrator.landTask(taskId,{callerCwd:deps.callerCwd});deps.notifyInfo(t3("worktrees.land.done",{branch:res.branch,landedOn:res.landedOn,commit:res.commit}));let cleanup=res.worktree;if(cleanup&&!cleanup.removed)deps.notifyNeedsInput(t3("worktrees.land.worktreeKept",{reason:cleanup.reason??"refused"}));else if(cleanup?.reason)deps.notifyNeedsInput(t3("worktrees.land.worktreePathStale",{reason:cleanup.reason}));if(cleanup?.residue)deps.notifyNeedsInput(t3("worktrees.land.worktreeResidue",{path:cleanup.residue.path,reason:cleanup.residue.reason}));return!0}catch(err){let msg=err instanceof Error?err.message:String(err);if(LAND_CONFLICT_RE.test(msg))deps.notifyNeedsInput(t3("worktrees.land.conflict",{files:msg}));else if(MAIN_DIRTY_RE.test(msg))deps.notifyNeedsInput(t3("worktrees.land.dirtyBase"));else deps.notifyError(t3("worktrees.land.failed",{error:msg}));return console.error("[rove land] failed:",err),!1}}function flattenRows(projects){return projects.flatMap((p3)=>p3.worktrees)}function taskIdForPath(orch,wtPath){let norm=(p3)=>p3.replace(/^\/private\//,"/");return orch.listTasks().find((task)=>task.worktreePath&&samePath(norm(task.worktreePath),norm(wtPath)))?.id}function WorktreesPage(props){let{theme}=useTheme(),dialog=useDialog(),t3=useT(),notif=useNotifications();function notifyError(message){notif.notify({kind:"error",taskId:"",tabId:"",title:message})}function notifyNeedsInput(message){notif.notify({kind:"needs_input",taskId:"",tabId:"",title:message})}function notifyInfo(message){notif.notify({kind:"done",taskId:"",tabId:"",title:message})}let[projects,setProjects]=import_react82.useState(null),[reloadTick,setReloadTick]=import_react82.useState(0),refetch=()=>setReloadTick((tick3)=>tick3+1);import_react82.useEffect(()=>{let disposed=!1,fullLanded=!1,orch=props.orchestrator;if(!orch){setProjects([]);return}return orch.listWorktrees({network:!1}).then((rows)=>{if(!disposed&&!fullLanded)setProjects(rows)}).catch(()=>{}),orch.listWorktrees().then((rows)=>{if(fullLanded=!0,disposed)return;setProjects(rows);let live=new Set(flattenRows(rows).map((r6)=>r6.path));setRemovingPaths((paths)=>paths.filter((p3)=>live.has(p3)))}).catch(()=>{}),()=>{disposed=!0}},[props.orchestrator,reloadTick]);let[removingPaths,setRemovingPaths]=import_react82.useState([]),visibleProjects=(projects??[]).map((p3)=>({...p3,worktrees:p3.worktrees.filter((w4)=>!removingPaths.includes(w4.path))})),flatRows=flattenRows(visibleProjects),[cursor,setCursor]=import_react82.useState(0);import_react82.useEffect(()=>{setCursor((c2)=>clampCursor2(c2,flatRows.length))},[flatRows.length]);let follow=useCursorFollow3(cursor),[busyPath,setBusyPath]=import_react82.useState(null);async function deleteInBackground(row,force){let orch=props.orchestrator;if(!orch)return;setRemovingPaths((paths)=>[...paths,row.path]);try{let residue=await orch.removeWorktree(row.path,force);if(residue)notifyNeedsInput(t3("worktrees.delete.residue",{path:residue.path,reason:residue.reason}));refetch()}catch(err){setRemovingPaths((paths)=>paths.filter((p3)=>p3!==row.path));let reason=force?null:dirtyRefusalReason(err);if(reason!==null){if(await DialogConfirm.show(dialog,t3("worktrees.delete.forceTitle"),`${t3("worktrees.delete.forceBody",{branch:row.branch||row.path})}
68
+ `),process.exit(1);process.exit(result.status??0)}import{TextAttributes as TextAttributes19}from"@opentui/core";function BannerStrip(props){let{theme}=useTheme(),ruleWidth=Math.max(4,props.width-2);return $jsxs("box",{flexDirection:"column",flexShrink:0,paddingLeft:1,paddingRight:1,paddingBottom:1,onMouseUp:props.onPress,children:[$jsx("text",{fg:props.tone,wrapMode:"none",children:"\u2594".repeat(ruleWidth)}),$jsx("box",{flexDirection:"row",gap:1,children:$jsx("text",{fg:props.tone,attributes:TextAttributes19.BOLD,wrapMode:"none",children:props.title})}),$jsx("box",{flexDirection:"row",gap:1,children:$jsx("text",{fg:theme.text,wrapMode:"word",children:props.hint})})]})}function VersionSkewBanner(props){let{theme}=useTheme(),t3=useT();if(!props.stale)return null;let params={daemon:props.daemonVersion?`v${props.daemonVersion}`:t3("update.skew.olderBuild"),clientVersion:props.clientVersion},hint=props.refreshChord?t3("update.skew.hint",{...params,keys:props.refreshChord}):t3("update.skew.hintNoKey",params);return $jsx(BannerStrip,{tone:theme.warning,title:t3("update.skew.title"),hint,width:props.width})}function StaleInstallBanner(props){let{theme}=useTheme(),t3=useT();if(!props.message)return null;return $jsx(BannerStrip,{tone:theme.error,title:t3("update.staleInstall.title"),hint:t3("update.staleInstall.hint"),width:props.width})}function SkillBanner(props){let{theme}=useTheme(),t3=useT();if(props.engines.length===0)return null;let hint=props.error?t3("settings.engines.skill.failed",{reason:props.error}):t3("settings.engines.skill.bannerHint",{engines:props.engines.join(", ")});return $jsx(BannerStrip,{tone:props.error?theme.error:theme.primary,title:t3("settings.engines.skill.bannerTitle"),hint,width:props.width,onPress:props.onInstall})}function useHostBanner(orch,width){let daemonStale=useAccessor(orch.daemonStaleSignal()),daemonVersion=useAccessor(orch.daemonVersionSignal()),update=useAccessor(orch.updateSignal()),notify=updateNotifyEnabled(useKV().get(UPDATE_NOTIFY_KEY)),staleInstall=useAccessor(orch.staleInstallSignal()),daemonRestarting=useAccessor(orch.daemonRestartingSignal()),missingSkill=useAccessor(skillMissing),[skillError,setSkillError]=import_react51.useState(null),inputs={daemonVersion,clientVersion:CURRENT_VERSION,staleInstall,daemonRestarting},available=planSelfRefresh(inputs).kind==="refresh";return{element:staleInstall?$jsx(StaleInstallBanner,{message:staleInstall,width}):$jsxs($Fragment,{children:[$jsx(VersionSkewBanner,{stale:daemonStale,daemonVersion,clientVersion:CURRENT_VERSION,refreshChord:available?refreshChord():null,width}),$jsx(SkillBanner,{engines:missingSkill,error:skillError,onInstall:()=>setSkillError(installSkillNow()),width})]}),update:notify?update:null,refresh:{available,inputs}}}function refreshChord(){let prefixKey=currentPrefixConfiguration().key,stroke=findBinding("app.refresh")?.prefixKeys?.[0];return prefixKey&&stroke?`${formatChord(prefixKey)} ${stroke}`:null}function FullWindowPage(props){return $jsxs("box",{flexDirection:"column",flexGrow:1,backgroundColor:props.background,children:[props.banner,props.children]})}var import_react59=__toESM(require_react_production(),1);var import_react58=__toESM(require_react_production(),1);async function remoteVerb(alias,verb,params){let envelope=await forwardVerb(requireMachine(alias),verb,params);if(!envelope.ok)throw Error(envelope.error.message);return envelope.result}async function remoteFiles(alias,taskId){return(await remoteVerb(alias,"worktree-files",{"task-id":taskId})).files}async function remoteChanges(alias,taskId,scope){let diff=await remoteVerb(alias,"worktree-diff",{"task-id":taskId}),entries=diff.files.filter((row)=>row.scope===scope).map((row)=>({path:row.path,status:row.status,added:row.added,deleted:row.deleted}));return{base:diff.base,entries}}function remotePreview(alias,taskId,relPath,base){return remoteVerb(alias,"worktree-diff-file",{"task-id":taskId,path:relPath,scope:base?"branch":"working"})}var lists=new Map;function cachedFileList(worktreePath){return lists.get(worktreePath)??null}function rememberFileList(worktreePath,files){lists.delete(worktreePath),lists.set(worktreePath,files);while(lists.size>4){let oldest=lists.keys().next().value;lists.delete(oldest)}}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{watch}from"fs";function statusToken(s2){switch(s2){case"M":return"warning";case"A":return"added";case"D":return"removed";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,w4){let stats=(w4.added>0?w4.added+1:0)+(w4.deleted>0?w4.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 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_react53=__toESM(require_react_production(),1);var import_react52=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes20}from"@opentui/core";var PLACEMENT={spinner:["rows","primary"],needsInput:["rows","warning"],attention:["rows","error"],unseen:["rows","primary"],idle:["rows","textMuted"],subagent:["rows","textMuted"],remote:["rows","textMuted"],done:["inbox","success"],rateLimited:["inbox","warning"],dead:["inbox","error"],routineFailed:["inbox","error"],conflict:["pr","error"],checksFailing:["pr","error"],checksPassing:["pr","success"],running:null},GROUP_ORDER=["rows","inbox","pr"];function glyphLegendSections(glyphs){let marks=Object.keys(PLACEMENT);return GROUP_ORDER.map((group)=>({group,rows:marks.flatMap((mark)=>{let placement=PLACEMENT[mark];if(placement?.[0]!==group)return[];let value=glyphs[mark];return[{mark,glyph:typeof value==="string"?value:value[0]??"",tone:placement[1]}]})}))}function useGlyphs(){return GLYPH_SETS[normalizeGlyphSet(useOptionalKV()?.get(GLYPH_SET_KEY,DEFAULT_GLYPH_SET))]}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(),[filtering,setFiltering]=import_react52.useState(!1),[query,setQuery]=import_react52.useState(""),keymapVersion2=useKeymapVersion(),pureTuiPrefix=currentPrefixConfiguration(),filteredSections=import_react52.useMemo(()=>grammarHelpSections(RoveKeymap,props.currentScope??null,pureTuiPrefix.key,props.reachability),[keymapVersion2,props.currentScope,props.reachability,pureTuiPrefix.key]).map((section)=>({...section,rows:section.rows.filter((row)=>matchesHelpAction(query,tKeys("desc",row.binding.id),row.primary))})).filter((section)=>section.rows.length>0),glyphs=useGlyphs(),legendSections=glyphLegendSections(glyphs).map((section)=>({...section,rows:section.rows.filter((row)=>matchesHelpAction(query,t3(`help.mark.${row.mark}`),row.glyph))})).filter((section)=>section.rows.length>0),close=()=>props.onClose?props.onClose():dialog.clear(),scrollRef=import_react52.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:[...!filtering?[{key:"?",cmd:close},{key:"/",cmd:()=>setFiltering(!0)}]:[],{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:TextAttributes20.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:TextAttributes20.DIM,children:t3("help.scrollKeys")}),$jsx("text",{fg:theme.textMuted,onMouseUp:close,children:t3("help.esc")})]})]}),filtering?$jsx("input",{focused:!0,value:query,placeholder:t3("help.search"),onInput:(value)=>{setQuery(value),scrollToEdge("top")}}):$jsx("text",{fg:theme.textMuted,children:t3("help.filter")}),filteredSections.length===0&&legendSections.length===0?$jsx("text",{fg:theme.textMuted,children:t3("help.noResults")}):null,$jsx("scrollbox",{ref:(r6)=>{scrollRef.current=r6},flexShrink:1,flexGrow:1,stickyScroll:!1,verticalScrollbarOptions:{trackOptions:{backgroundColor:theme.backgroundDialog,foregroundColor:theme.borderActive}},children:$jsxs("box",{paddingBottom:1,gap:1,paddingRight:1,children:[filteredSections.map((section,sectionIndex)=>$jsxs("box",{gap:0,children:[$jsx("text",{fg:theme.accent,attributes:TextAttributes20.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}`)),legendSections.map((section)=>$jsxs("box",{gap:0,children:[$jsx("text",{fg:theme.accent,attributes:TextAttributes20.BOLD,children:t3(`help.marks.${section.group}`)}),section.rows.map((row)=>$jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,children:[$jsx("box",{width:18,children:$jsx("text",{fg:theme[row.tone],children:row.glyph})}),$jsx("box",{flexGrow:1,children:$jsx("text",{fg:theme.text,children:t3(`help.mark.${row.mark}`)})})]},`mark-${row.mark}`))]},`marks-${section.group}`))]})})]})}HelpDialog.show=(dialog,currentScope)=>{let reachability=currentBindingReachability(),inputScope=reachability.inputPassthrough?"terminal":currentScope;dialog.replace(()=>$jsx(HelpDialog,{currentScope:inputScope,reachability}))};var EMPTY_HINT_SNAPSHOT={tokens:[],modal:!1};function useStatusKeyHintItems(opts){let t3=useT(),kv=useOptionalKV(),focus=useOptionalFocus(),dialog=useOptionalDialog(),keymapVersion2=useKeymapVersion(),hintsEnabled=keyHintsEnabled(kv?.get(KEY_HINTS_ENABLED_KEY,!0)),[snapshot,setSnapshot]=import_react53.useState(EMPTY_HINT_SNAPSHOT),shownRef=import_react53.useRef(snapshot),enabledRef=import_react53.useRef(hintsEnabled),dialogDepthRef=import_react53.useRef(dialog?.stack.length??0);enabledRef.current=hintsEnabled,dialogDepthRef.current=dialog?.stack.length??0;let refresh=import_react53.useCallback(()=>{let enabled=enabledRef.current,nextModal=modalActive()||dialogDepthRef.current>0,fresh=enabled&&!nextModal?statusHintTokens(currentBindingReachability(),currentPrefixConfiguration().key):null,prev=shownRef.current,nextTokens=fresh??(enabled?prev.tokens:[]);if(prev.modal===nextModal&&prev.tokens.length===nextTokens.length&&prev.tokens.every((tok,i2)=>tok.chord===nextTokens[i2]?.chord&&tok.msg===nextTokens[i2]?.msg))return;let next={tokens:nextTokens,modal:nextModal};shownRef.current=next,setSnapshot(next)},[]);import_react53.useEffect(()=>{let queued=!1,live=!0,unsubscribe=subscribeBindingStack(()=>{if(queued)return;queued=!0,queueMicrotask(()=>{if(queued=!1,live)refresh()})});return()=>{live=!1,unsubscribe()}},[refresh]),import_react53.useEffect(refresh,[keymapVersion2,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_react53.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_react57=__toESM(require_react_production(),1);var import_react54=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes21}from"@opentui/core";var FileTreeRowView=import_react54.memo(function(props){let{theme}=useTheme(),inks=useDiffInks(),selection=resolveRowSelectionChrome2(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:TextAttributes21.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 isUntrackedDir=row.fileCount!==void 0,marker=isUntrackedDir?row.expanded?"\u25BE ":"\u25B8 ":"",countSuffix=isUntrackedDir?` (${row.fileCount})`:"",indent=row.child?" ":"",pathBudget=props.pathBudget-displayWidth(marker)-displayWidth(countSuffix)-displayWidth(indent),tone=statusToken(row.status),statusColor=tone==="added"?inks.added:tone==="warning"?theme.warning:tone==="removed"?inks.removed: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:isUntrackedDir?theme.textMuted:theme.text,wrapMode:"none",flexGrow:1,children:`${indent}${marker}${truncatePathTail(row.path,pathBudget)}${countSuffix}`}),props.statWidths.added>0?$jsx("text",{fg:inks.added,wrapMode:"none",children:statCell(row.added,props.statWidths.added,"+")}):null,props.statWidths.deleted>0?$jsx("text",{fg:inks.removed,wrapMode:"none",children:statCell(row.deleted,props.statWidths.deleted,"-")}):null]})]})});var import_react56=__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_react56.useState({top:0,height:0}),sample=import_react56.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_react56.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_react57.useState(null),rowWindow=useRowWindow({scrollEl,rowCount:rows.length}),rowCount=rows.length,sample=rowWindow.sample;return import_react57.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 TextAttributes22}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:TextAttributes22.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:TextAttributes22.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?TextAttributes22.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 dims=useTerminalSize(),[tab,setTab]=import_react58.useState("all"),[scope,setScope]=import_react58.useState("working"),[scopeManual,setScopeManual]=import_react58.useState(!1),[base,setBase]=import_react58.useState(null),[cursorIndex,setCursorIndex]=import_react58.useState(0),[refreshTick,setRefreshTick]=import_react58.useState(0),[allFiles,setAllFiles]=import_react58.useState(null),[changes,setChanges]=import_react58.useState(null),[error,setError]=import_react58.useState(null),[expandedDirs,setExpandedDirs]=import_react58.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_react58.useRef(0),remoteRef=useLatest(props.remote),refetch=import_react58.useCallback(async(currentTab,path,signal)=>{let seq2=++fetchSeq.current;if(path==null){setAllFiles(null),setChanges(null),setError(null);return}setError(null);try{let remote=remoteRef.current;if(currentTab==="all"){let files=remote?await remoteFiles(remote.machine,remote.taskId):await listFiles(path,signal);if(signal?.aborted||seq2!==fetchSeq.current||pathRef.current!==path)return;rememberFileList(cacheKey(path,remote),files),setAllFiles((prev)=>sameFileList(prev,files)?prev:files)}else if(currentTab==="changes"){let wantBranch=scopeRef.current==="branch"&&baseRef.current!=null,entries=remote?(await remoteChanges(remote.machine,remote.taskId,wantBranch?"branch":"working")).entries:wantBranch?await statusFilesBranch(path,baseRef.current,signal):await statusFiles(path,signal);if(signal?.aborted||seq2!==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(seq2===fetchSeq.current&&pathRef.current===path)setError(message)}},[]);import_react58.useEffect(()=>{let path=props.worktreePath;setAllFiles(path!=null&&tabRef.current==="all"?cachedFileList(cacheKey(path,remoteRef.current)):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_react58.useEffect(()=>{let path=props.worktreePath;if(path==null){setBase(null);return}let disposed=!1,controller=new AbortController,remote=remoteRef.current;return(remote?remoteChanges(remote.machine,remote.taskId,"branch").then((r6)=>r6.base):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_react58.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_react58.useEffect(()=>{let path=props.worktreePath;if(path==null)return;if(readRoveEnv("FILETREE_WATCH")==="0")return;if(props.remote)return;return watchWorktree(path,()=>setRefreshTick((n2)=>n2+1))},[props.worktreePath,props.remote]),import_react58.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_react58.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_react58.useMemo(()=>allFiles==null?null:buildTree(allFiles),[allFiles]),prevRows=import_react58.useRef([]),rows=import_react58.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_react58.useEffect(()=>{if(rows.length===0)return;setCursorIndex((i2)=>i2>rows.length-1?rows.length-1:i2)},[rows]);let statWidths=import_react58.useMemo(()=>computeStatWidths(rows),[rows]),paneWidth=props.paneWidth??dims.width,pathBudget=import_react58.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_react58.useCallback((row)=>{if(row.kind==="dir"||row.path.endsWith("/"))setExpandedDirs((prev)=>toggleDir(prev,row.path));else onOpenFileRef.current(row.path)},[]),handleRowActivate=import_react58.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 loaded2=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:loaded2,tab}),props.worktreePath!=null?$jsx("box",{flexDirection:"row",justifyContent:"flex-end",paddingTop:1,flexShrink:0,children:$jsx(PaneKeyHint,{pane:"files"})}):null]})}function cacheKey(path,remote){return remote?`${remote.machine}:${path}`:path}var WORKTREE_TOOLS_MIN_WIDTH=22,WORKTREE_TOOLS_MAX_WIDTH=34;function useFilesPaneActions(actions){let latest=useLatest(actions);return import_react59.useMemo(()=>({onOpenFile:(relPath)=>latest.current.onOpenFile(relPath),onOpenDiff:(relPath,base)=>latest.current.onOpenDiff(relPath,base),onMention:(relPath)=>latest.current.onMention(relPath),onZenToggle:()=>latest.current.onZenToggle(),onCreatePR:()=>latest.current.onCreatePR()}),[])}var HostFilesPane=import_react59.memo(function(props){let{theme}=useTheme(),t3=useT(),focus=useFocus(),dims=useTerminalSize(),inactiveBorder=theme.borderActive,available=Math.max(WORKTREE_TOOLS_MIN_WIDTH,dims.width-props.sidebarWidth),width=Math.max(WORKTREE_TOOLS_MIN_WIDTH,Math.min(WORKTREE_TOOLS_MAX_WIDTH,Math.floor(available/3)));return $jsx(RenderProfiler,{id:"files",children:$jsx("box",{width,flexShrink:0,borderStyle:"rounded",borderColor:focus.focused==="files"?theme.focusAccent:inactiveBorder,onMouseUp:()=>focus.setFocused("files"),children:$jsx(PaneErrorBoundary,{region:"files",resetKeys:[props.worktree],children:props.remoteHost&&!props.remote?$jsxs("box",{flexDirection:"column",padding:1,gap:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("tasks.machine.filesElsewhere",{host:props.remoteHost})}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("tasks.machine.filesHint",{host:props.remoteHost})})]}):$jsx(FileTree,{worktreePath:props.worktree,paneWidth:width-2,prBaseRef:props.prBaseRef,remote:props.remote,focused:props.focused,onOpenFile:props.actions.onOpenFile,onOpenDiff:props.actions.onOpenDiff,onMention:props.actions.onMention,onZenToggle:props.actions.onZenToggle,onCreatePR:props.taskKind==="main"?void 0:props.actions.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((w4)=>({label:w4.label,percentText:`${w4.percent}%`,resetText:formatReset(w4.resetsAt,nowMs),tone:toneOf(w4.percent)}))}function narrowUsageChip(usage,nowMs){let w4=usage.windows.find((win)=>win.kind==="session")??usage.windows[0];if(!w4)return null;return{label:w4.label,percentText:`${w4.percent}%`,resetText:formatReset(w4.resetsAt,nowMs),tone:toneOf(w4.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((entry2)=>entry2.chips.length>0);if(entries.length===0)return null;if(!opts.forceCompact){let fulls=entries.map((entry2)=>({vendor:entry2.vendor,chips:entry2.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 entry2 of entries){let chip=narrowUsageChip(entry2.snapshot,opts.nowMs);if(!chip)continue;let gap=vendors.length>0?2:0,need=displayWidth(entry2.vendor)+1+displayWidth(chip.percentText);if(need+gap<=remaining){vendors.push({vendor:entry2.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(entry2.vendor,nameBudget,approxCharCells),percentText:chip.percentText,tone:chip.tone});break}return{form:"compact",vendors}}function contextChip(usage){if(!usage)return null;let window2=usage.contextWindowTokens;if(window2===void 0||window2<=0)return null;let percent=Math.min(100,Math.max(0,Math.round(usage.contextTokens/window2*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((w4,win)=>Math.max(w4,displayWidth(win.label)),2));return usage.windows.map((w4)=>({label:padEndCells(truncateEndCells(w4.label,labelWidth,charWidth),labelWidth),bar:ratioBar(w4.percent/100,USAGE_BAR_WIDTH),percentText:`${String(w4.percent).padStart(3)}%`,resetText:formatReset(w4.resetsAt,nowMs),tone:toneOf(w4.percent)}))}function ContextChip(props){let{theme}=useTheme(),chip=props.chip;if(!chip)return null;let toneColor3={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:toneColor3[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()),toneColor3={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:toneColor3[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:toneColor3[vendor.tone],wrapMode:"none",children:vendor.percentText})]},`${vendor.vendor}-${index}`))})}function WorkspaceFrame(props){let{theme}=useTheme(),dims=useTerminalSize(),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,onMouseDrag:props.onPaneDrag,onMouseUp:props.onPaneRelease,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]})})}var import_react62=__toESM(require_react_production(),1);var import_react60=__toESM(require_react_production(),1);var MIN_CHARS=2,DEBOUNCE_MS=300,LIMIT=30;function matchingTasks(tasks2,query){let q2=query.trim();if(!q2)return[];return tasks2.filter((task)=>task.kind!=="dir"&&fuzzyMatch(q2,task.title))}function useSaid(search,query){let[state,setState]=import_react60.useState({kind:"idle"}),seq2=import_react60.useRef(0),orchestrator=search?.orchestrator,debounceMs=search?.debounceMs??DEBOUNCE_MS;return import_react60.useEffect(()=>{let q2=query.trim(),mine=++seq2.current;if(!orchestrator||q2.length<MIN_CHARS){setState({kind:"idle"});return}let timer3=setTimeout(()=>{setState({kind:"searching"}),searchTasks(orchestrator.listTasks(),q2,LIMIT).then((result)=>mine===seq2.current&&setState({kind:"done",result}),(err)=>mine===seq2.current&&setState({kind:"failed",reason:err instanceof Error?err.message:String(err)}))},debounceMs);return()=>clearTimeout(timer3)},[query,orchestrator,debounceMs]),state}function useMatchingTasks(search,query){let tasks2=search?.tasks;return import_react60.useMemo(()=>tasks2?matchingTasks(tasks2,query):[],[tasks2,query])}function splitMarked(text,needle){let n2=needle.trim().toLowerCase();if(!n2)return[text];let lower=text.toLowerCase(),parts=[],from=0;for(let at2=lower.indexOf(n2);at2>=0;at2=lower.indexOf(n2,from))parts.push(text.slice(from,at2),text.slice(at2,at2+n2.length)),from=at2+n2.length;return parts.push(text.slice(from)),parts}function CommandPalette({actions,search}){let dialog=useDialog(),{theme}=useTheme(),t3=useT(),padX=useDialogPaddingX(),dimensions=useTerminalSize(),[query,setQuery]=import_react62.useState(""),[selected,setSelected]=import_react62.useState(0),prefix=currentPrefixConfiguration().key,commands=actions.map((action)=>({kind:"command",key:`c:${action.id}`,action,name:tKeys("desc",action.id),chord:action.prefix?`${prefix?formatChord(prefix):""} + ${formatChord(action.key)}`:formatChord(action.key)})).filter((row)=>matchesHelpAction(query,row.name,row.action.prefix?`${prefix} + ${row.action.key}`:row.action.key)),tasks2=useMatchingTasks(search,query).map((task)=>({kind:"task",key:`t:${task.id}`,name:task.title,taskId:task.id})),said=useSaid(search,query),hits=said.kind==="done"?said.result.matches.map((hit,i2)=>({kind:"said",key:`s:${hit.taskId}:${hit.at}:${i2}`,name:hit.title,taskId:hit.taskId,...hit.tabId?{tabId:hit.tabId}:{},role:hit.role,at:hit.at,snippet:hit.snippet})):[],rows=[...commands,...tasks2,...hits],extra=tasks2.length>0||said.kind!=="idle",visibleCount=Math.max(1,Math.min(10,dimensions.height-10-(extra?6:0))),index=Math.min(selected,Math.max(0,rows.length-1)),run=(row)=>{if(flushSync(()=>dialog.clear({refocus:!1})),row.kind==="command"){if(!row.action.run())dialog.replace(()=>$jsx("text",{fg:theme.warning,children:t3("help.unavailable")}))}else search?.openTask(row.taskId,row.kind==="said"?row.tabId:void 0)};useBindings(()=>({bindings:[{key:"up",cmd:()=>setSelected(Math.max(0,index-1))},{key:"down",cmd:()=>setSelected(Math.min(rows.length-1,index+1))},{key:"return",cmd:()=>{let row=rows[index];if(row)run(row)}}]}));let start=Math.max(0,index-visibleCount+1),now=Date.now(),head=(at2,row)=>{if(!extra||at2>0&&rows[at2-1]?.kind===row.kind)return null;let label={command:"search.commands",task:"search.tasks",said:"search.inConversations"};return $jsx("text",{fg:theme.textMuted,children:t3(label[row.kind])})};return $jsxs("box",{paddingLeft:padX,paddingRight:padX,paddingBottom:1,gap:1,children:[$jsx("text",{fg:theme.accent,children:t3("help.palette")}),$jsx("input",{focused:!0,value:query,placeholder:t3("help.search"),onInput:(value)=>{setQuery(value),setSelected(0)}}),$jsxs("box",{children:[rows.length===0&&said.kind==="idle"?$jsx("text",{fg:theme.textMuted,children:t3("help.noResults")}):rows.slice(start,start+visibleCount).map((row,offset)=>{let at2=start+offset,picked=at2===index;return $jsxs("box",{flexDirection:"column",children:[head(at2,row),$jsxs("box",{flexDirection:"column",backgroundColor:picked?theme.backgroundElement:void 0,onMouseUp:()=>run(row),children:[$jsxs("box",{flexDirection:"row",gap:2,children:[$jsx("text",{fg:theme.text,flexGrow:1,flexBasis:0,flexShrink:1,children:`${picked?"\u203A ":" "}${row.name}`}),row.kind==="command"&&$jsx("text",{fg:theme.primary,flexShrink:0,children:row.chord}),row.kind==="said"&&$jsx("text",{fg:theme.textMuted,flexShrink:0,children:`${t3(row.role==="user"?"search.you":"search.agent")} \xB7 ${relativeAge(Date.parse(row.at),now)}`})]}),row.kind==="said"&&$jsxs("text",{fg:theme.textMuted,children:[" ",splitMarked(row.snippet,query).map((part,i2)=>$jsx("span",{fg:i2%2===1?theme.accent:theme.textMuted,children:part},i2))]})]})]},row.key)}),said.kind!=="idle"&&hits.length===0&&$jsxs("box",{flexDirection:"column",children:[$jsx("text",{fg:theme.textMuted,children:t3("search.inConversations")}),said.kind==="searching"&&$jsx("text",{fg:theme.textMuted,children:t3("search.searching")}),said.kind==="failed"&&$jsx("text",{fg:theme.error,children:t3("search.failed",{reason:said.reason})}),said.kind==="done"&&$jsx("text",{fg:theme.textMuted,children:t3("search.none",{query:said.result.query})})]}),said.kind==="done"&&said.result.truncated&&$jsx("text",{fg:theme.textMuted,children:t3("search.truncated")}),said.kind==="done"&&said.result.skipped.length>0&&$jsx("text",{fg:theme.textMuted,children:t3("search.skipped",{count:said.result.skipped.length})})]}),$jsx("text",{fg:theme.textMuted,children:t3("help.run")})]})}CommandPalette.show=(dialog,search)=>{let actions=currentPaletteActions();dialog.replace(()=>$jsx(CommandPalette,{actions,...search?{search}:{}}))};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(current2,delta,opts){let reachable=PANE_CYCLE.filter((pane)=>pane!=="files"||opts.filesVisible),idx=reachable.indexOf(current2);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 pageEntries2=usePageEntries(),{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},pagesClosed=workspacePagesClosed(pages);useBindings(()=>({enabled:pagesClosed,bindings:[...bindByIds({"help.open":prefixAction(()=>HelpDialog.show(dialog,focus.focused)),"palette.open":prefixAction(()=>CommandPalette.show(dialog,deps.paletteSearch)),"focus.previous":prefixAction(()=>cyclePane(-1)),"focus.next":prefixAction(()=>cyclePane(1)),"workspace.zenToggle":prefixAction(()=>deps.toggleZen()),"attention.next":prefixAction(()=>deps.jumpToNextAttention()),"inbox.show":prefixAction(()=>deps.openInbox()),...Object.fromEntries(pageEntries2.flatMap((page)=>page.action?[[page.action,prefixAction(()=>deps.pages.openPage(page.id))]]:[])),"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":prefixAction(()=>deps.createTask())})})),useBindings(()=>({enabled:pagesClosed&&focus.focused!=="sidebar",bindings:bindByIds({"focus.sidebar":prefixAction(()=>focus.setFocused("sidebar"))})})),useBindings(()=>({enabled:pagesClosed&&deps.refresh?.available!==!0,bindings:bindByIds({"view.redraw":prefixAction(()=>{if(renderer)redrawScreen(renderer)})})})),useBindings(()=>({enabled:!pages.dialogOpen&&deps.refresh?.available===!0,bindings:bindByIds({"app.refresh":prefixAction(()=>deps.refresh?.run())})})),useBindings(()=>({enabled:pagesClosed&&focus.focused==="sidebar"&&!deps.searchActive,bindings:bindByIds({"app.quit":(_evt,slot)=>{if(slot===1){exitApp();return}quit()},"settings.open.sidebar":prefixAction(()=>deps.pages.openSettings()),"worktrees.open.sidebar":prefixAction(()=>deps.pages.openWorktrees()),"tasks.update":prefixAction(()=>deps.pages.openUpdate())})})),useBindings(()=>({enabled:pagesClosed&&focus.focused==="sidebar"&&!deps.searchActive,bindings:bindByIds({"task.new":prefixAction(()=>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":prefixAction(()=>focus.setFocused("workspace")),"sidebar.sort":prefixAction(()=>deps.toggleSortMode())})})),useBindings(()=>({enabled:settingsCloseKeysEnabled(pages),bindings:pageCloseBindings(deps.pages.closeSettings)})),usePluginKeybindings(pagesClosed)}var import_react83=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes39}from"@opentui/core";var import_react79=__toESM(require_react_production(),1);import{unlinkSync}from"fs";import{join}from"path";function hasRestartableDaemon(orchestrator){return orchestrator instanceof RemoteOrchestrator}function destroyRendererSafely(renderer,action){try{renderer?.destroy()}catch(err){console.error(`Rove: renderer.destroy() failed during ${action}:`,err)}}function removeTasksFileForReset(){try{unlinkSync(join(roveStateDir(),"tasks.json"))}catch(err){if(err.code!=="ENOENT")console.error("Rove: failed to delete tasks.json during reset:",err)}}async function confirmResetState(dialog,kv,renderer){if(await DialogConfirm.show(dialog,t("settings.reset.title"),t("settings.reset.body"),"cancel",void 0,{danger:!0})!==!0)return;if(!kv.clear()){await DialogConfirm.show(dialog,t("settings.reset.failedTitle"),t("settings.reset.failedBody"),"cancel");return}removeTasksFileForReset(),destroyRendererSafely(renderer,"reset"),process.stderr.write(`${t("settings.reset.done")}
69
+ `),process.exit(0)}async function confirmRestartDaemon(dialog,orchestrator,renderer){if(!hasRestartableDaemon(orchestrator))return;if(await DialogConfirm.show(dialog,t("settings.restart.title"),t("settings.restart.body"),"cancel")!==!0)return;await orchestrator.restartDaemon(),relaunchSelf({renderer,notice:t("settings.restart.done")})}function reloadSettingsStatus(kv){let result=kv.reload();if(!result.ok){let error=result.error instanceof Error?result.error.message:String(result.error);return t("settings.dev.reloadFailed",{error})}return result.changed===0?t("settings.dev.reloadUnchanged"):t("settings.dev.reloadDone",{count:result.changed})}async function installEngineHooks(){try{let{ensureGlobalRoveHooks}=await import("./chunk-6q4br0pt.js");await ensureGlobalRoveHooks({quiet:!0})}catch{}}async function uninstallEngineHooks(){try{let{activityHookAdapters}=await import("./chunk-2kt0mfvf.js");await Promise.all(activityHookAdapters().map(async(adapter)=>{try{await adapter.removeActivityHooks(adapter.globalSettingsPath())}catch{}}))}catch{}}import{TextAttributes as TextAttributes24}from"@opentui/core";var FILLS=["\u25CB","\u25D4","\u25D1","\u25D5","\u25CF","\u25C9"];function effortMark(levels,level){let index=levels&&level?levels.indexOf(level.trim()):-1;if(!levels||index<0)return null;let fraction=levels.length>1?index/(levels.length-1):1;return{glyph:FILLS[Math.round(fraction*(FILLS.length-1)-0.000000001)]??FILLS[0],fraction}}function effortLabel(levels,level){let mark=effortMark(levels,level);return mark?`${mark.glyph} ${level}`:level}import{TextAttributes as TextAttributes23}from"@opentui/core";function Row(props){let{theme}=useTheme();return $jsxs("box",{ref:props.rowRef,flexDirection:"row",gap:1,paddingLeft:1,paddingRight:1,overflow:"hidden",backgroundColor:props.cursor?theme.primary:props.idleBackground,onMouseUp:props.onMouseUp,children:[$jsx("text",{fg:props.cursor?theme.selectedListItemText:props.fg,attributes:props.bold?TextAttributes23.BOLD:void 0,wrapMode:"none",children:props.children}),props.hint?$jsx("text",{fg:props.cursor?theme.selectedListItemText:theme.textMuted,wrapMode:"none",flexShrink:1,children:props.hint}):null]})}function SubSection(props){let{theme}=useTheme();return $jsxs("box",{flexDirection:"column",gap:0,paddingTop:props.paddingTop??1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes23.BOLD,children:props.title}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:props.hint}),props.children]})}function AutoRoutingSettingsSection(props){let{theme}=useTheme(),t3=useT(),rows=autoRoutingRows(),{table}=props.autoRouting,isBodyCursor=(row)=>props.level==="body"&&props.bodyRow===row;return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes24.BOLD,children:t3("settings.autoRouting.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.autoRouting.hint")}),table===null?$jsx("text",{fg:theme.warning,wrapMode:"word",children:t3("settings.autoRouting.unconfigured")}):null,$jsx("box",{flexDirection:"column",gap:0,children:rows.map((row)=>{if(row.kind!=="autoRoutingTier")return null;let tier=row.tier,i2=rowIndex(rows,row.id),target=table?.[tier],block=props.autoRouting.block(tier),label=`${t3(`tasks.tier.${tier}`)}`.padEnd(10),fields=target?[engineDisplayName(target.engine),target.model??t3("settings.autoRouting.engineDefault"),target.effort?effortLabel(engineEntry(target.engine).effortLevels,target.effort):t3("settings.autoRouting.engineDefault")].join(" \xB7 "):"\u2014";return $jsxs("box",{flexDirection:"column",gap:0,children:[$jsx(Row,{cursor:isBodyCursor(i2),rowRef:props.rowRef(i2),onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(i2),props.autoRouting.edit(tier)},fg:theme.text,bold:!0,hint:fields,children:label}),$jsx("box",{flexDirection:"row",gap:1,paddingLeft:3,overflow:"hidden",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:1,children:t3(`tasks.tierDesc.${tier}`)})}),$jsx("box",{flexDirection:"row",gap:1,paddingLeft:3,overflow:"hidden",children:block===void 0?$jsx("text",{fg:theme.textMuted,children:t3("settings.accounts.checking")}):block===null?$jsx("text",{fg:theme.success,children:t3("settings.autoRouting.ready")}):$jsx("text",{fg:theme.warning,wrapMode:"none",flexShrink:1,children:t3("settings.autoRouting.unavailable",{reason:describeTierBlock(block)})})})]},row.id)})}),$jsx(ClassifierRows,{...props})]})}function ClassifierRows(props){let{theme}=useTheme(),t3=useT(),rows=autoRoutingRows(),c2=props.classifier,isBodyCursor=(row)=>props.level==="body"&&props.bodyRow===row,on=c2.mode!=="off",modeLabel=c2.mode==="off"?t3("settings.autoRouting.classifierOff"):c2.mode==="jev"?"jev":t3("settings.autoRouting.classifierCustomLabel"),modeHint=c2.mode==="off"?t3("settings.autoRouting.classifierOffHint"):c2.mode==="jev"?t3("settings.autoRouting.classifierJevHint"):t3("settings.autoRouting.classifierCustomHint");function open(id,run){let i2=rowIndex(rows,id);return{i:i2,onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(i2),run()}}}let status=(()=>{if(c2.mode==="off")return null;if(!c2.keyConfigured)return{ok:!0,text:t3("settings.autoRouting.keyCustomUnused")};if(c2.keySource==="env")return{ok:!0,text:t3("settings.autoRouting.keyPresentEnv",{env:c2.keyEnv})};if(c2.keySource==="file")return{ok:!0,text:t3("settings.autoRouting.keySaved")};return{ok:!1,text:t3("settings.autoRouting.keyMissing")}})(),mode=open("auto-routing-classifier",()=>c2.cycle()),endpoint=open("auto-routing-endpoint",()=>void c2.editEndpoint()),threshold=open("auto-routing-threshold",()=>void c2.editThreshold()),key=open("auto-routing-key",()=>void c2.editKey()),keyValue=c2.keySource==="env"?t3("settings.autoRouting.keyFromEnv",{env:c2.keyEnv}):c2.keySource==="file"?t3("settings.autoRouting.keyStored",{hint:c2.keyHint}):t3("settings.autoRouting.keyNone");return $jsxs(SubSection,{title:t3("settings.autoRouting.classifierTitle"),hint:t3("settings.autoRouting.classifierHint"),children:[$jsx("box",{paddingTop:1,paddingBottom:1,children:$jsx("text",{fg:on?theme.warning:theme.textMuted,wrapMode:"word",children:t3("settings.autoRouting.classifierDataFlow")})}),$jsx(Row,{cursor:isBodyCursor(mode.i),rowRef:props.rowRef(mode.i),onMouseUp:mode.onMouseUp,fg:theme.text,hint:modeHint,children:`${t3("settings.autoRouting.classifierLabel").padEnd(20)}${modeLabel}`}),$jsx(Row,{cursor:isBodyCursor(endpoint.i),rowRef:props.rowRef(endpoint.i),onMouseUp:endpoint.onMouseUp,fg:c2.mode==="custom"?theme.text:theme.textMuted,children:`${t3("settings.autoRouting.endpointLabel").padEnd(20)}${c2.endpoint||t3("settings.autoRouting.endpointUnset")}`}),$jsx(Row,{cursor:isBodyCursor(threshold.i),rowRef:props.rowRef(threshold.i),onMouseUp:threshold.onMouseUp,fg:theme.text,hint:t3("settings.autoRouting.thresholdHint"),children:`${t3("settings.autoRouting.thresholdLabel").padEnd(20)}${c2.threshold.toFixed(2)}`}),$jsx(Row,{cursor:isBodyCursor(key.i),rowRef:props.rowRef(key.i),onMouseUp:key.onMouseUp,fg:theme.text,children:`${t3("settings.autoRouting.keyLabel").padEnd(20)}${keyValue}`}),status?$jsx("box",{paddingTop:1,children:$jsx("text",{fg:status.ok?theme.success:theme.warning,wrapMode:"word",children:status.text})}):null]})}var import_react64=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes26}from"@opentui/core";function engineHealth(facts){if(facts.binaryFound===void 0)return{key:"settings.engines.status.checking",tone:"unknown"};if(facts.binaryFound===null)return{key:"settings.engines.status.unknown",tone:"unknown"};if(!facts.binaryFound)return facts.commandChosen?{key:"settings.engines.status.notOnPath",tone:"attention"}:{key:"settings.engines.status.notInstalled",tone:"absent"};if(facts.configIssue)return{key:"settings.engines.status.integrationBlocked",tone:"error"};if(facts.login==="no")return{key:"settings.engines.status.signIn",tone:"attention"};if(facts.hooks==="outdated")return{key:"settings.engines.status.integrationOutdated",tone:"attention"};if(facts.hooks==="not-installed")return{key:"settings.engines.status.integrationMissing",tone:"attention"};return{key:"settings.engines.status.ready",tone:"ready"}}function engineLogin(status){if(!status||status.account===null||status.accountError)return"unknown";return status.account.kind==="none"?"no":"yes"}import{TextAttributes as TextAttributes25}from"@opentui/core";function EngineDetails(props){let{theme}=useTheme(),t3=useT(),binary=props.commandText.split(/\s+/)[0]??props.commandText,facts=[{label:t3("settings.engines.detail.program"),lines:[programLine(props,binary,t3,theme)]},{label:t3("settings.engines.detail.command"),lines:[{text:t3(props.commandIsOwn?"settings.engines.detail.commandCustom":"settings.engines.detail.commandDefault",{command:props.commandText})}]},{label:t3("settings.engines.detail.signIn"),lines:[signInLine(props,t3,theme)]}];if(props.integration)facts.push({label:t3("settings.engines.detail.reporting"),lines:reportingLines(props,t3,theme)});if(props.integration?.skillDir){let{skillDir,skillState}=props.integration;facts.push({label:t3("settings.engines.detail.skill"),lines:[skillState==="installed"?{text:t3("settings.engines.detail.skillInstalled",{dir:tildify(skillDir)})}:{text:t3(skillState==="outdated"?"settings.engines.detail.skillOutdated":"settings.engines.detail.skillMissing"),fg:theme.warning}]})}if(props.protocol)facts.push({label:t3("settings.engines.detail.adapter"),lines:[{text:props.protocol.declared?t3("settings.engines.detail.adapterDeclared",{protocol:props.protocol.declared}):t3("settings.engines.detail.adapterGeneric"),fg:props.protocol.declared?void 0:theme.textMuted}]});let labelWidth=facts.reduce((max,f2)=>Math.max(max,displayWidth(f2.label)),0);return $jsxs("box",{flexDirection:"column",gap:0,paddingLeft:1,paddingRight:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes25.BOLD,wrapMode:"none",children:props.name}),facts.map((fact)=>$jsxs("box",{flexDirection:"row",gap:2,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:fact.label+" ".repeat(Math.max(0,labelWidth-displayWidth(fact.label)))}),$jsx("box",{flexDirection:"column",flexShrink:1,flexGrow:1,children:fact.lines.map((line)=>$jsx("text",{fg:line.fg??theme.text,wrapMode:"word",children:line.text},line.text))})]},fact.label))]})}function programLine(props,binary,t3,theme){let s2=props.status;if(!s2)return props.probing?{text:t3("settings.accounts.checking"),fg:theme.textMuted}:{text:t3("settings.engines.detail.programUnknown",{binary}),fg:theme.textMuted};if(s2.binary.found)return{text:t3("settings.engines.detail.programFound",{binary,path:tildify(s2.binary.path)})};return{text:t3("settings.engines.detail.programMissing",{binary}),fg:theme.warning}}function signInLine(props,t3,theme){let s2=props.status;if(!s2)return{text:props.probing?t3("settings.accounts.checking"):t3("settings.engines.detail.signInUnknown"),fg:theme.textMuted};if(s2.accountError)return{text:t3("settings.engines.detail.signInFailed",{error:s2.accountError}),fg:theme.warning};if(s2.account===null)return{text:t3("settings.engines.detail.signInUnknown"),fg:theme.textMuted};return accountLine(s2.account,t3,theme)}function accountLine(account,t3,theme){if(account.kind==="oauth"){if(!("email"in account))return{text:t3("settings.engines.detail.signedIn")};let who=account.email+(account.billingType?` (${account.billingType})`:"");return{text:t3("settings.engines.detail.signedInAs",{who})}}if(account.kind==="chatgpt"){let who=account.email+(account.plan?` (${account.plan})`:"");return{text:t3("settings.engines.detail.signedInAs",{who})}}if(account.kind==="apikey")return{text:t3("settings.engines.detail.apiKey")};if(account.kind==="token")return{text:t3("settings.engines.detail.token",{source:account.source})};return{text:t3("settings.engines.detail.signedOut"),fg:theme.warning}}function reportingLines(props,t3,theme){let row=props.integration;if(!row)return[];let lines=[];if(row.configIssue)lines.push({text:t3("settings.engines.detail.hooksBlocked",{file:tildify(row.hookFile),reason:row.configIssue}),fg:theme.error});else if(!row.hooksSupported)lines.push({text:t3("settings.engines.detail.hooksUnsupported"),fg:theme.textMuted});else if(row.hookState==="installed")lines.push({text:t3("settings.engines.detail.hooksInstalled")});else if(row.hookState==="outdated")lines.push({text:t3("settings.engines.detail.hooksOutdated"),fg:theme.warning});else if(props.status?.binary.found===!1)lines.push({text:t3("settings.engines.detail.hooksAwaitEngine"),fg:theme.textMuted});else lines.push({text:t3("settings.engines.detail.hooksMissing"),fg:theme.warning});if(lines.push({text:t3(row.markers?"settings.engines.detail.markersYes":"settings.engines.detail.markersNo")}),lines.push({text:t3(row.screen?"settings.engines.detail.screenYes":row.hooksSupported&&row.hookState==="installed"?"settings.engines.detail.screenNotNeeded":"settings.engines.detail.screenNo")}),row.setupCommand)lines.push({text:t3("settings.engines.hookTrustHint",{command:row.setupCommand}),fg:theme.warning});return lines}var NAME_MAX=22;function EngineSettingsSection(props){let{theme}=useTheme(),t3=useT(),addRowIndex=props.vendors.length,isBodyCursor=(row)=>props.level==="body"&&props.bodyRow===row,byVendor=new Map((props.statuses??[]).map((s2)=>[s2.vendor,s2])),integrationByVendor=new Map((props.integrations??[]).map((row)=>[row.vendor,row])),lastFocused=import_react64.useRef(void 0),cursorVendor=props.level==="body"?props.vendors[props.bodyRow]:void 0;if(cursorVendor)lastFocused.current=cursorVendor;let focused=lastFocused.current&&props.vendors.includes(lastFocused.current)?lastFocused.current:props.vendors[0],health=(vendor)=>{let status=byVendor.get(vendor),integration=integrationByVendor.get(vendor);return engineHealth({binaryFound:props.statuses===null?void 0:status?.binary.found??null,login:engineLogin(status),hooks:integration?integration.hooksSupported?integration.hookState:"unsupported":"unsupported",configIssue:integration?.configIssue,commandChosen:props.isCustom(vendor)||props.hasCommandOverride(vendor)})},toneColor3=(tone)=>tone==="ready"?theme.success:tone==="attention"?theme.warning:tone==="error"?theme.error:theme.textMuted,nameText=(vendor)=>props.displayName(vendor),subText=(vendor)=>{let from=props.renamedFrom(vendor);if(from)return` (${from})`;return props.isCustom(vendor)?` (${t3("settings.engines.customTag")})`:""},nameWidth=Math.min(NAME_MAX,props.vendors.reduce((max,v3)=>Math.max(max,displayWidth(nameText(v3)+subText(v3))),0)),rows=props.vendors.map((vendor)=>({vendor,health:health(vendor)})),statusWidth=rows.reduce((max,r6)=>Math.max(max,displayWidth(t3(r6.health.key))),0),pad=(text,width)=>text+" ".repeat(Math.max(0,width-displayWidth(text))),availableLabel=t3("settings.engines.available"),offLabel=t3("settings.engines.off"),markWidth=Math.max(displayWidth(availableLabel),displayWidth(offLabel)),defaultLabel=t3("settings.engines.defaultMark"),present=(vendor)=>byVendor.get(vendor)?.binary.found!==!1,installCount=props.needsHookInstall.filter(present).length,removeCount=props.hooksInstalled.length,hookable=(props.integrations??[]).filter((row)=>row.hooksSupported&&present(row.vendor)),hookTotal=hookable.length,hookCurrent=hookable.filter((row)=>row.hookState==="installed").length,skillable=(props.integrations??[]).filter((row)=>row.skillDir),skillCurrent=skillable.filter((row)=>row.skillState==="installed").length,skillNeeded=skillable.length-skillCurrent;return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes26.BOLD,children:t3("settings.engines.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.engines.hint")}),$jsxs("box",{flexDirection:"column",gap:0,children:[rows.map(({vendor,health:h2},i2)=>{let isCursor=isBodyCursor(i2),enabled=props.isEnabled(vendor),isDefault=props.isDefaultEngine(vendor),on=(idle)=>isCursor?theme.selectedListItemText:idle,name=nameText(vendor),sub=subText(vendor),subFits=displayWidth(name+sub)<=nameWidth?sub:"";return $jsxs("box",{ref:props.rowRef(i2),flexDirection:"row",gap:2,paddingLeft:1,paddingRight:1,overflow:"hidden",backgroundColor:isCursor?theme.primary:void 0,onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(i2),props.editEngine(vendor)},children:[$jsxs("box",{flexDirection:"row",flexShrink:1,overflow:"hidden",children:[$jsx("text",{fg:on(enabled?theme.text:theme.textMuted),attributes:TextAttributes26.BOLD,wrapMode:"none",children:name}),displayWidth(name)<nameWidth||subFits?$jsx("text",{fg:on(theme.textMuted),wrapMode:"none",children:pad(subFits,nameWidth-displayWidth(name))}):null]}),$jsxs("box",{flexDirection:"row",gap:1,flexShrink:0,children:[$jsx("text",{fg:on(toneColor3(h2.tone)),wrapMode:"none",children:"\u25CF"}),$jsx("text",{fg:on(enabled?theme.text:theme.textMuted),wrapMode:"none",children:pad(t3(h2.key),statusWidth)})]}),$jsx("text",{fg:on(enabled?theme.text:theme.textMuted),wrapMode:"none",flexShrink:0,onMouseUp:(evt)=>{evt.stopPropagation(),props.setLevel("body"),props.setBodyRow(i2),props.toggleEngine(vendor)},children:pad(enabled?availableLabel:offLabel,markWidth)}),$jsx("text",{fg:on(isDefault?theme.accent:theme.textMuted),attributes:isDefault?TextAttributes26.BOLD:0,wrapMode:"none",flexShrink:0,onMouseUp:(evt)=>{evt.stopPropagation(),props.setLevel("body"),props.setBodyRow(i2),props.chooseDefault(vendor)},children:pad(isDefault?defaultLabel:"",displayWidth(defaultLabel))})]},vendor)}),$jsx("box",{ref:props.rowRef(addRowIndex),flexDirection:"row",paddingLeft:1,paddingRight:1,backgroundColor:isBodyCursor(addRowIndex)?theme.primary:void 0,onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(addRowIndex),props.onAddEngine()},children:$jsx("text",{fg:isBodyCursor(addRowIndex)?theme.selectedListItemText:theme.primary,wrapMode:"none",children:t3("settings.engines.addEngine")})})]}),focused?$jsx(EngineDetails,{name:props.displayName(focused),status:byVendor.get(focused)??null,probing:props.statuses===null,integration:integrationByVendor.get(focused)??null,commandText:props.commandText(focused),commandIsOwn:props.isCustom(focused)||props.hasCommandOverride(focused),protocol:props.isCustom(focused)?{declared:props.engineProtocol(focused)??null}:void 0}):null,$jsxs("box",{flexDirection:"column",gap:0,children:[$jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes26.BOLD,wrapMode:"none",children:t3("settings.engines.integrations.title")}),props.integrations?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("settings.engines.integrations.summary",{installed:String(hookCurrent),total:String(hookTotal)})}):null]}),$jsx("box",{paddingLeft:1,paddingRight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.engines.integrations.hint")})}),$jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,paddingRight:1,children:[$jsx(IntegrationButton,{rowRef:props.rowRef(addRowIndex+1),cursor:isBodyCursor(addRowIndex+1),live:installCount>0,label:installCount>0?t3("settings.engines.integrations.install",{count:String(installCount)}):t3("settings.engines.integrations.upToDate"),onPress:()=>{props.setLevel("body"),props.setBodyRow(addRowIndex+1),props.onInstallHooks()}}),$jsx(IntegrationButton,{rowRef:props.rowRef(addRowIndex+2),cursor:isBodyCursor(addRowIndex+2),live:removeCount>0,label:removeCount>0?t3("settings.engines.integrations.remove",{count:String(removeCount)}):t3("settings.engines.integrations.noneInstalled"),onPress:()=>{props.setLevel("body"),props.setBodyRow(addRowIndex+2),props.onUninstallHooks()}})]})]}),$jsxs("box",{flexDirection:"column",gap:0,children:[$jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes26.BOLD,wrapMode:"none",children:t3("settings.engines.skill.title")}),props.integrations?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("settings.engines.integrations.summary",{installed:String(skillCurrent),total:String(skillable.length)})}):null]}),$jsx("box",{paddingLeft:1,paddingRight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.engines.skill.hint")})}),$jsx("box",{flexDirection:"row",paddingLeft:1,paddingRight:1,children:$jsx(IntegrationButton,{rowRef:props.rowRef(addRowIndex+3),cursor:isBodyCursor(addRowIndex+3),live:skillNeeded>0,label:skillNeeded>0?t3("settings.engines.skill.install",{count:String(skillNeeded)}):skillable.length>0?t3("settings.engines.integrations.upToDate"):t3("settings.engines.skill.noEngines"),onPress:()=>{props.setLevel("body"),props.setBodyRow(addRowIndex+3),props.onInstallSkill()}})}),props.skillError?$jsx("box",{paddingLeft:1,paddingRight:1,children:$jsx("text",{fg:theme.error,wrapMode:"word",children:t3("settings.engines.skill.failed",{reason:props.skillError})})}):null]}),$jsx("box",{paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.engines.keys")})})]})}function IntegrationButton(props){let{theme}=useTheme();return $jsx("box",{ref:props.rowRef,flexDirection:"row",paddingLeft:1,paddingRight:1,backgroundColor:props.cursor?theme.primary:theme.backgroundElement,onMouseUp:props.onPress,children:$jsx("text",{fg:props.cursor?theme.selectedListItemText:props.live?theme.text:theme.textMuted,wrapMode:"none",children:props.label})})}var import_react69=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes33}from"@opentui/core";import{TextAttributes as TextAttributes32}from"@opentui/core";function appearanceChoiceLabel(choice,t3){switch(choice.kind){case"theme":return choice.value;case"themeMode":return t3({dark:"settings.appearance.modeDark",light:"settings.appearance.modeLight",auto:"settings.appearance.modeAuto"}[choice.value]);case"transparent":return t3(choice.value?"settings.appearance.enabled":"settings.appearance.disabled");case"focusAccent":return t3(`settings.general.accent${choice.value.charAt(0).toUpperCase()}${choice.value.slice(1)}`);case"splitStyle":return t3({box:"settings.general.splitBox",line:"settings.general.splitLine",rail:"settings.general.splitRail",rule:"settings.general.splitRule"}[choice.value]);case"railFold":return t3({glyphs:"settings.general.railFoldGlyphs",initials:"settings.general.railFoldInitials",hairline:"settings.general.railFoldHairline"}[choice.value]);case"workingBorder":return t3(choice.value==="flow"?"settings.appearance.borderFlow":"settings.appearance.borderStill");case"taskColors":return t3(choice.value==="on"?"settings.appearance.enabled":"settings.appearance.disabled");case"glyphSet":return t3({braille:"settings.appearance.glyphsBraille",starburst:"settings.appearance.glyphsStarburst",ascii:"settings.appearance.glyphsAscii"}[choice.value]);case"colorblind":return t3(choice.value==="on"?"settings.appearance.enabled":"settings.appearance.disabled");case"runningTitle":return t3(choice.value==="shimmer"?"settings.appearance.titleShimmer":"settings.appearance.titleStill")}}import{TextAttributes as TextAttributes31}from"@opentui/core";import{TextAttributes as TextAttributes27}from"@opentui/core";var SHIMMER_CELLS_PER_TICK=2.4,SHIMMER_HALF_WIDTH=5,QUIET_CELLS=24,SHIMMER_CREST=0.65,CYCLE_CELLS=Math.round(SPINNER_TICK_CYCLE*SHIMMER_CELLS_PER_TICK);function shimmerLoop(cells){let loop=cells+2*SHIMMER_HALF_WIDTH+QUIET_CELLS;while(CYCLE_CELLS%loop!==0&&loop<CYCLE_CELLS)loop++;return loop}function shimmerIntensity(index,cells,tick3){let loop=shimmerLoop(cells),centre=tick3*SHIMMER_CELLS_PER_TICK%loop-SHIMMER_HALF_WIDTH,dist=Math.abs(index+0.5-centre);if(dist>=SHIMMER_HALF_WIDTH)return 0;return 0.5+0.5*Math.cos(Math.PI*dist/SHIMMER_HALF_WIDTH)}function shimmerInk(muted,accent,intensity){if(intensity<=0)return muted;if(muted.intent!=="rgb"||accent.intent!=="rgb")return intensity>=SHIMMER_CREST?accent:muted;return mixInk(accent,muted,intensity)}function ShimmerLabel(props){let glyphs=[],cells=0;for(let ch of props.label){let width=charWidth(ch.codePointAt(0)??0),last=glyphs[glyphs.length-1];if(width===0&&last)last.text+=ch;else glyphs.push({text:ch,cell:cells,width});cells+=width}return glyphs.map((glyph,i2)=>{let intensity=shimmerIntensity(glyph.cell+(glyph.width-1)/2,cells,props.tick);return $jsx("span",{fg:shimmerInk(props.muted,props.accent,intensity),attributes:intensity>=SHIMMER_CREST?TextAttributes27.BOLD:void 0,children:glyph.text},i2)})}var import_react68=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes30}from"@opentui/core";var RECENT_ROW_ID="~recent",SCRATCH_SECTION_ID="~scratch",ARCHIVED_ROW_ID="~archived";function routinesRowId(projectKey){return`~routines:${projectKey}`}function projectKeyOfRoutinesRow(id){return id.startsWith("~routines:")?id.slice(10):null}function tabRowId(taskId,tabId){return`${taskId}::${tabId}`}function parseRowId(rowId){let at2=rowId.indexOf("::");if(at2<0)return{taskId:rowId,tabId:null};return{taskId:rowId.slice(0,at2),tabId:rowId.slice(at2+2)}}var UNGROUPED_SECTION_LABEL="Ungrouped";function isRoutineTask(task){return task.routine!==void 0}function isClosedDownProject(tasks2,tabsByTask2){let only=tasks2.length===1?tasks2[0]:void 0;if(!only||only.kind!=="main"&&only.kind!=="dir")return!1;return tabsByTask2.get(only.id)?.length===0}function idleMainIds(input,tasks2){let parents=new Set;for(let task of tasks2)if(task.parentTaskId!==void 0&&task.routine===void 0)parents.add(task.parentTaskId);let idle=new Set;for(let task of tasks2){if(task.kind!=="main"||input.keepTaskIds?.has(task.id)||parents.has(task.id))continue;let tabs=input.tabsByTask.get(task.id),local=(task.origin?.machineId??"local")==="local";if(tabs?tabs.length===0:local&&input.tabsDaemonBacked===!0)idle.add(task.id)}return idle}function isListed(task){let phase=task.deletion?.phase;return phase!=="queued"&&phase!=="running"}function archivedTasks(tasks2){return tasks2.filter((task)=>task.archived===!0&&isListed(task))}function buildSidebarGroups(input){let tasks2=input.tasks.filter((task)=>isListed(task)&&task.archived!==!0),{tabsByTask:tabsByTask2}=input,sortMode=input.sortMode??"default",compare=sortMode==="recent"?compareNewest:sortMode==="attention"?compareTaskGroup(input.activityOf??(()=>{return})):sortMode==="name"?compareName:null,scratchTasks=tasks2.filter(isNoProjectTask);if(compare)scratchTasks.sort(compare);let keyOf=sidebarProjectKeyResolver(tasks2),byProject=new Map;for(let task of tasks2){if(isNoProjectTask(task))continue;let key=keyOf(task),entry2=byProject.get(key)??{repo:task.repo,machineId:task.origin?.machineId??"local",homeMain:!1,mains:[],rest:[]};if(!entry2.repoId&&task.repoId)entry2.repoId=task.repoId;if(sidebarProjectKeyOfTask(task)===key&&!entry2.homeMain){if(entry2.repo=task.repo,entry2.machineId=task.origin?.machineId??"local",entry2.homeMain=task.kind==="main",entry2.homeMain){entry2.mains.unshift(task),byProject.set(key,entry2);continue}}if(task.kind==="main")entry2.mains.push(task);else entry2.rest.push(task);byProject.set(key,entry2)}let orderedKeys=[],seen=new Set;for(let task of tasks2){if(task.kind!=="main")continue;let key=keyOf(task);if(!seen.has(key))seen.add(key),orderedKeys.push(key)}for(let key of byProject.keys())if(!seen.has(key))seen.add(key),orderedKeys.push(key);let ordered=new Map;for(let[key,entry2]of byProject){if(compare)entry2.rest.sort(compare);ordered.set(key,[...entry2.mains,...entry2.rest])}let idle=idleMainIds(input,tasks2),visibleKeys=orderedKeys.filter((key)=>{let list=ordered.get(key);return list?!isClosedDownProject(list,tabsByTask2):!1}),labelled=new Map;for(let key of visibleKeys){let entry2=byProject.get(key);if(entry2)labelled.set(key,{repo:entry2.repo,...entry2.repoId?{repoId:entry2.repoId}:{}})}let projects=[...labelled.values()],groups=[];if(scratchTasks.length>0){let own=scratchTasks.filter((task)=>!isRoutineTask(task)),routines=scratchTasks.filter(isRoutineTask);groups.push({key:SCRATCH_SECTION_ID,repo:"",label:UNGROUPED_SECTION_LABEL,machineId:"local",tasks:[...own,...routines],routineCount:routines.length})}for(let key of visibleKeys){let entry2=byProject.get(key),list=ordered.get(key),project=labelled.get(key);if(!entry2||!list||!project)continue;let kept=list.filter((task)=>!idle.has(task.id)),shown=kept.length>0?kept:list,own=shown.filter((task)=>!isRoutineTask(task)),routines=shown.filter(isRoutineTask);groups.push({key,repo:entry2.repo,label:sidebarRepoLabel(project,projects),machineId:entry2.machineId,tasks:[...own,...routines],routineCount:routines.length})}return groups}function ownTasks(group){return group.tasks.slice(0,group.tasks.length-group.routineCount)}function rowHaystacks(row,liveBranch){if(row.kind==="project")return[row.label];if(row.kind==="routines"||row.kind==="archived")return[];let task=row.task,title=task.kind==="dir"?"":task.title,liveBranchName=liveBranch?.(task),liveTitle=row.kind==="worktree"?row.title:void 0;return[worktreeRowLabel(task,{liveBranch:liveBranchName,liveTitle}),liveBranchName||task.branch,title,repoBasename(task.repo)]}function matchesRow(query,row,liveBranch){return rowHaystacks(row,liveBranch).some((field)=>field!==""&&fuzzyMatch(query,field))}function filterTreeRows(rows,query,liveBranch){let q2=query.trim();if(q2==="")return[...rows];let projectOf=new Map,taskRows=new Map,header=null;for(let row of rows){if(row.kind==="project")header=row.id;else if(header!==null)projectOf.set(row.id,header);if(row.kind==="worktree")taskRows.set(row.id,row)}let parentRowId=(row)=>{let parent=row.kind==="worktree"?row.task.parentTaskId:void 0;return parent!==void 0&&taskRows.has(parent)?parent:void 0},selfMatch=new Set,keep=new Set;for(let row of rows){if(!matchesRow(q2,row,liveBranch))continue;if(selfMatch.add(row.id),keep.add(row.id),row.kind==="project"||row.kind==="routines"||row.kind==="archived")continue;let project=projectOf.get(row.id);if(project!==void 0)keep.add(project);for(let up=parentRowId(row);up!==void 0&&!keep.has(up);){keep.add(up);let parentRow=taskRows.get(up);up=parentRow?parentRowId(parentRow):void 0}}let underMatchedParent=(row)=>{let seen=new Set;for(let up=parentRowId(row);up!==void 0&&!seen.has(up);){if(selfMatch.has(up))return!0;seen.add(up);let parentRow=taskRows.get(up);up=parentRow?parentRowId(parentRow):void 0}return!1},out=[];for(let row of rows){if(row.kind==="project"){if(keep.has(row.id))out.push(row);continue}if(row.kind==="routines"||row.kind==="archived")continue;let project=projectOf.get(row.id);if(project!==void 0&&selfMatch.has(project)||keep.has(row.id)||underMatchedParent(row))out.push(row)}return out}function tabRowActivity(args){return args.tabActivities?.get(args.tabId)}function withRecentRow(rows,recent){if(!recent)return[...rows];return[{kind:"recent",id:RECENT_ROW_ID,task:recent,depth:1},...rows]}var MAX_TREE_DEPTH=3,AUTO_FOLD_CHILDREN=5;function childMarkerOf(task){if(task.parentTaskId===void 0)return null;return isSharedChild(task)?"shared":"worktree"}function loopsBack(task,byId){let seen=new Set([task.id]);for(let at2=task.parentTaskId;at2!==void 0;at2=byId.get(at2)?.parentTaskId){if(seen.has(at2))return at2===task.id;seen.add(at2)}return!1}function indexChildren(groups){let byId=new Map;for(let group of groups)for(let task of group.tasks)byId.set(task.id,task);let children=new Map,nested=new Set;for(let task of byId.values()){let parent=task.parentTaskId;if(parent===void 0||task.routine!==void 0||!byId.has(parent)||loopsBack(task,byId))continue;nested.add(task.id);let siblings=children.get(parent);if(siblings)siblings.push(task);else children.set(parent,[task])}return{children,nested}}function descendantIds(children,id,out=[]){for(let child of children.get(id)??[])out.push(child.id),descendantIds(children,child.id,out);return out}function isFolded(id,childCount,descendants,ctx){if(ctx.collapsed?.has(id))return!0;if(ctx.opened?.has(id)||childCount<=AUTO_FOLD_CHILDREN)return!1;return ctx.selectedId===void 0||!descendants.includes(ctx.selectedId)}function pushTask(rows,task,generation,ctx){let kids=ctx.children.get(task.id),ids=kids?descendantIds(ctx.children,task.id):[],collapsed=kids!==void 0&&ctx.collapsed!==void 0&&isFolded(task.id,kids.length,ids,ctx),level=generation+1,title=ctx.titles?.get(task.id);if(rows.push({kind:"worktree",id:task.id,task,depth:Math.min(level,MAX_TREE_DEPTH),...level>MAX_TREE_DEPTH?{level}:{},...kids?{fold:{count:ids.length,collapsed,descendantIds:ids}}:{},...title?{title}:{}}),collapsed||!kids)return;for(let child of kids)pushTask(rows,child,generation+1,ctx)}function buildRowsFromGroups(input){let ctx={...indexChildren(input.groups),collapsed:input.collapsedTasks,opened:input.openedTasks,selectedId:input.selectedTaskId,titles:input.conversationTitles},rows=[];for(let group of input.groups){let ownCount=group.tasks.length-group.routineCount,top=ownTasks(group).filter((task)=>!ctx.nested.has(task.id));if(top.length===0&&group.routineCount===0)continue;rows.push({kind:"project",id:group.key,repo:group.repo,label:group.label,machineId:group.machineId,depth:0});for(let task of top)pushTask(rows,task,0,ctx);if(group.routineCount>0){let expanded=input.expandedRoutines?.has(group.key)===!0,routines=group.tasks.slice(ownCount);if(rows.push({kind:"routines",id:routinesRowId(group.key),projectKey:group.key,count:group.routineCount,tasks:routines,expanded,depth:1}),expanded)for(let task of routines)pushTask(rows,task,0,ctx)}}return pushArchived(rows,input),rows}function pushArchived(rows,input){let archived=input.archived??[];if(archived.length===0)return;let expanded=input.archivedExpanded===!0;if(rows.push({kind:"archived",id:ARCHIVED_ROW_ID,count:archived.length,expanded,depth:0}),!expanded)return;let ctx={...indexChildren([{key:ARCHIVED_ROW_ID,repo:"",label:"",machineId:"local",tasks:archived,routineCount:0}]),collapsed:input.collapsedTasks,opened:input.openedTasks,selectedId:input.selectedTaskId,titles:input.conversationTitles};for(let task of archived)if(!ctx.nested.has(task.id))pushTask(rows,task,0,ctx)}function treeFlatIds(rows){let ids=[];for(let row of rows)if(row.kind!=="project")ids.push(row.id);return ids}function mainTaskIdOfProject(tasks2,projectKey){for(let task of tasks2){if(task.kind!=="main")continue;if(sidebarProjectKeyOfTask(task)===projectKey)return String(task.id)}return null}var import_react65=__toESM(require_react_production(),1);var EMPTY={},rowStatusCell=createStateCell(EMPTY,"row.status"),transport2=null,rev=-1,local=EMPTY,remote=EMPTY,viewing;function publish2(){let prev=rowStatusCell.get(),next={};for(let[taskId,status]of Object.entries(remote))if(!(taskId in local))next[taskId]=status;for(let[taskId,status]of Object.entries(local))next[taskId]=status;let changed=Object.keys(prev).length!==Object.keys(next).length;for(let[taskId,status]of Object.entries(next)){let old=prev[taskId];if(old!==void 0&&JSON.stringify(old)===JSON.stringify(status))next[taskId]=old;else changed=!0}if(changed)rowStatusCell.set(next)}function acceptRowStatus(payload,force=!1){if(!force&&payload.rev<rev)return;rev=payload.rev,local=payload.tasks,publish2()}function remoteRowStatus(activity,tabActivity){let out={};for(let taskId of new Set([...activity.keys(),...tabActivity?.keys()??[]])){let tabs={};for(let[tabId,entry3]of tabActivity?.get(taskId)??[])tabs[tabId]=tabStatus({activity:{state:entry3.state,at:entry3.at},viewed:!1});let entry2=activity.get(taskId),tabless=entry2&&Object.keys(tabs).length===0?tabStatus({activity:{state:entry2.state,at:entry2.at},viewed:!1}):void 0;out[taskId]={task:taskStatus(tabs,tabless?{tabless}:{}),tabs}}return out}function acceptRemoteActivity(activity,tabActivity){remote=remoteRowStatus(activity,tabActivity),publish2()}function followRemoteActivity(live){let take=()=>{let{activity,tabActivity}=live.get();acceptRemoteActivity(activity,tabActivity)};take();let off=live.subscribe(take);return()=>{off(),acceptRemoteActivity(new Map)}}function taskRowStatus(map,taskId){return map[taskId]?.task}function tabRowStatus(map,taskId,tabId){return map[taskId]?.tabs[tabId]}var read=()=>rowStatusCell.get();function useRowStatusMap(){return import_react65.useSyncExternalStore(rowStatusCell.subscribe,read,read)}function useTaskRowStatus(taskId){let pick=()=>taskRowStatus(rowStatusCell.get(),taskId);return import_react65.useSyncExternalStore(rowStatusCell.subscribe,pick,pick)}function useTabRowStatus(taskId,tabId){let pick=()=>tabRowStatus(rowStatusCell.get(),taskId,tabId);return import_react65.useSyncExternalStore(rowStatusCell.subscribe,pick,pick)}function sendViewing(){if(!transport2||viewing===void 0)return;transport2.viewing(viewing.taskId,viewing.tabId).catch((err)=>logClientError("row-status",err))}function reportViewing(taskId,tabId){let next={taskId,tabId:taskId===null?null:tabId};if(viewing&&viewing.taskId===next.taskId&&viewing.tabId===next.tabId)return;viewing=next,sendViewing()}function reportAnswered(taskId,tabId){transport2?.answered(taskId,tabId).catch((err)=>logClientError("row-status",err))}function noteAnswerInput(data,taskId,tabId){if(data!=="\r"&&!data.endsWith("\r"))return;if(tabRowStatus(rowStatusCell.get(),taskId,tabId)?.kind!=="needs-input")return;reportAnswered(taskId,tabId)}async function reloadRowStatus(){let current2=transport2;if(!current2)return;sendViewing();try{acceptRowStatus(await current2.list(),!0)}catch(err){logClientError("row-status",err)}}function attachRowStatusTransport(next){if(transport2=next,rev=-1,!next)return()=>{};let off=next.onChanged((payload)=>acceptRowStatus(payload));return reloadRowStatus(),()=>{if(off(),transport2===next)transport2=null}}function useRowStatusSync(channel,connection){import_react65.useEffect(()=>{if(!channel)return;let detach=attachRowStatusTransport(channel),last=connection(),off=connection.subscribe(()=>{let now=connection();if(now==="online"&&last!=="online")reloadRowStatus();last=now});return()=>{off(),detach()}},[channel,connection])}function useViewingReport(taskId,tabId){import_react65.useEffect(()=>{reportViewing(taskId,tabId)},[taskId,tabId]),import_react65.useEffect(()=>()=>reportViewing(null,null),[])}import{TextAttributes as TextAttributes28}from"@opentui/core";function CollapseButton(props){let{theme}=useTheme(),onMouseUp=(evt)=>{evt.stopPropagation(),props.onToggle()},glyph=$jsx("text",{fg:theme.textMuted,attributes:TextAttributes28.BOLD,wrapMode:"none",children:props.collapsed?"\u203A\u203A":"\u2039\u2039"});if(props.inline)return $jsx("box",{flexShrink:0,onMouseUp,children:glyph});return $jsx("box",{position:"absolute",bottom:0,right:1,flexShrink:0,onMouseUp,children:glyph})}var import_react67=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes29}from"@opentui/core";import{stat}from"fs/promises";import{join as join2}from"path";var BRANCH_POLL_TIMEOUT_MS=2000,BRANCH_SLOW_RETRY_MS=30000,BRANCH_MIN_POLL_INTERVAL_MS=1500,headCache=new Map;async function headFingerprint(repo){try{let st2=await stat(join2(repo,".git","HEAD"));return`${st2.mtimeMs}:${st2.size}`}catch{return null}}async function resolveBranchHead(repo,signal,spawn3=spawnCapture){let fingerprint=await headFingerprint(repo);if(fingerprint!==null){let cached=headCache.get(repo);if(cached&&cached.fingerprint===fingerprint)return cached.value}let value="",resolved=!1;recordSpawn("sidebar.gitHead",["git","symbolic-ref","--short","HEAD"],repo);let ref=await spawn3("git",["symbolic-ref","--short","HEAD"],{cwd:repo,env:readOnlyGitProcessEnv(),signal}),name=ref.status===0?ref.stdout.trim():"";if(name&&name!=="HEAD")value=name,resolved=!0;else if((await spawn3("git",["rev-parse","--verify","HEAD"],{cwd:repo,env:readOnlyGitProcessEnv(),signal})).status===0)value="(detached)",resolved=!0;if(resolved&&fingerprint!==null)headCache.set(repo,{fingerprint,value});return value}var poller2=createBackgroundPoller({initial:"",timeoutMs:BRANCH_POLL_TIMEOUT_MS,slowRetryMs:BRANCH_SLOW_RETRY_MS,minIntervalMs:BRANCH_MIN_POLL_INTERVAL_MS,run:(repo,signal)=>resolveBranchHead(repo,signal)});function currentBranch(repo){return poller2.read(repo)}function pollCurrentBranch(repo){poller2.poll(repo)}function machineStateKey(state){switch(state){case"online":return null;case"connecting":return"tasks.machine.connecting";case"unsupported":return"tasks.machine.unsupported";case"mismatch":return"tasks.machine.mismatch";default:return"tasks.machine.offline"}}function remoteRowCaption(mark,t3){let where=t3("tasks.machine.runsOn",{host:mark.host}),word=machineStateKey(mark.state);if(word)return`${where} \xB7 ${t3(word)}`;return mark.version?`${where} \xB7 v${mark.version}`:where}function remoteMarkLive(mark){return mark.state==="online"}function applyMachineLayer(rows,machines){if(machines.length===0)return rows;let byAlias=new Map(machines.map((entry2)=>[entry2.alias,entry2])),kept=[],header=-1,dropped=!1,closeHeader=()=>{if(header>=0&&dropped&&header===kept.length-1)kept.pop()};for(let row of rows){if(row.kind==="project"){closeHeader(),header=kept.length,dropped=!1,kept.push(row);continue}if(row.kind==="routines"||row.kind==="recent"||row.kind==="archived"){kept.push(row);continue}let alias=row.task.origin?.machineId??"local";if(alias==="local"){kept.push(row);continue}let entry2=byAlias.get(alias);if(!entry2){dropped=!0;continue}kept.push({...row,remote:{host:entry2.hostLabel||row.task.origin?.hostLabel||alias,state:entry2.state,...entry2.version?{version:entry2.version}:{}}})}return closeHeader(),kept}var import_react66=__toESM(require_react_production(),1);var NO_SUBSCRIBE=()=>()=>{};function mostUrgentStatus(map,taskIds){let children={};for(let id of taskIds){let status=taskRowStatus(map,id);if(status)children[id]={...status,alive:!0,restored:!1,tracked:!0}}return Object.keys(children).length===0?void 0:taskStatus(children)}function useMostUrgentStatus(taskIds,enabled){let read2=()=>{let status=enabled?mostUrgentStatus(rowStatusCell.get(),taskIds):void 0;return status?`${status.kind}|${status.reason??""}`:""},key=import_react66.useSyncExternalStore(enabled?rowStatusCell.subscribe:NO_SUBSCRIBE,read2,read2);return import_react66.useMemo(()=>{if(key==="")return;let[kind,reason]=key.split("|");return{kind,since:0,...reason?{reason}:{}}},[key])}import{MouseButton as MouseButton2}from"@opentui/core";var indentOf=(depth)=>depth>0?" ".repeat(1+(depth-1)*2):"";function treeLabelBudget(shared2,reserved){let width=shared2.width??SIDEBAR_WIDTH;return Math.max(6,width-3-reserved)}function clusterCells(text){let cells=1;for(let ch of text)cells+=charWidth(ch.codePointAt(0)??0);return cells}function MoveChip(props){let{theme}=useTheme(),t3=useT();if(props.shared.movingRowId!==props.rowId)return null;return $jsx("text",{fg:theme.info,wrapMode:"none",flexShrink:0,children:t3("tasks.moveChip").trim()})}function RowShell(props){let{theme}=useTheme(),shared2=props.shared,selection=resolveRowSelectionChrome2(theme,{cursor:shared2.cursorIndex===props.flatIndex,selected:shared2.activeRowId===props.rowId});return $jsxs("box",{ref:(renderable)=>{if(!renderable)return;return shared2.rowEls.set(props.flatIndex,renderable),()=>{if(shared2.rowEls.get(props.flatIndex)===renderable)shared2.rowEls.delete(props.flatIndex)}},width:"100%",flexDirection:"row",gap:0,backgroundColor:selection.backgroundColor,onMouseUp:(evt)=>{if(evt.stopPropagation(),evt.button===MouseButton2.RIGHT&&shared2.onContextMenu){shared2.onContextMenu(props.flatIndex,props.rowId,evt.x,evt.y);return}shared2.onPress(props.flatIndex,props.rowId)},children:[$jsx("text",{fg:selection.markerColor,wrapMode:"none",children:selection.marker}),props.depth>0?$jsx("text",{wrapMode:"none",flexShrink:0,children:indentOf(props.depth)}):null,props.children]})}var REMOTE_TITLE_CELLS=12,SHARED_MARK="\u2442",WORKTREE_MARK="\u2387",FOLD_OPEN="\u25BE",FOLD_CLOSED="\u25B8";function statusAgeLabel(status){if(!status||status.since<=0)return null;if(status.kind!=="running"&&status.kind!=="attention"&&status.kind!=="needs-input")return null;return relativeAge(status.since)}function conversationActivity(task,tabStates){let alias=task.ptyAlias,tabs=tabStates?.get(alias?.taskId??task.id);if(!tabs)return;if(alias)return tabRowActivity({tabId:alias.tabId,tabActivities:tabs});let latest;for(let activity of tabs.values())if(!latest||activity.at>latest.at)latest=activity;return latest}function useStateCell(args){let{theme}=useTheme(),baseView=useTabRowBaseView({task:args.task,status:args.status,lifecycle:args.lifecycle}),frame2=useSpinnerFrame(baseView.loading),rowView=withSpinnerFrame(baseView,()=>frame2),pulsing=useDonePulse(completionStampOf(args.activity)),fg=pulsing?theme.success:rowView.loading&&rowView.tone==="primary"?breathColor(theme.primary,theme.textMuted,frame2):toneColor2(theme,rowView.tone);return{rowView,fg,pulsing,frame:frame2}}function useTaskStateCell(task,shared2){let alias=task.ptyAlias,rollup=useTaskRowStatus(task.id),aliased=useTabRowStatus(alias?.taskId??task.id,alias?.tabId??""),status=alias&&rollup?.kind!=="busy"?aliased:rollup,cell=useStateCell({task,status,lifecycle:shared2.engineLifecycle?.get(task.id),activity:conversationActivity(task,shared2.engineTabState)});return{status,...cell}}function FoldCluster(props){let{theme}=useTheme(),glyphs=useGlyphs(),{fold}=props,urgent=useMostUrgentStatus(fold.descendantIds,fold.collapsed),mark=rowStatusGlyph(urgent,glyphs),frame2=useSpinnerFrame(fold.collapsed&&mark.spinning);return $jsxs("box",{flexDirection:"row",gap:1,flexShrink:0,onMouseUp:(evt)=>{evt.stopPropagation(),props.shared.onToggleFold?.(props.task.id)},children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:fold.collapsed?FOLD_CLOSED:FOLD_OPEN}),fold.collapsed?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:String(fold.count)}):null,fold.collapsed&&urgent?$jsx("text",{fg:toneColor2(theme,sidebarTone(mark.tone)),wrapMode:"none",children:mark.spinning?breathGlyph(glyphs.spinner,frame2):mark.glyph}):null]})}function WorktreeTreeRow(props){let{theme}=useTheme(),t3=useT(),glyphs=useGlyphs(),kv=useOptionalKV(),shared2=props.shared,task=props.task,chip=sidebarPrChip(task,glyphs),livePath=rowLiveBranchPath(task);usePollOnClock(livePath,pollCurrentBranch);let label=worktreeRowLabel(task,{liveTitle:props.title,...livePath?{liveBranch:currentBranch(livePath)}:{}}),moving=shared2.movingRowId===props.rowId,{status,rowView,fg,pulsing,frame:frame2}=useTaskStateCell(task,shared2),age=statusAgeLabel(status);useClockTick(age!==null);let deletionPhase=task.deletion?.phase,deleting=deletionPhase==="queued"||deletionPhase==="running",deleteFailed=deletionPhase==="error",checkoutPercent=status?.kind==="busy"&&status.reason==="job"?shared2.taskJobs?.get(task.id)?.progress:void 0,checkoutText=checkoutPercent===void 0?null:`${checkoutPercent}%`,deletionWord=deleting||deleteFailed?t3(deleteFailed?"tasks.subtitle.deleteFailed":"tasks.subtitle.deleting"):null;useClockTick((shared2.rowTokens?.get(task.id)?.length??0)>0);let tokens=liveRowTokens(shared2.rowTokens,task.id,Date.now()),remote2=props.remote,remoteLive=remote2?remoteMarkLive(remote2):!0,caption=remote2&&shared2.cursorIndex===props.flatIndex?remoteRowCaption(remote2,t3):null,marker=childMarkerOf(task),extraRepoText=task.extraRepos?.length?`+${task.extraRepos.length}`:null,fold=props.fold,reserved=2+2*((props.depth??1)-1)+tokens.reduce((cells,token)=>cells+clusterCells(token.text),0)+(deletionWord?clusterCells(deletionWord):0)+(checkoutText?clusterCells(checkoutText):0)+(age?clusterCells(age):0)+(props.level!==void 0?clusterCells(String(props.level)):0)+(marker?clusterCells(SHARED_MARK):0)+(extraRepoText?clusterCells(extraRepoText):0)+(fold?clusterCells(fold.collapsed?FOLD_CLOSED:FOLD_OPEN)+(fold.collapsed?clusterCells(String(fold.count))+clusterCells(glyphs.idle):0):0)+(remote2?clusterCells(glyphs.remote):0)+(task.pinned===!0?2:0)+(chip?2:0)+(moving?clusterCells(t3("tasks.moveChip").trim()):0),budget=treeLabelBudget(shared2,reserved),captionCells=caption?Math.max(0,budget-Math.min(displayWidth(label),REMOTE_TITLE_CELLS)-1):0,remoteText=remote2?captionCells>2?`${glyphs.remote} ${truncateEndCells(caption??"",captionCells,charWidth)}`:glyphs.remote:null,shimmer=rowView.loading&&!pulsing&&normalizeRunningTitle(kv?.get(RUNNING_TITLE_KEY,DEFAULT_RUNNING_TITLE))==="shimmer",clipped=truncateEndCells(label,budget-(remoteText?displayWidth(remoteText)-1:0),charWidth);return $jsxs(RowShell,{rowId:props.rowId,flatIndex:props.flatIndex,depth:props.depth??1,shared:shared2,children:[$jsx("text",{fg,attributes:pulsing?TextAttributes29.BOLD:void 0,wrapMode:"none",width:2,flexShrink:0,children:`${rowView.stateGlyph} `}),$jsxs("box",{flexDirection:"row",flexGrow:1,paddingRight:1,gap:1,children:[$jsx("text",{fg:task.origin?.stale||!remoteLive?theme.textMuted:theme.text,attributes:pulsing?TextAttributes29.BOLD:void 0,wrapMode:"none",flexBasis:0,flexGrow:1,flexShrink:1,children:shimmer?$jsx(ShimmerLabel,{label:clipped,tick:frame2,muted:theme.textMuted,accent:theme.primary}):clipped}),task.pinned===!0?$jsx("text",{fg:theme.warning,wrapMode:"none",flexShrink:0,children:"\u25B4"}):null,chip?$jsx("text",{fg:toneColor2(theme,chip.tone),wrapMode:"none",flexShrink:0,children:chip.glyph}):null,tokens.map((token)=>$jsx("text",{fg:token.tone?toneColor2(theme,rowTokenTone(token.tone)):theme.textMuted,wrapMode:"none",flexShrink:0,children:token.text},`${token.source}\x00${token.key}`)),deletionWord?$jsx("text",{fg:deleteFailed?theme.error:theme.textMuted,wrapMode:"none",flexShrink:0,children:deletionWord}):null,$jsx(MoveChip,{rowId:props.rowId,shared:shared2}),checkoutText?$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:checkoutText}):null,age?$jsx("text",{fg:theme.textMuted,attributes:TextAttributes29.DIM,wrapMode:"none",flexShrink:0,children:age}):null,props.level!==void 0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:String(props.level)}):null,extraRepoText?$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:extraRepoText}):null,marker?$jsx("text",{fg:marker==="shared"?theme.info:theme.textMuted,wrapMode:"none",flexShrink:0,children:marker==="shared"?SHARED_MARK:WORKTREE_MARK}):null,fold?$jsx(FoldCluster,{task,fold,shared:shared2}):null,remoteText?$jsx("text",{fg:remoteLive?theme.textMuted:theme.warning,wrapMode:"none",flexShrink:0,children:remoteText}):null]})]})}function useTabRowBaseView(args){let t3=useT(),glyphs=useGlyphs(),{task,status,lifecycle}=args;return import_react67.useMemo(()=>{return buildSidebarRowView({task,status,lifecycle,spinnerFrame:0,subtitleBudget:0,truncateBranch:truncateBranchLabel,glyphs})},[task,status,lifecycle,t3,glyphs])}function RecentJumpRow(props){let{theme}=useTheme(),t3=useT();return $jsxs(RowShell,{rowId:props.rowId,flatIndex:props.flatIndex,depth:1,shared:props.shared,children:[$jsx("text",{fg:theme.accent,wrapMode:"none",width:2,flexShrink:0,children:"\u21A9 "}),$jsx("text",{fg:theme.text,wrapMode:"none",flexShrink:1,children:t3("tasks.recentJump",{title:props.task.title})})]})}var DEFAULT_COLLAPSED_RAIL_STYLE="glyphs",COLLAPSED_RAIL_STYLES=["glyphs","initials","hairline"],COLLAPSED_RAIL_WIDTH={hairline:2,glyphs:4,initials:7};function railInitials(title){let words=title.trim().split(/[\s_\-/.]+/).filter(Boolean);if(words.length===0)return"\xB7\xB7";if(words.length===1)return words[0].slice(0,2).padEnd(2," ");return`${words[0][0]??""}${words[1][0]??""}`}function useRailSections(props){let treeRows=import_react68.useMemo(()=>buildRowsFromGroups({groups:props.groups}),[props.groups]),tasks2=import_react68.useMemo(()=>treeRows.flatMap((row)=>row.kind==="worktree"?[row.task]:[]),[treeRows]),statuses=useRowStatusMap(),spinning=tasks2.some((task)=>rowIsLoading(taskRowStatus(statuses,task.id))),frame2=useSpinnerFrame(spinning),glyphs=useGlyphs(),sections=[];for(let row of treeRows){if(row.kind==="project"){sections.push({key:row.id,label:row.label,rows:[]});continue}if(row.kind!=="worktree")continue;let base=buildSidebarRowView({task:row.task,status:taskRowStatus(statuses,row.task.id),spinnerFrame:frame2,subtitleBudget:0,truncateBranch:(branch)=>branch,glyphs}),view=withSpinnerFrame(base,()=>frame2);sections[sections.length-1]?.rows.push({task:row.task,glyph:view.stateGlyph,tone:view.tone,breath:spinning&&view.loading?frame2:void 0,selected:row.task.id===props.selectedId,depth:row.depth,marker:childMarkerOf(row.task)})}return sections}function projectHeading(label,width){let initial=(new Intl.Segmenter().segment(label.trim()).containing(0)?.segment??"\xB7").toLowerCase(),cells=displayWidth(initial),head=cells>0&&cells<=width?initial:"\xB7";return head+"\u2500".repeat(width-displayWidth(head))}function CollapsedRail(props){let{theme}=useTheme(),sections=useRailSections(props),width=COLLAPSED_RAIL_WIDTH[props.style];return $jsxs("box",{width,flexShrink:0,flexDirection:"column",backgroundColor:theme.backgroundPanel,children:[sections.map((section)=>$jsxs(import_react68.Fragment,{children:[$jsx("text",{fg:theme.textMuted,attributes:TextAttributes30.BOLD,wrapMode:"none",flexShrink:0,children:projectHeading(section.label,width)}),section.rows.map((row)=>$jsx(RailRowView,{row,style:props.style,onSelect:props.onSelect},row.task.id))]},section.key)),$jsx(CollapseButton,{collapsed:!0,onToggle:props.onExpand})]})}function RailRowView(props){let{theme}=useTheme(),{row}=props,fg=row.breath!==void 0&&row.tone==="primary"?breathColor(theme.primary,theme.textMuted,row.breath):toneColor2(theme,row.tone),chrome=resolveRowSelectionChrome2(theme,{cursor:row.selected});return $jsxs("box",{flexShrink:0,flexDirection:"row",backgroundColor:chrome.backgroundColor,onMouseUp:()=>props.onSelect(row.task.id),children:[props.style==="hairline"?null:$jsx("text",{fg:chrome.markerColor??fg,wrapMode:"none",flexShrink:0,children:row.selected?chrome.marker:" "}),$jsx(RailCell,{row,style:props.style,fg})]})}function RailCell(props){let{theme}=useTheme(),{row,fg}=props,bold=row.selected?TextAttributes30.BOLD:void 0,indent=" ".repeat(Math.min(row.depth-1,props.style==="initials"?2:1)),mark=row.marker?$jsx("text",{fg:row.marker==="shared"?theme.info:theme.textMuted,wrapMode:"none",flexShrink:0,children:row.marker==="shared"?SHARED_MARK:WORKTREE_MARK}):null;switch(props.style){case"hairline":return $jsx("text",{fg,wrapMode:"none",children:row.selected?"\u2588 ":"\u258E "});case"glyphs":return $jsxs("box",{flexDirection:"row",flexShrink:0,children:[$jsx("text",{fg,attributes:bold,wrapMode:"none",flexShrink:0,children:`${indent}${row.glyph}`}),mark,$jsx("text",{wrapMode:"none",flexShrink:0,children:" ".repeat(Math.max(0,2-indent.length-(mark?1:0)))})]});default:return $jsxs("box",{flexDirection:"row",flexShrink:0,children:[$jsx("text",{fg,wrapMode:"none",flexShrink:0,children:`${indent}${row.glyph}${mark?"":" "}`}),mark,$jsx("text",{fg:row.selected?theme.text:theme.textMuted,attributes:bold,wrapMode:"none",flexShrink:0,children:railInitials(row.task.title??"")})]})}}import{RGBA as RGBA3}from"@opentui/core";var TITLE_LABEL_CELLS=32,UNFOCUSED_SHARE=0.55,CLEAR=RGBA3.fromInts(0,0,0,0);function runningPaneFlow(accent,inactive,focused,tick3,partnerDeg){let ramp=flowPalette(accent,partnerDeg),palette=focused?ramp:ramp.map((ink)=>mixInk(ink,inactive,UNFOCUSED_SHARE));return function(buffer){let cells=perimeter(this.width,this.height),{char,attributes}=buffer.buffers;cells.forEach(([dx,dy],index)=>{let x2=this.x+dx,y3=this.y+dy;if(x2<0||y3<0||x2>=buffer.width||y3>=buffer.height)return;let cell=y3*buffer.width+x2,code=char[cell]??0;if(code<=32||code>1114111)return;let ink=flowInk(palette,flowPhase(index,cells.length,tick3));if(!ink)return;buffer.setCellWithAlphaBlending(x2,y3,String.fromCodePoint(code),ink,CLEAR,attributes[cell]??0)})}}function runningPaneTitle(label,word){return` ${truncateEndCells(label,TITLE_LABEL_CELLS,charWidth)} \xB7 ${word} `}function AppearancePreview(props){let{current:current2}=props,theme=useTheme().preview(current2),t3=useT(),size=useTerminalSize(),narrow=size.width<75,short=size.height<30,fold=current2.railFoldStyle,{spinner,done,idle}=GLYPH_SETS[current2.glyphSet],tick3=useSpinnerFrame(!0),working=breathGlyph(spinner,tick3),workingInk=breathColor(theme.primary,theme.textMuted,tick3),folded=[{id:"ui",label:{glyphs:`\u258C${working}`,initials:`\u258C${working} UI`,hairline:"\u2588"}[fold]},{id:"api",label:{glyphs:` ${done}`,initials:` ${done} API`,hairline:"\u258E"}[fold]},{id:"review",label:{glyphs:` ${idle}`,initials:` ${idle} QA`,hairline:"\u258E"}[fold]}],marked=current2.taskColors==="on",flowing=current2.workingBorder==="flow",workingTaskInk=marked?taskColor("preview-ui",theme):void 0,inks=diffInks(theme,current2.colorblind==="on"),pane=(divider,edge,name,nameInk)=>paneBoxProps(paneChrome(current2.splitStyle,divider),{edge,name,nameInk}),namesOnRule=paneChrome(current2.splitStyle,void 0).nameOnRule,tasksInk=theme.textMuted;return $jsxs("box",{flexDirection:"column",flexShrink:0,border:!0,borderColor:theme.border,backgroundColor:theme.background,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1,backgroundColor:theme.backgroundPanel,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes31.BOLD,children:t3("settings.appearance.preview")}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:current2.themeName})]}),$jsxs("box",{flexDirection:"row",flexGrow:1,children:[$jsxs("box",{width:COLLAPSED_RAIL_WIDTH[fold],flexShrink:0,flexDirection:"column",backgroundColor:theme.backgroundPanel,children:[$jsx("text",{fg:props.active==="railFold"?theme.focusAccent:theme.textMuted,children:"\u2039"}),folded.map((row,i2)=>$jsx("text",{fg:i2===0?workingInk:i2===1?theme.success:theme.textMuted,wrapMode:"none",children:row.label},row.id))]}),$jsxs("box",{flexGrow:2,flexBasis:0,flexShrink:1,flexDirection:"column",...pane(void 0,theme.border,t3("settings.appearance.tasks"),theme.textMuted),paddingLeft:1,paddingRight:1,backgroundColor:theme.backgroundPanel,children:[!namesOnRule&&$jsx("text",{fg:tasksInk,children:t3("settings.appearance.tasks")}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:"demo / workspace"}),$jsxs("box",{flexDirection:"row",children:[$jsx("text",{fg:theme.focusAccent,attributes:TextAttributes31.BOLD,wrapMode:"none",children:"\u258C "}),$jsx("text",{fg:workingInk,wrapMode:"none",children:`${working} `}),$jsx("text",{fg:theme.text,attributes:TextAttributes31.BOLD,wrapMode:"none",children:current2.runningTitle==="shimmer"?$jsx(ShimmerLabel,{label:"UI polish",tick:tick3,muted:theme.textMuted,accent:theme.primary}):"UI polish"})]}),$jsxs("box",{flexDirection:"row",children:[$jsx("text",{wrapMode:"none",children:" "}),$jsxs("text",{fg:theme.text,wrapMode:"none",children:["API tests ",done]})]}),!short&&$jsxs("box",{flexDirection:"row",children:[$jsx("text",{wrapMode:"none",children:" "}),$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:["Review ",idle]})]})]}),$jsxs("box",{flexGrow:5,flexBasis:0,flexShrink:1,flexDirection:"column",...pane("left",theme.focusAccent,t3("settings.appearance.terminal"),theme.focusAccent),...flowing?{renderAfter:runningPaneFlow(workingTaskInk??theme.focusAccent,theme.border,!0,tick3,workingTaskInk?TASK_PARTNER_HUE_DEG:void 0),...namesOnRule?{}:{title:runningPaneTitle("UI polish",t3("workspace.inbox.state.running"))}}:{},paddingLeft:1,paddingRight:1,children:[!namesOnRule&&$jsxs("text",{fg:theme.focusAccent,attributes:TextAttributes31.BOLD,wrapMode:"none",children:["\u258C ",t3("settings.appearance.terminal")]}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:"UI polish / main"}),!short&&$jsx("text",{fg:theme.text,wrapMode:"none",children:"$ bun test"}),$jsxs("text",{fg:theme.success,wrapMode:"none",children:["\u2713 ",t3("settings.appearance.testsPassed")]}),!short&&$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:"2 pass \xB7 0 fail"}),$jsx("text",{fg:theme.text,wrapMode:"none",children:"$ \u258C"})]}),!narrow&&$jsxs("box",{flexGrow:2,flexBasis:0,flexShrink:1,flexDirection:"column",...pane("left",theme.border,t3("settings.appearance.files"),theme.textMuted),paddingLeft:1,paddingRight:1,children:[!namesOnRule&&$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("settings.appearance.files")}),$jsx("text",{fg:theme.text,wrapMode:"none",children:"\u25BE src"}),$jsxs("text",{fg:inks.added,wrapMode:"none",children:[" ","app.ts +8"]}),$jsxs("text",{fg:inks.removed,wrapMode:"none",children:[" ","ui.tsx \u22123"]}),!short&&$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:[" ","README.md"]})]})]}),$jsx("text",{fg:theme.textMuted,bg:theme.backgroundPanel,wrapMode:"none",children:` \u25CF main ${t3(current2.transparentBackground?"settings.appearance.transparent":"settings.appearance.opaque")}`})]})}function AppearanceSettingsSection(props){let{theme}=useTheme(),t3=useT();return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes32.BOLD,children:t3("settings.general.appearance")}),$jsx(AppearancePreview,{current:props.appearance.current}),$jsx("text",{fg:theme.textMuted,children:t3("settings.appearance.openHint")}),$jsx("box",{flexDirection:"column",children:APPEARANCE_SETTINGS.map((setting)=>{let index=rowIndex(props.rows,`appearance:${setting}`);return $jsx(Row,{cursor:props.level==="body"&&props.bodyRow===index,rowRef:props.rowRef(index),onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(index),props.appearance.open(setting)},fg:theme.text,children:`${t3(`settings.general.${setting}`)}: ${appearanceChoiceLabel(currentAppearanceChoice(props.appearance.current,setting),t3)} \u203A`},setting)})})]})}function SettingsSectionSidebar(props){let{theme}=useTheme(),t3=useT();return $jsx("box",{flexDirection:"column",flexShrink:0,width:SECTIONS_SIDEBAR_WIDTH,gap:1,children:SECTIONS.map((s2,i2)=>{let isSection=i2===props.cursor,isSidebarFocused=isSection&&props.level==="sidebar";return $jsx("box",{paddingLeft:1,paddingRight:1,backgroundColor:isSidebarFocused?theme.primary:void 0,onMouseUp:()=>props.switchSection(s2.id),children:$jsx("text",{fg:isSidebarFocused?theme.selectedListItemText:isSection?theme.accent:theme.textMuted,attributes:isSection?TextAttributes33.BOLD:void 0,wrapMode:"none",children:t3(`settings.sections.${s2.id}`)})},s2.id)})})}function UsageDashboard(props){let{theme}=useTheme(),t3=useT(),toneColor3={ok:theme.success,warn:theme.warning,crit:theme.error},now=Date.now();return $jsx("box",{flexDirection:"column",flexShrink:0,alignSelf:"flex-start",gap:0,children:[...props.usage.entries()].map(([vendor,usage])=>$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes33.BOLD,wrapMode:"none",children:`${engineDisplayName(vendor).toUpperCase()} ${t3("settings.general.usage")}`}),usageRows(usage,now).map((row)=>$jsxs("box",{flexDirection:"row",gap:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:row.label}),$jsx("text",{fg:toneColor3[row.tone],wrapMode:"none",children:`${row.bar} ${row.percentText}`}),row.resetText?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:row.resetText}):null]},row.label))]},vendor))})}function GeneralSettingsSection(props){let{prefs}=props,themeCtx=useTheme(),{theme}=themeCtx,t3=useT(),kv=useKV(),rows=import_react69.useMemo(()=>generalRows(),[]),rowIdx=(id)=>rowIndex(rows,id),isBodyCursor=(row)=>props.level==="body"&&props.bodyRow===row,activate=(row,action)=>()=>{props.setLevel("body"),props.setBodyRow(row),action()},{labelColumn,showHint}=generalLabelLayout(useTerminalSize().width,useDialogPaddingX()),hint=(key)=>showHint?t3(key):void 0,pad=(label)=>label+" ".repeat(Math.max(0,labelColumn-displayWidth(label))),check=(on)=>on?"[x]":"[ ]",radio=(on)=>on?"(\u25CF)":"( )",toastRow=rowIdx("toast"),soundRow=rowIdx("sound"),soundVolumeRow=rowIdx("sound-volume"),crossTaskRow=rowIdx("cross-task"),finishedAlertsRow=rowIdx("finished-alerts"),keyHintsRow=rowIdx("key-hints"),zenDefaultOnRow=rowIdx("zen-default-on"),updateChannelRow=rowIdx("update-channel"),updateCheckRow=rowIdx("update-check"),updateNotifyRow=rowIdx("update-notify"),{info:checked,state:checkState}=props.updateCheck,checkLabelKey=checkState==="checking"?"settings.general.updateChecking":checked?.hasUpdate?"settings.general.updateOpenPageRow":"settings.general.updateCheck",checkResult=checkState!=="done"?null:checked===null?{text:t3("update.latestUnknown"),fg:theme.textMuted}:checked.hasUpdate?{text:t3("update.available",{version:checked.latest}),fg:theme.warning}:{text:t3("update.upToDate"),fg:theme.success},editorKindRow=rowIdx("editor-kind"),editorCustomRow=rowIdx("editor-custom"),worktreeBaseRow=rowIdx("worktree-base"),worktreeCustomRow=rowIdx("worktree-custom"),scrollbackRow=rowIdx("scrollback-rows"),tabStripHideSingleRow=rowIdx("tab-strip-hide-single");return $jsxs("box",{flexDirection:"row",gap:2,children:[$jsxs("box",{flexDirection:"column",gap:1,flexGrow:1,flexShrink:1,children:[$jsx(SubSection,{title:t3("settings.general.language"),hint:t3("settings.general.languageHint"),children:LOCALES.map((loc)=>{let langRow=rowIdx(languageRowId(loc.id)),isSelected=props.currentLocale===loc.id;return $jsx(Row,{cursor:isBodyCursor(langRow),rowRef:props.rowRef(langRow),onMouseUp:activate(langRow,()=>props.selectLanguage(loc.id)),fg:isSelected?theme.accent:theme.text,bold:isBodyCursor(langRow)||isSelected,children:`${radio(isSelected)} ${loc.label}`},loc.id)})}),$jsx(AppearanceSettingsSection,{...props,rows,appearance:props.appearance}),$jsxs(SubSection,{title:t3("settings.general.notifications"),hint:t3("settings.general.notificationsHint"),children:[$jsx(Row,{cursor:isBodyCursor(toastRow),rowRef:props.rowRef(toastRow),onMouseUp:activate(toastRow,prefs.toggleToast),fg:prefs.toastEnabled()?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.toastHint"),children:pad(`${check(prefs.toastEnabled())} ${t3("settings.general.toast")}`)}),$jsx(Row,{cursor:isBodyCursor(soundRow),rowRef:props.rowRef(soundRow),onMouseUp:activate(soundRow,prefs.toggleSound),fg:prefs.soundEnabled()?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.soundHint"),children:pad(`${check(prefs.soundEnabled())} ${t3("settings.general.sound")}`)}),$jsx(Row,{cursor:isBodyCursor(soundVolumeRow),rowRef:props.rowRef(soundVolumeRow),onMouseUp:activate(soundVolumeRow,prefs.cycleSoundVolume),fg:prefs.soundEnabled()?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.soundVolumeHint"),children:pad(t3("settings.general.soundVolume",{percent:String(Math.round(prefs.soundVolume()*100))}))}),$jsx(Row,{cursor:isBodyCursor(crossTaskRow),rowRef:props.rowRef(crossTaskRow),onMouseUp:activate(crossTaskRow,prefs.toggleCrossTask),fg:prefs.crossTaskEnabled()?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.crossTaskHint"),children:pad(`${check(prefs.crossTaskEnabled())} ${t3("settings.general.crossTask")}`)}),$jsx(Row,{cursor:isBodyCursor(finishedAlertsRow),rowRef:props.rowRef(finishedAlertsRow),onMouseUp:activate(finishedAlertsRow,prefs.toggleFinishedAlerts),fg:prefs.finishedAlertsEnabled()?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.finishedAlertsHint"),children:pad(`${check(prefs.finishedAlertsEnabled())} ${t3("settings.general.finishedAlerts")}`)})]}),$jsx(SubSection,{title:t3("settings.general.keyHints"),hint:t3("settings.general.keyHintsHint"),children:$jsx(Row,{cursor:isBodyCursor(keyHintsRow),rowRef:props.rowRef(keyHintsRow),onMouseUp:activate(keyHintsRow,()=>toggleKeyHints(kv)),fg:keyHintsToggleOn(kv)?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.keyHintsShowHint"),children:pad(`${check(keyHintsToggleOn(kv))} ${t3("settings.general.keyHintsShow")}`)})}),$jsx(SubSection,{title:t3("settings.general.zen"),hint:t3("settings.general.zenHint"),children:$jsx(Row,{cursor:isBodyCursor(zenDefaultOnRow),rowRef:props.rowRef(zenDefaultOnRow),onMouseUp:activate(zenDefaultOnRow,prefs.toggleZenDefaultOn),fg:prefs.zenDefaultOn()?theme.accent:theme.textMuted,bold:!0,children:`${check(prefs.zenDefaultOn())} ${t3("settings.general.zenDefaultOn")}`})}),$jsxs(SubSection,{title:t3("settings.general.updates"),hint:t3("settings.general.updatesHint"),children:[$jsx(Row,{cursor:isBodyCursor(updateChannelRow),rowRef:props.rowRef(updateChannelRow),onMouseUp:activate(updateChannelRow,prefs.cycleUpdateChannel),fg:theme.accent,bold:!0,hint:hint("settings.general.updateChannelHint"),children:pad(t3("settings.general.updateChannel",{channel:t3(`settings.general.updateChannelName.${prefs.updateChannel()}`)}))}),$jsx(Row,{cursor:isBodyCursor(updateNotifyRow),rowRef:props.rowRef(updateNotifyRow),onMouseUp:activate(updateNotifyRow,prefs.toggleUpdateNotify),fg:prefs.updateNotify()?theme.accent:theme.textMuted,bold:!0,hint:hint("settings.general.updateNotifyHint"),children:pad(`${check(prefs.updateNotify())} ${t3("settings.general.updateNotify")}`)}),$jsx(Row,{cursor:isBodyCursor(updateCheckRow),rowRef:props.rowRef(updateCheckRow),onMouseUp:activate(updateCheckRow,props.updateCheck.press),fg:theme.text,bold:isBodyCursor(updateCheckRow),hint:hint("settings.general.updateCheckHint"),children:pad(t3(checkLabelKey))}),checkResult?$jsx("text",{fg:checkResult.fg,children:checkResult.text}):null]}),$jsxs(SubSection,{title:t3("settings.general.editor"),hint:t3("settings.general.editorHint"),children:[$jsx(Row,{cursor:isBodyCursor(editorKindRow),rowRef:props.rowRef(editorKindRow),onMouseUp:activate(editorKindRow,prefs.cycleEditorKind),fg:theme.accent,bold:!0,hint:hint("settings.general.editorRowHint"),children:pad(t3("settings.general.editorRow",{kind:prefs.editorKind()}))}),$jsx(Row,{cursor:isBodyCursor(editorCustomRow),rowRef:props.rowRef(editorCustomRow),onMouseUp:activate(editorCustomRow,()=>void prefs.editEditorCustom()),fg:prefs.editorKind()==="custom"?theme.text:theme.textMuted,children:t3("settings.general.editorCustom",{cmd:prefs.editorCustomCommand().trim()||t3("settings.general.editorCustomUnset")})})]}),$jsxs(SubSection,{title:t3("settings.general.worktree"),hint:t3("settings.general.worktreeHint"),children:[$jsx(Row,{cursor:isBodyCursor(worktreeBaseRow),rowRef:props.rowRef(worktreeBaseRow),onMouseUp:activate(worktreeBaseRow,prefs.cycleWorktreeBase),fg:theme.accent,bold:!0,hint:hint("settings.general.worktreeBaseHint"),children:pad(t3("settings.general.worktreeBase",{kind:prefs.worktreeKindLabel()}))}),$jsx(Row,{cursor:isBodyCursor(worktreeCustomRow),rowRef:props.rowRef(worktreeCustomRow),onMouseUp:activate(worktreeCustomRow,()=>void prefs.editWorktreeCustom()),fg:prefs.worktreeKind()==="custom"?theme.text:theme.textMuted,children:t3("settings.general.worktreeCustom",{path:prefs.worktreeCustomPath()||t3("settings.general.worktreeCustomUnset")})})]}),$jsxs(SubSection,{title:t3("settings.general.terminal"),hint:t3("settings.general.terminalHint"),children:[$jsx(Row,{cursor:isBodyCursor(scrollbackRow),rowRef:props.rowRef(scrollbackRow),onMouseUp:activate(scrollbackRow,()=>void prefs.editScrollbackRows()),fg:theme.accent,bold:!0,hint:hint("settings.general.scrollbackRowHint"),children:pad(t3("settings.general.scrollbackRow",{rows:String(prefs.scrollbackRows())}))}),$jsx(Row,{cursor:isBodyCursor(tabStripHideSingleRow),rowRef:props.rowRef(tabStripHideSingleRow),onMouseUp:activate(tabStripHideSingleRow,prefs.cycleTabStripMode),fg:theme.accent,bold:!0,children:t3("settings.general.tabStripRow",{mode:t3(`settings.general.tabStripMode.${prefs.tabStripMode()}`)})})]})]}),props.usage&&props.usage.size>0?$jsx(UsageDashboard,{usage:props.usage}):null]})}import{TextAttributes as TextAttributes34}from"@opentui/core";function MarketRow(props){let{theme}=useTheme(),t3=useT(),{row}=props,installed=row.installedId!==null;return $jsxs("box",{flexDirection:"column",gap:0,children:[$jsxs("box",{ref:props.rowRef,flexDirection:"row",gap:1,paddingLeft:1,paddingRight:1,backgroundColor:props.cursor?theme.primary:void 0,onMouseUp:props.onActivate,children:[$jsx("text",{fg:props.cursor?theme.selectedListItemText:installed?theme.textMuted:theme.accent,attributes:TextAttributes34.BOLD,wrapMode:"none",children:row.ref}),$jsx("text",{fg:props.cursor?theme.selectedListItemText:theme.textMuted,wrapMode:"none",children:installed?t3("settings.marketplace.installedTag"):row.stars!==null?`\u2605${row.stars}`:row.firstParty?t3("settings.marketplace.firstParty"):""})]}),row.desc?$jsx("box",{flexDirection:"row",paddingLeft:5,paddingRight:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:row.desc})}):null]})}function MarketplaceSettingsSection(props){let{theme}=useTheme(),t3=useT();return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes34.BOLD,children:t3("settings.marketplace.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.marketplace.hint")}),props.offline?$jsx("text",{fg:theme.warning,wrapMode:"word",children:t3("settings.marketplace.offline")}):null,props.status?$jsx("text",{fg:theme.accent,wrapMode:"word",children:props.status}):null,props.loading?$jsx("text",{fg:theme.textMuted,children:t3("settings.marketplace.loading")}):props.rows.length===0?$jsx("text",{fg:theme.textMuted,children:t3("settings.marketplace.empty")}):$jsx("box",{flexDirection:"column",gap:0,children:props.rows.map((row,i2)=>$jsx(MarketRow,{row,cursor:props.level==="body"&&props.bodyRow===i2,rowRef:props.rowRef(i2),onActivate:()=>{props.setLevel("body"),props.setBodyRow(i2),props.install(row.ref)}},row.ref))})]})}var import_react70=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes35}from"@opentui/core";function FeedbackSettingsSection(props){let{theme}=useTheme(),t3=useT(),editing=props.level==="body",titleFocused=editing&&props.bodyRow===0,bodyFocused=editing&&props.bodyRow===1,sendFocused=editing&&props.bodyRow===2,labelFg=(focused)=>focused?theme.primary:theme.textMuted,labelAttrs=(focused)=>focused?TextAttributes35.BOLD|TextAttributes35.UNDERLINE:void 0,bodyEl=import_react70.useRef(null);return import_react70.useEffect(()=>{if(props.body===""&&bodyEl.current&&bodyEl.current.plainText!=="")bodyEl.current.setText("")},[props.body]),$jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.feedback.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.feedback.hint")}),$jsxs("box",{flexDirection:"column",gap:1,children:[$jsxs("box",{gap:0,children:[$jsx("text",{fg:labelFg(titleFocused),attributes:labelAttrs(titleFocused),children:t3("settings.feedback.titleLabel")}),$jsx("input",{value:props.title,placeholder:t3("settings.feedback.titlePlaceholder"),focused:titleFocused,onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(0)},onInput:(v3)=>props.setTitle(stripNewlines2(v3)),onSubmit:()=>props.onTitleSubmit()})]}),$jsxs("box",{gap:0,children:[$jsx("text",{fg:labelFg(bodyFocused),attributes:labelAttrs(bodyFocused),children:t3("settings.feedback.descriptionLabel")}),$jsx("textarea",{ref:(el)=>{bodyEl.current=el},initialValue:props.body,placeholder:t3("settings.feedback.descriptionPlaceholder"),focused:bodyFocused,height:4,wrapMode:"word",onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(1)},onContentChange:()=>props.setBody(bodyEl.current?.plainText??"")})]}),$jsx("box",{flexDirection:"row",paddingLeft:1,paddingRight:1,backgroundColor:sendFocused?theme.primary:theme.backgroundElement,onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(2),props.submit()},children:$jsx("text",{fg:sendFocused?theme.selectedListItemText:theme.accent,attributes:TextAttributes35.BOLD,children:t3("settings.feedback.send")})})]}),props.status?$jsx("text",{fg:props.status.startsWith("error:")?theme.warning:theme.success,wrapMode:"word",children:props.status}):null]})}function DevSettingsSection(props){let{prefs}=props,{theme}=useTheme(),t3=useT(),rows=devRows(props.hasDaemon),isBodyCursor=(row)=>props.level==="body"&&props.bodyRow===row,activate=(row,action)=>()=>{props.setLevel("body"),props.setBodyRow(row),action()},toggleRow=(id,enabled,hintKey,labelKey,act)=>{let row=rowIndex(rows,id);return $jsxs("box",{flexDirection:"column",gap:0,paddingTop:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3(hintKey)}),$jsx(Row,{cursor:isBodyCursor(row),rowRef:props.rowRef(row),onMouseUp:activate(row,act),fg:theme.text,bold:enabled,idleBackground:theme.backgroundElement,children:`${enabled?"[x]":"[ ]"} ${t3(labelKey)}`})]})};return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.dev.reset")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.dev.resetHint")}),$jsx(Row,{cursor:isBodyCursor(0),rowRef:props.rowRef(0),onMouseUp:activate(0,props.confirmReset),fg:theme.warning,bold:!0,idleBackground:theme.backgroundElement,children:t3("settings.dev.resetButton")}),props.hasDaemon?$jsx(SubSection,{title:t3("settings.dev.restart"),hint:t3("settings.dev.restartHint"),children:$jsx(Row,{cursor:isBodyCursor(1),rowRef:props.rowRef(1),onMouseUp:activate(1,props.confirmRestartDaemon),fg:theme.accent,bold:!0,idleBackground:theme.backgroundElement,children:t3("settings.dev.restartButton")})}):null,$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.dev.doctorHint")}),$jsxs(SubSection,{title:t3("settings.dev.reload"),hint:t3("settings.dev.reloadHint"),children:[$jsx(Row,{cursor:isBodyCursor(rowIndex(rows,"dev-reload")),rowRef:props.rowRef(rowIndex(rows,"dev-reload")),onMouseUp:activate(rowIndex(rows,"dev-reload"),props.reloadSettings),fg:theme.accent,bold:!0,idleBackground:theme.backgroundElement,children:t3("settings.dev.reloadButton")}),props.reloadStatus?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:props.reloadStatus}):null]}),$jsxs("box",{flexDirection:"column",gap:0,paddingTop:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.dev.experimental")}),toggleRow("remote-projects",prefs.remoteProjectsEnabled(),"settings.dev.remoteHint","settings.dev.remote",prefs.toggleRemoteProjects),toggleRow("auto-status",prefs.autoStatusOn(),"settings.dev.autoStatusHint","settings.dev.autoStatus",prefs.toggleAutoStatus),toggleRow("dispatcher",prefs.dispatcherOn(),"settings.dev.dispatcherHint","settings.dev.dispatcher",prefs.toggleDispatcher)]})]})}function KeybindingsSettingsSection(props){let{theme}=useTheme(),t3=useT();useKeymapVersion();let report=userKeybindingsReport(),rows=keybindingRows(report.exists),prefix=currentPrefixConfiguration(),fixedIds=Object.keys(FIXED_BINDING_IDS).sort(),appliedIdWidth=Math.min(28,report.applied.reduce((max,o2)=>Math.max(max,o2.id.length),0));return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.keybindings.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.keybindings.hint")}),$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.keybindings.configFile")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:tildify(report.path)+(report.exists?"":t3("settings.keybindings.notCreated"))})]}),$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.keybindings.tapPresentation")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.keybindings.tapPresentationHint")}),PREFIX_TAP_PRESENTATIONS.map((presentation)=>{let row=rowIndex(rows,prefixTapPresentationRowId(presentation)),selected=props.prefs.prefixTapPresentation()===presentation;return $jsx(Row,{cursor:props.level==="body"&&props.bodyRow===row,rowRef:props.rowRef(row),onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(row),props.prefs.selectPrefixTapPresentation(presentation)},fg:selected?theme.accent:theme.text,bold:selected||props.level==="body"&&props.bodyRow===row,children:`${selected?"(\u25CF)":"( )"} ${t3(presentation==="local"?"settings.keybindings.tapPresentationLocal":"settings.keybindings.tapPresentationGuide")}`},presentation)})]}),$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.keybindings.prefixTitle",{prefix:prefix.key??t3("settings.keybindings.prefixDisabled")})}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.keybindings.prefixHint",{prefix:prefix.key??t3("settings.keybindings.prefixDisabled"),timeout:prefix.timeoutMs})})]}),!report.exists?$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.keybindings.createHint")}),$jsx(Row,{cursor:props.level==="body"&&props.bodyRow===rowIndex(rows,"keys-create"),rowRef:props.rowRef(rowIndex(rows,"keys-create")),onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(rowIndex(rows,"keys-create")),props.onCreateFile()},fg:theme.text,idleBackground:theme.backgroundElement,children:t3("settings.keybindings.createFile")})]}):$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes35.BOLD,children:t3("settings.keybindings.overridesApplied")}),report.applied.length===0?$jsx("text",{fg:theme.textMuted,children:t3("settings.keybindings.none")}):null,report.applied.map((o2)=>$jsx("text",{fg:theme.text,wrapMode:"none",children:`${o2.id.padEnd(appliedIdWidth)} ${o2.keys.length>0?o2.keys.join(" / "):t3("settings.keybindings.unbound")} (${t3("settings.keybindings.defaultKeys",{keys:o2.defaultKeys.join(" / ")})})`},o2.id))]}),report.warnings.length>0?$jsxs("box",{flexDirection:"column",gap:0,children:[$jsx("text",{fg:theme.warning,attributes:TextAttributes35.BOLD,children:t3("settings.keybindings.warnings")}),report.warnings.map((w4)=>$jsx("text",{fg:theme.warning,wrapMode:"word",children:`! ${w4}`},w4))]}):null,fixedIds.length>0?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("settings.keybindings.fixed",{ids:fixedIds.join(", ")})}):null]})}import{TextAttributes as TextAttributes36}from"@opentui/core";function toggleRowOffsets(plugins){let offsets=[],next=0;for(let plugin of plugins)offsets.push(next),next+=1+plugin.settings.length;return offsets}function SettingRow(props){let{theme}=useTheme(),t3=useT(),{setting}=props,value=setting.type==="boolean"?isBooleanOn(setting.value)?t3("settings.general.on"):t3("settings.general.off"):displaySettingValue(setting)||t3("settings.plugins.settingUnset");return $jsxs("box",{ref:props.rowRef,flexDirection:"row",gap:1,paddingLeft:5,paddingRight:1,backgroundColor:props.cursor?theme.primary:void 0,onMouseUp:props.onActivate,children:[$jsx("text",{fg:props.cursor?theme.selectedListItemText:theme.text,wrapMode:"none",children:setting.label}),$jsx("text",{fg:props.cursor?theme.selectedListItemText:setting.defaulted?theme.textMuted:theme.accent,wrapMode:"none",children:value})]})}function PluginSettingsSection(props){let{theme}=useTheme(),t3=useT(),now=Date.now(),isBodyCursor=(row)=>props.level==="body"&&props.bodyRow===row,offsets=toggleRowOffsets(props.plugins);return $jsxs("box",{flexDirection:"column",gap:1,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes36.BOLD,children:t3("settings.plugins.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3(props.plugins.some((plugin)=>!plugin.builtIn)?"settings.plugins.hint":"settings.plugins.empty")}),props.plugins.length===0?null:$jsx("box",{flexDirection:"column",gap:0,children:props.plugins.map((plugin,i2)=>{let toggleRow=offsets[i2]??0,isCursor=isBodyCursor(toggleRow);return $jsxs("box",{flexDirection:"column",gap:0,children:[$jsxs("box",{ref:props.rowRef(toggleRow),flexDirection:"row",gap:1,paddingLeft:1,paddingRight:1,backgroundColor:isCursor?theme.primary:void 0,onMouseUp:()=>{props.setLevel("body"),props.setBodyRow(toggleRow),props.toggle(plugin.id)},children:[$jsx("text",{fg:isCursor?theme.selectedListItemText:plugin.enabled?theme.accent:theme.textMuted,attributes:TextAttributes36.BOLD,wrapMode:"none",children:`${plugin.enabled?"[x]":"[ ]"} ${plugin.id}`}),$jsx("text",{fg:isCursor?theme.selectedListItemText:theme.textMuted,wrapMode:"none",children:plugin.builtIn?t3(plugin.enabled?"settings.plugins.sourceBuiltInInstalled":"settings.plugins.sourceBuiltIn"):`v${plugin.version} ${plugin.linked?t3("settings.plugins.sourceLink",{path:plugin.source}):t3("settings.plugins.sourceGithub",{spec:plugin.source})}`}),plugin.updateAvailable?$jsx("text",{fg:theme.warning,wrapMode:"none",children:t3("settings.plugins.updateAvailable")}):null]}),plugin.builtIn?null:$jsxs("box",{flexDirection:"row",gap:1,paddingLeft:5,paddingRight:1,children:[$jsx("text",{fg:plugin.declares?theme.textMuted:theme.warning,wrapMode:"none",children:plugin.declares?plugin.declares.engines>0?t3("settings.plugins.declaresWithEngines",{actions:String(plugin.declares.actions),events:String(plugin.declares.events),panes:String(plugin.declares.panes),engines:String(plugin.declares.engines)}):t3("settings.plugins.declares",{actions:String(plugin.declares.actions),events:String(plugin.declares.events),panes:String(plugin.declares.panes)}):t3("settings.plugins.manifestUnreadable")}),plugin.declares&&plugin.declares.pages>0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("settings.plugins.declaresPages",{pages:String(plugin.declares.pages)})}):null,$jsx("text",{fg:!plugin.platformOk||plugin.lastRun?.running?theme.warning:plugin.lastRun?.ok===!1?theme.error:theme.textMuted,wrapMode:"none",children:!plugin.platformOk?t3("settings.plugins.unsupportedPlatform"):plugin.lastRun?t3("settings.plugins.lastRun",{label:plugin.lastRun.label,status:plugin.lastRun.running?t3("settings.plugins.runRunning"):plugin.lastRun.ok?t3("settings.plugins.runOk"):plugin.lastRun.spawnError?t3("settings.plugins.runFailed"):t3("settings.plugins.runExit",{code:String(plugin.lastRun.exitCode)}),ago:relativeAge(plugin.lastRun.at,now)}):plugin.hooksDeclared?t3("settings.plugins.neverRun"):t3("settings.plugins.noHooks")})]}),plugin.pageErrors.map((detail)=>$jsx("text",{fg:theme.warning,paddingLeft:5,wrapMode:"word",children:t3("settings.plugins.pageFailed",{detail})},detail)),plugin.settings.map((setting,s2)=>$jsx(SettingRow,{setting,cursor:isBodyCursor(toggleRow+1+s2),rowRef:props.rowRef(toggleRow+1+s2),onActivate:()=>{props.setLevel("body"),props.setBodyRow(toggleRow+1+s2),props.editSetting(plugin.id,setting.key)}},setting.key))]},plugin.id)})})]})}var import_react71=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes37}from"@opentui/core";function AppearancePicker(props){let dialog=useDialog(),{theme}=useTheme(),t3=useT(),options=appearanceChoices(props.setting,props.themes),saved=currentAppearanceChoice(props.current,props.setting),[cursor,setCursor]=import_react71.useState(()=>Math.max(0,options.findIndex((option)=>option.value===saved.value))),selected=options[cursor],follow=useCursorFollow3(cursor);function commit(choice){if(!choice)return;props.onCommit(choice),dialog.pop()}function move(delta){if(options.length)setCursor((cursor+delta+options.length)%options.length)}return useBindings(()=>({bindings:[{key:"j",cmd:()=>move(1)},{key:"down",cmd:()=>move(1)},{key:"k",cmd:()=>move(-1)},{key:"up",cmd:()=>move(-1)},{key:"return",cmd:()=>commit(selected)}]})),$jsxs("box",{paddingLeft:useDialogPaddingX(),paddingRight:useDialogPaddingX(),paddingBottom:1,gap:1,flexShrink:1,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",flexShrink:0,children:[$jsxs("text",{fg:theme.text,attributes:TextAttributes37.BOLD,children:[t3("settings.general.appearance")," / ",t3(`settings.general.${props.setting}`)]}),$jsx("text",{fg:theme.textMuted,onMouseUp:()=>dialog.pop(),children:t3("settings.esc")})]}),$jsx(AppearancePreview,{current:selected?applyAppearanceChoice(props.current,selected):props.current,active:props.setting}),$jsx("text",{fg:theme.textMuted,flexShrink:0,children:t3("settings.appearance.chooseHint")}),$jsx("scrollbox",{ref:follow.scrollRef,flexShrink:1,maxHeight:8,children:options.map((option,index)=>$jsx(Row,{cursor:cursor===index,rowRef:follow.rowRef(index),onMouseUp:()=>commit(option),fg:theme.text,bold:option.value===saved.value,children:`${option.value===saved.value?"(\u25CF)":"( )"} ${appearanceChoiceLabel(option,t3)}`},String(option.value)))})]})}function useAppearanceSettings(kv,dialog,prefs){let theme=useTheme(),current2={themeName:theme.selected,themeMode:theme.modePreference,transparentBackground:theme.transparentBackground,focusAccent:theme.focusAccent,splitStyle:prefs.splitStyle(),railFoldStyle:prefs.railFoldStyle(),workingBorder:prefs.workingBorder(),taskColors:prefs.taskColors(),glyphSet:prefs.glyphSet(),colorblind:prefs.colorblind(),runningTitle:prefs.runningTitle()};function commit(choice){switch(choice.kind){case"theme":if(theme.set(choice.value))kv.set("activeTheme",choice.value);break;case"themeMode":theme.setMode(choice.value),kv.set("themeMode",choice.value);break;case"transparent":theme.setTransparentBackground(choice.value),kv.set("transparentBackground",choice.value);break;case"focusAccent":theme.setFocusAccent(choice.value),kv.set("focusAccent",choice.value);break;case"splitStyle":prefs.selectSplitStyle(choice.value);break;case"railFold":prefs.selectRailFoldStyle(choice.value);break;case"workingBorder":prefs.selectWorkingBorder(choice.value);break;case"taskColors":prefs.selectTaskColors(choice.value);break;case"glyphSet":prefs.selectGlyphSet(choice.value);break;case"colorblind":prefs.selectColorblind(choice.value);break;case"runningTitle":prefs.selectRunningTitle(choice.value);break}}function open(setting){dialog.setSize("xlarge"),dialog.push(()=>$jsx(AppearancePicker,{setting,current:current2,themes:theme.all().slice().sort(),onCommit:commit}))}return{current:current2,open}}var import_react73=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes38}from"@opentui/core";var import_react72=__toESM(require_react_production(),1);function engineAcceptsModel(vendor){return engineEntry(vendor).modelArgv!==void 0}var lists2=new Map;function modelsFor(vendor){let list=engineEntry(vendor).listModels;if(!list)return null;let pending=lists2.get(vendor);if(!pending)pending=list().catch((err)=>{throw lists2.delete(vendor),err}),lists2.set(vendor,pending);return pending}function filterModels(models,query){let q2=query.trim().toLowerCase();if(!q2)return models;return models.filter((m3)=>m3.id.toLowerCase().includes(q2)||m3.label?.toLowerCase().includes(q2))}function useModelField(opts){let[query,setQuery]=import_react72.useState(()=>opts.vendor===opts.initialVendor?opts.initial??"":""),[cursor,setCursor]=import_react72.useState(-1),[models,setModels]=import_react72.useState([]),[status,setStatus]=import_react72.useState("none");import_react72.useEffect(()=>{setQuery(opts.vendor===opts.initialVendor?opts.initial??"":""),setCursor(-1);let pending=modelsFor(opts.vendor);if(!pending){setModels([]),setStatus("none");return}let live=!0;return setStatus("loading"),pending.then((list)=>{if(!live)return;setModels(list),setStatus("loaded")},()=>{if(!live)return;setModels([]),setStatus("failed")}),()=>{live=!1}},[opts.vendor,opts.seedKey]);let suggestions=import_react72.useMemo(()=>filterModels(models,query),[models,query]),value=cursor>=0?suggestions[cursor]?.id??query:query,window2=windowAround(suggestions.map((m3)=>m3.id),Math.max(0,cursor),opts.pickerRows);function setText(v3){setQuery(stripNewlines2(v3)),setCursor(-1)}function moveCursor(delta){if(suggestions.length===0)return;setCursor((c2)=>clampCursor2(c2+delta,suggestions.length))}function pickAt(absoluteIndex){if(suggestions[absoluteIndex])setCursor(absoluteIndex)}return{value,query,cursor,suggestions,window:window2,status,setText,moveCursor,pickAt}}function ModelSection(props){let{theme}=useTheme(),t3=useT(),{field}=props,rows=field.suggestions.slice(field.window.start,field.window.start+field.window.items.length).map((m3,i2)=>({key:`${field.window.start+i2}:${m3.id}`,body:m3.id,accent:!1,...m3.label&&m3.label!==m3.id?{dim:m3.label}:{}}));return $jsxs($Fragment,{children:[$jsx(DialogSection2,{label:t3("tasks.engineModel.label"),focused:props.focused,hint:props.hint,onPress:props.onFocus,children:$jsx(DialogField2,{focused:props.focused,children:$jsx("input",{value:field.value,placeholder:t3("tasks.engineModel.placeholder"),focused:props.focused,onMouseUp:props.onFocus,onInput:(v3)=>field.setText(v3),onSubmit:props.onSubmit})})}),props.focused&&field.status==="loading"?$jsx("box",{paddingLeft:2,paddingBottom:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("tasks.engineModel.loading")})}):null,props.focused&&field.window.total>0?$jsx(PickerList,{window:field.window,cursor:Math.max(0,field.cursor),rows,onPick:field.pickAt,paddingBottom:1}):null]})}var NO_EFFORT="";function effortLevelsOf(vendor){return engineEntry(vendor).effortLevels??[]}function seedEffort(vendor,current2){let trimmed=current2?.trim();return trimmed&&effortLevelsOf(vendor).includes(trimmed)?trimmed:NO_EFFORT}function EnginePickerDialogView(props){let dialog=useDialog(),{theme}=useTheme(),t3=useT(),padX=useDialogPaddingX(),{engines}=props,[cursor,setCursor]=import_react73.useState(()=>Math.max(0,engines.indexOf(props.current))),[effort,setEffort]=import_react73.useState(()=>seedEffort(props.current,props.currentEffort)),[field,setField]=import_react73.useState("engine"),window2={items:[...engines],start:0,total:engines.length},cursorEngine=engines[cursor]??props.current,levels=effortLevelsOf(cursorEngine),effortChoices=levels.length>0?[NO_EFFORT,...levels]:[],modelRow=engineAcceptsModel(cursorEngine),model=useModelField({vendor:cursorEngine,pickerRows:pickerVisibleRows(useTerminalSize().height),initial:props.currentModel,initialVendor:props.current}),modelFocused=modelRow&&field==="model";function move(delta){setCursor((c2)=>{let next=clampCursor2(c2+delta,engines.length);return setEffort((e2)=>seedEffort(engines[next]??props.current,e2)),next})}function stepEffort(delta){if(effortChoices.length===0)return;let i2=effortChoices.indexOf(effort);setEffort(effortChoices[clampCursor2((i2<0?0:i2)+delta,effortChoices.length)]??NO_EFFORT)}function commit(engine){let applicable=effortLevelsOf(engine);props.onSubmit({vendor:engine,...applicable.length>0?{effort:seedEffort(engine,effort)}:{},...engineAcceptsModel(engine)?{model:model.value.trim()}:{}}),dialog.clear()}let rows=engines.map((engine,i2)=>({key:`${i2}:${engine}`,body:engineDisplayName(engine),accent:engine===props.current,dim:engine===props.current?t3("tasks.changeEngine.current"):void 0}));useBindings(()=>({bindings:[{key:"up",cmd:()=>modelFocused?model.moveCursor(-1):move(-1)},{key:"down",cmd:()=>modelFocused?model.moveCursor(1):move(1)},...modelFocused?[]:[{key:"left",cmd:()=>stepEffort(-1)},{key:"right",cmd:()=>stepEffort(1)},{key:"h",cmd:()=>stepEffort(-1)},{key:"l",cmd:()=>stepEffort(1)},{key:"return",cmd:()=>commit(engines[cursor]??props.current)}],...modelRow?[{key:"tab",cmd:()=>setField((f2)=>f2==="engine"?"model":"engine")}]:[]]}));let footer=[t3("tasks.changeEngine.footer.engine"),...modelRow?[t3("tasks.changeEngine.footer.model")]:[],...effortChoices.length>0?[t3("tasks.changeEngine.footer.effort")]:[],t3("tasks.changeEngine.footer.set"),t3("tasks.changeEngine.footer.cancel")].join(" \xB7 ");return $jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:1,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",children:[$jsx("text",{attributes:TextAttributes38.BOLD,fg:theme.text,children:t3("tasks.changeEngine.title")}),$jsx("text",{fg:theme.textMuted,onMouseUp:()=>props.onCancel(),children:"esc"})]}),$jsx(PickerList,{window:window2,cursor,rows,onPick:(absoluteIndex)=>commit(engines[absoluteIndex]??props.current),paddingBottom:effortChoices.length>0||modelRow?0:1,focused:!modelFocused}),modelRow?$jsx(ModelSection,{field:model,focused:modelFocused,hint:"tab",onFocus:()=>setField("model"),onSubmit:()=>commit(cursorEngine)}):null,effortChoices.length>0?$jsx(DialogSection2,{label:t3("tasks.changeEngine.effortLabel"),focused:!1,hint:"\u2190/\u2192",children:$jsx(ChipRow2,{choices:effortChoices,selected:effort,display:(choice)=>choice===NO_EFFORT?t3("tasks.changeEngine.noEffort"):effortLabel(levels,choice),onPick:(choice)=>setEffort(choice)})}):null,$jsx("box",{paddingBottom:1,children:$jsx("text",{fg:theme.textMuted,children:footer})})]})}function show6(dialog,opts){return showDialog(dialog,(resolve2)=>$jsx(EnginePickerDialogView,{engines:opts.engines,current:opts.current,currentEffort:opts.currentEffort,currentModel:opts.currentModel,onSubmit:(v3)=>resolve2(v3),onCancel:()=>resolve2(void 0)}))}var EnginePickerDialog={show:show6};function useAutoRoutingSettings(kv,dialog,engineList,statuses){let table=readAutoRoutingTable((key)=>kv.get(key)),engineIds=new Set(engineList());function block(tier){if(!table)return;if(statuses===null)return;let byVendor=new Map(statuses.map((s2)=>[s2.vendor,s2]));return tierBlock(table[tier],{engineIds,accountKind:(engine)=>byVendor.get(engine)?.account?.kind??null})}async function edit(tier){let current2=table?.[tier],engines=engineList(),pick=await EnginePickerDialog.show(dialog,{engines:engines.length>0?engines:current2?[current2.engine]:[],current:current2?.engine??engines[0]??"claude",currentEffort:current2?.effort,currentModel:current2?.model});if(!pick)return;kv.set(autoRoutingKey(tier,"engine"),pick.vendor),kv.set(autoRoutingKey(tier,"model"),pick.model??""),kv.set(autoRoutingKey(tier,"effort"),pick.effort??"")}return{table,block,edit}}var MODE_KEY="autoRouting.classifier",ENDPOINT_KEY="autoRouting.classifierEndpoint",THRESHOLD_KEY="autoRouting.classifierThreshold",LOOPBACK=/^(?:localhost|127\.\d+\.\d+\.\d+|\[?::1\]?|.+\.localhost)$/i;function stringAt(kv,key){let v3=kv.get(key,"");return typeof v3==="string"?v3.trim():""}function acceptableEndpoint(url){let parsed;try{parsed=new URL(url)}catch{return!1}if(parsed.protocol==="https:")return!0;return parsed.protocol==="http:"&&LOOPBACK.test(parsed.hostname)}function useClassifierSettings(kv,dialog,visible,env=process.env){let t3=useT(),config=readClassifierConfig((key2)=>kv.get(key2)),mode=config.mode.kind==="url"?"custom":config.mode.kind==="jev"?"jev":"off",remembered=stringAt(kv,ENDPOINT_KEY),endpoint=displayEndpoint(config.mode.kind,stringAt(kv,MODE_KEY),remembered);function cycle(){if(mode==="off"){kv.set(MODE_KEY,"jev");return}if(mode==="jev"){kv.set(MODE_KEY,remembered||"off");return}if(endpoint)kv.set(ENDPOINT_KEY,endpoint);kv.set(MODE_KEY,"off")}async function editEndpoint(){let next=await RenameTaskDialog.show(dialog,endpoint,{dialogTitle:t3("settings.autoRouting.endpointTitle"),fieldLabel:t3("settings.autoRouting.endpointField"),submitLabel:t3("settings.action.save"),placeholder:"https://tiers.internal/pick",allowEmpty:!0});if(next===void 0)return;let url=next.trim();if(!url){if(kv.set(ENDPOINT_KEY,""),mode==="custom")kv.set(MODE_KEY,"off");return}if(!acceptableEndpoint(url)){await DialogConfirm.show(dialog,t3("settings.autoRouting.endpointInvalidTitle"),t3("settings.autoRouting.endpointInvalidBody"),"cancel");return}if(kv.set(ENDPOINT_KEY,url),mode==="custom")kv.set(MODE_KEY,url)}async function editThreshold(){let next=await RenameTaskDialog.show(dialog,config.threshold.toFixed(2),{dialogTitle:t3("settings.autoRouting.thresholdTitle"),fieldLabel:t3("settings.autoRouting.thresholdField"),submitLabel:t3("settings.action.save"),placeholder:"0.50"});if(next===void 0)return;let n2=Number.parseFloat(next.trim());if(!Number.isFinite(n2)||n2<0||n2>1){await DialogConfirm.show(dialog,t3("settings.autoRouting.thresholdInvalidTitle"),t3("settings.autoRouting.thresholdInvalidBody"),"cancel");return}kv.set(THRESHOLD_KEY,n2)}async function editKey(){if(!config.keyEnv){await DialogConfirm.show(dialog,t3("settings.autoRouting.keyNoVariableTitle"),t3("settings.autoRouting.keyNoVariableBody"),"cancel");return}let next=await RenameTaskDialog.show(dialog,"",{dialogTitle:t3("settings.autoRouting.keyTitle",{env:config.keyEnv}),fieldLabel:config.keyEnv,submitLabel:t3("settings.action.save"),placeholder:t3("settings.autoRouting.keyPlaceholder"),allowEmpty:!0});if(next===void 0)return;try{writeSecret(config.keyEnv,next.trim())}catch(err){await DialogConfirm.show(dialog,t3("settings.autoRouting.keyWriteFailedTitle"),t3("settings.autoRouting.keyWriteFailedBody",{reason:err instanceof Error?err.message:String(err)}),"cancel")}}let key=visible&&config.keyEnv?secretStatus(config.keyEnv,env):{source:"none",hint:""};return{mode,endpoint,threshold:config.threshold,keyEnv:config.keyEnv??"",keySource:key.source,keyHint:key.hint,keyConfigured:config.keyEnv!==void 0,cycle,editEndpoint,editThreshold,editKey}}var import_react75=__toESM(require_react_production(),1);var import_react74=__toESM(require_react_production(),1);var NO_ENGINE_PROTOCOL="",CHOICES=[...ENGINE_PROTOCOLS,NO_ENGINE_PROTOCOL];function EngineProtocolPickerDialogView(props){let dialog=useDialog(),t3=useT(),padX=useDialogPaddingX(),[cursor,setCursor]=import_react74.useState(0),window2={items:[...CHOICES],start:0,total:CHOICES.length};function commit(protocol){if(protocol===void 0)return;props.onSubmit(protocol),dialog.clear()}let rows=CHOICES.map((protocol,i2)=>({key:`${i2}:${protocol||"none"}`,body:protocol?engineEntry(protocol).displayName:t3("settings.engines.protocolNone"),dim:protocol||void 0}));return useBindings(()=>({bindings:[{key:"up",cmd:()=>setCursor((c2)=>clampCursor2(c2-1,CHOICES.length))},{key:"down",cmd:()=>setCursor((c2)=>clampCursor2(c2+1,CHOICES.length))},{key:"return",cmd:()=>commit(CHOICES[cursor])}]})),$jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:1,children:[$jsx(DialogHeader2,{title:t3("settings.engines.protocolTitle",{id:props.engineId}),onClose:()=>props.onCancel()}),$jsx(PickerList,{window:window2,cursor,rows,onPick:(absoluteIndex)=>commit(CHOICES[absoluteIndex]),paddingBottom:1}),$jsx(DialogFooter2,{children:t3("settings.engines.protocolFooter")})]})}function show7(dialog,opts){return showDialog(dialog,(resolve2)=>$jsx(EngineProtocolPickerDialogView,{engineId:opts.engineId,onSubmit:(v3)=>resolve2(v3),onCancel:()=>resolve2(void 0)}))}var EngineProtocolPickerDialog={show:show7};function useEngineSettings(kv,dialog,onEngineListShrunk){let[detected,setDetected]=import_react75.useState([]);import_react75.useEffect(()=>{installedEngineIds().then(setDetected)},[]);function customEngines(){let raw=kv.get("customEngineIds",[]);return Array.isArray(raw)?raw.filter((s2)=>typeof s2==="string"&&s2.trim().length>0):[]}function engineList(){return[...new Set([...ALL_VENDORS,...customEngines(),...detected])]}function isCustomEngine(vendor){return customEngines().includes(vendor)}function disabledEngines(){let raw=kv.get("disabledEngineIds",[]);return Array.isArray(raw)?raw.filter((s2)=>typeof s2==="string"&&s2.trim().length>0):[]}function isEngineEnabled(vendor){return!disabledEngines().includes(vendor)}function toggleEngineEnabled(vendor){let off=disabledEngines();if(off.includes(vendor)){kv.set("disabledEngineIds",off.filter((id)=>id!==vendor));return}let nextDefault=engineList().find((id)=>id!==vendor&&!off.includes(id));if(defaultEngine===vendor){if(!nextDefault)return;setEngineDefault(nextDefault)}kv.set("disabledEngineIds",[...off,vendor])}function engineOverride(vendor){let v3=kv.get(engineCommandKey(vendor),"");return typeof v3==="string"?v3.trim():""}function engineCommandText(vendor){return engineOverride(vendor)||defaultEngineCommand(vendor).join(" ")}function engineHasCommandOverride(vendor){return engineOverride(vendor).length>0}function engineRenamedFromName(vendor){return engineRenamedFrom(vendor,engineNameOverride(vendor))}function engineIsDefault(vendor){return!isCustomEngine(vendor)&&engineOverride(vendor).length===0&&!engineNameIsCustom(vendor)}function engineNameOverride(vendor){let v3=kv.get(engineNameKey(vendor),"");return typeof v3==="string"?v3.trim():""}function engineNameIsCustom(vendor){return engineNameOverride(vendor).length>0}function engineProtocol(vendor){let raw=kv.get(engineProtocolKey(vendor),""),declared=typeof raw==="string"?raw.trim():"";return declared&&ENGINE_PROTOCOLS.includes(declared)?declared:void 0}function engineName(vendor){return engineNameOverride(vendor)||engineEntry(vendor).displayName}let[defaultEngine,setDefaultEngineState]=import_react75.useState(()=>getGlobalDefaultVendor()??DEFAULT_TASK_VENDOR);function setEngineDefault(vendor){setGlobalDefaultVendor(vendor),kv.set("defaultVendor",vendor),setDefaultEngineState(vendor)}function chooseDefaultEngine(vendor){let off=disabledEngines();if(off.includes(vendor))kv.set("disabledEngineIds",off.filter((id)=>id!==vendor));setEngineDefault(vendor)}async function editEngine(vendor){let next=await RenameTaskDialog.show(dialog,engineCommandText(vendor),{dialogTitle:t("settings.engines.launchCommandTitle",{name:engineName(vendor)}),fieldLabel:t("settings.field.command"),submitLabel:t("settings.action.save"),allowEmpty:!0});if(next===void 0)return;kv.set(engineCommandKey(vendor),next.trim())}async function renameEngine(vendor){let next=await RenameTaskDialog.show(dialog,engineName(vendor),{dialogTitle:t("settings.engines.displayNameTitle",{name:engineName(vendor)}),fieldLabel:t("settings.field.name"),submitLabel:t("settings.action.save"),allowEmpty:!0});if(next===void 0)return;kv.set(engineNameKey(vendor),next.trim())}function resetEngine(vendor){if(kv.set(engineCommandKey(vendor),""),kv.set(engineNameKey(vendor),""),isCustomEngine(vendor))kv.set(engineProtocolKey(vendor),""),kv.set("customEngineIds",customEngines().filter((id)=>id!==vendor)),onEngineListShrunk(engineList().length)}async function addEngineFlow(){let idRaw=await RenameTaskDialog.show(dialog,"",{dialogTitle:t("settings.engines.addTitle"),fieldLabel:t("settings.field.id"),submitLabel:t("settings.action.next"),placeholder:t("settings.engines.idPlaceholder")});if(idRaw===void 0)return;let id=idRaw.trim().toLowerCase();if(!id||isBuiltinVendor(id)||customEngines().includes(id))return;let command=await RenameTaskDialog.show(dialog,"",{dialogTitle:t("settings.engines.addStepTitle",{id}),fieldLabel:t("settings.field.command"),submitLabel:t("settings.action.next"),placeholder:t("settings.engines.commandPlaceholder")});if(command===void 0)return;let protocol=await EngineProtocolPickerDialog.show(dialog,{engineId:id});if(protocol===void 0)return;let name=await RenameTaskDialog.show(dialog,id,{dialogTitle:t("settings.engines.addStepTitle",{id}),fieldLabel:t("settings.field.name"),submitLabel:t("settings.action.add"),allowEmpty:!0});if(kv.set("customEngineIds",[...customEngines(),id]),command.trim())kv.set(engineCommandKey(id),command.trim());if(protocol&&ENGINE_PROTOCOLS.includes(protocol))kv.set(engineProtocolKey(id),protocol);let typedName=name?.trim()??"";kv.set(engineNameKey(id),typedName&&typedName!==id?typedName:humanizeSlug(id))}return{engineList,isCustomEngine,isEngineEnabled,toggleEngineEnabled,engineName,engineProtocol,engineCommandText,engineHasCommandOverride,engineRenamedFromName,engineIsDefault,defaultEngine,setEngineDefault,chooseDefaultEngine,editEngine,renameEngine,resetEngine,addEngineFlow}}var import_react76=__toESM(require_react_production(),1);function installedSpecIds(plugins){let map=new Map;for(let plugin of plugins){if(plugin.linked)continue;map.set(plugin.source.toLowerCase().replace(/^sma1lboy\/rove-plugins\//,"sma1lboy/rove-plugins/"),plugin.id)}return map}function marketplaceRowViews(entries,plugins){let installed=installedSpecIds(plugins);return entries.map((entry2)=>({ref:entry2.ref,desc:entry2.desc,stars:entry2.stars??null,firstParty:entry2.firstParty===!0,installedId:installed.get(entry2.ref.toLowerCase())??null}))}function useAccountProbes(section,vendors){let[statuses,setStatuses]=import_react76.useState(null),key=vendors.join(",");return import_react76.useEffect(()=>{if(section!=="engines"&&section!=="autoRouting")return;let cancelled=!1;return detectEngineStatuses(key?key.split(","):[]).then((s2)=>{if(!cancelled)setStatuses(s2)}),()=>{cancelled=!0}},[section,key]),statuses}function useEngineIntegrations(section,vendors){let[rows,setRows]=import_react76.useState(null),key=vendors.join(","),read2=import_react76.useCallback(()=>{setRows(engineIntegrations(key?key.split(","):[]))},[key]);return import_react76.useEffect(()=>{if(section!=="engines")return;read2()},[section,read2]),{rows,reprobe:read2}}function builtInPlugins(){return BUNDLED_PLUGINS.map((plugin)=>({id:plugin.id,description:plugin.description,pages:plugin.pages.length,enabled:isBundledPluginInstalled(plugin.id)}))}function usePluginSettings(section,dialog){let[rows,setRows]=import_react76.useState([]),t3=useT();import_react76.useEffect(()=>{if(section!=="plugins")return;setRows(readPluginRows(builtInPlugins()))},[section]);function store(pluginId,key,value){try{setPluginSetting(pluginId,key,value)}catch{}setRows(readPluginRows(builtInPlugins()))}return{rows,refresh:()=>setRows(readPluginRows(builtInPlugins())),toggle:(id)=>{let row=rows.find((p3)=>p3.id===id);if(!row)return;let bundled=BUNDLED_PLUGINS.find((plugin)=>plugin.id===id);if(row.builtIn&&bundled){try{setBundledPluginInstalled(bundled.id,!row.enabled)}catch{}registerBundledPlugins(),setRows(readPluginRows(builtInPlugins()));return}try{setPluginEnabled(id,!row.enabled)}catch{}setRows(readPluginRows(builtInPlugins())),loadPluginPages().then(()=>setRows(readPluginRows(builtInPlugins())))},editSetting:async(pluginId,key)=>{let setting=rows.find((p3)=>p3.id===pluginId)?.settings.find((s2)=>s2.key===key);if(!setting)return;if(setting.type==="enum"){store(pluginId,key,nextEnumValue(setting.options,setting.value));return}if(setting.type==="boolean"){store(pluginId,key,toggledBooleanValue(setting));return}let initial=setting.type==="secret"?"":setting.value,next=await RenameTaskDialog.show(dialog,initial,{dialogTitle:setting.label,fieldLabel:key,submitLabel:t3("settings.action.save"),allowEmpty:!0,placeholder:setting.type==="secret"&&setting.value!==""?"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022":setting.defaultValue});if(next===void 0)return;if(setting.type!=="number"){store(pluginId,key,next.trim());return}let numeric=normalizeNumberInput(next);if(numeric===null){await DialogConfirm.show(dialog,t3("settings.plugins.settingInvalidTitle"),t3("settings.plugins.settingInvalidBody",{label:setting.label}),"cancel");return}store(pluginId,key,numeric)}}}function useMarketplace(section,dialog,plugins){let t3=useT(),[entries,setEntries]=import_react76.useState(null),[offline,setOffline]=import_react76.useState(!1),[status,setStatus]=import_react76.useState(""),busy=import_react76.useRef(!1);import_react76.useEffect(()=>{if(section!=="marketplace")return;let cancelled=!1;return setEntries(null),fetchMarketplace().then((result)=>{if(cancelled)return;setEntries(result.entries),setOffline(result.offline)}),()=>{cancelled=!0}},[section]);function previewMessage(preview){let lines=[`${preview.name} (${preview.id}) v${preview.version}`];if(preview.description)lines.push(preview.description);if(lines.push(t3("settings.marketplace.previewSource",{source:preview.source}),""),preview.commands.length===0)lines.push(t3("settings.marketplace.previewNoCommands"));else{lines.push(t3("settings.marketplace.previewCommands"));for(let command of preview.commands)lines.push(` ${command}`)}for(let warning of preview.warnings)lines.push(t3("settings.marketplace.previewWarning",{warning}));return lines.push("",t3("settings.marketplace.previewTrust")),lines.join(`
70
+ `)}return{rows:marketplaceRowViews(entries??[],plugins.rows),loading:entries===null,offline,status,install:async(ref)=>{if(busy.current)return;let already=installedSpecIds(plugins.rows).get(ref.toLowerCase());if(already){setStatus(t3("settings.marketplace.alreadyInstalled",{id:already}));return}busy.current=!0,setStatus(t3("settings.marketplace.preparing",{ref}));try{let prepared=await preparePluginInstall(ref);if(await DialogConfirm.show(dialog,t3("settings.marketplace.confirmTitle",{name:prepared.preview.name}),previewMessage(prepared.preview),void 0,t3("settings.marketplace.confirmInstall"),{danger:!0,size:"medium"})!==!0){prepared.discard(),setStatus(t3("settings.marketplace.cancelled"));return}setStatus(t3("settings.marketplace.installing",{name:prepared.preview.name}));let id=await prepared.commit();reloadPluginEngines(),plugins.refresh(),setStatus(t3("settings.marketplace.installed",{id,version:prepared.preview.version}))}catch(err){setStatus(t3("settings.marketplace.failed",{error:errorMessage(err)}))}finally{busy.current=!1}}}}import{accessSync,constants as fsConstants,mkdirSync}from"fs";function useSettingsPrefs(kv,dialog){let t3=useT();function toastEnabled(){return kv.get("notifications.toast.enabled",!0)!==!1}function soundEnabled(){return kv.get("notifications.sound.enabled",!0)!==!1}function toggleToast(){kv.set("notifications.toast.enabled",!toastEnabled())}function toggleSound(){kv.set("notifications.sound.enabled",!soundEnabled())}function soundVolume(){return normalizeSoundVolume(kv.get(SOUND_VOLUME_KEY,DEFAULT_SOUND_VOLUME))}function cycleSoundVolume(){kv.set(SOUND_VOLUME_KEY,nextSoundVolume(soundVolume()))}function crossTaskEnabled(){return kv.get("notifications.crossTask.enabled",!0)!==!1}function toggleCrossTask(){kv.set("notifications.crossTask.enabled",!crossTaskEnabled())}function finishedAlertsEnabled(){return kv.get(FINISHED_ALERTS_KEY,!0)!==!1}function toggleFinishedAlerts(){kv.set(FINISHED_ALERTS_KEY,!finishedAlertsEnabled())}function prefixTapPresentation(){return normalizePrefixTapPresentation(kv.get(PREFIX_TAP_PRESENTATION_KEY))}function selectPrefixTapPresentation(next){kv.set(PREFIX_TAP_PRESENTATION_KEY,next)}function splitStyle(){return normalizeSplitStyle(kv.get(SPLIT_STYLE_KEY))}function selectSplitStyle(style){kv.set(SPLIT_STYLE_KEY,style)}function zenDefaultOn(){return kv.get(ZEN_ACTIVE_KEY,ZEN_DEFAULT)===!0}function toggleZenDefaultOn(){kv.set(ZEN_ACTIVE_KEY,!zenDefaultOn())}function updateChannel(){return normalizeReleaseChannel(kv.get(UPDATE_CHANNEL_KEY))??channelOf()}function cycleUpdateChannel(){let at2=RELEASE_CHANNELS.indexOf(updateChannel());kv.set(UPDATE_CHANNEL_KEY,RELEASE_CHANNELS[(at2+1)%RELEASE_CHANNELS.length])}function updateNotify(){return updateNotifyEnabled(kv.get(UPDATE_NOTIFY_KEY))}function toggleUpdateNotify(){kv.set(UPDATE_NOTIFY_KEY,!updateNotify())}function tabStripMode(){return resolveTabStripMode(kv.get(TAB_STRIP_MODE_KEY,void 0),kv.get(TAB_STRIP_HIDE_SINGLE_KEY,void 0))}function cycleTabStripMode(){let next=TAB_STRIP_MODES[(TAB_STRIP_MODES.indexOf(tabStripMode())+1)%TAB_STRIP_MODES.length];kv.set(TAB_STRIP_MODE_KEY,next)}function remoteProjectsEnabled(){return kv.get("experimental.remoteProjects",!1)===!0}function toggleRemoteProjects(){kv.set("experimental.remoteProjects",!remoteProjectsEnabled())}function autoStatusOn(){return kv.get(AUTO_STATUS_KEY,!1)===!0}function toggleAutoStatus(){kv.set(AUTO_STATUS_KEY,!autoStatusOn())}function dispatcherOn(){return kv.get(DISPATCHER_KEY,!1)===!0}function toggleDispatcher(){kv.set(DISPATCHER_KEY,!dispatcherOn())}function railFoldStyle(){let raw=kv.get(RAIL_FOLD_STYLE_KEY,DEFAULT_COLLAPSED_RAIL_STYLE);return COLLAPSED_RAIL_STYLES.includes(raw)?raw:DEFAULT_COLLAPSED_RAIL_STYLE}function selectRailFoldStyle(style){kv.set(RAIL_FOLD_STYLE_KEY,style)}function workingBorder(){return normalizeWorkingBorder(kv.get(WORKING_BORDER_KEY,DEFAULT_WORKING_BORDER))}function selectWorkingBorder(style){kv.set(WORKING_BORDER_KEY,style)}function taskColors(){return normalizeTaskColors(kv.get(TASK_COLORS_KEY,DEFAULT_TASK_COLORS))}function selectTaskColors(value){kv.set(TASK_COLORS_KEY,value)}function glyphSet(){return normalizeGlyphSet(kv.get(GLYPH_SET_KEY,DEFAULT_GLYPH_SET))}function selectGlyphSet(name){kv.set(GLYPH_SET_KEY,name)}function colorblind(){return normalizeColorblind(kv.get(COLORBLIND_KEY,DEFAULT_COLORBLIND))}function selectColorblind(mode){kv.set(COLORBLIND_KEY,mode)}function runningTitle(){return normalizeRunningTitle(kv.get(RUNNING_TITLE_KEY,DEFAULT_RUNNING_TITLE))}function selectRunningTitle(style){kv.set(RUNNING_TITLE_KEY,style)}function editorKind(){return normalizeEditorKind(kv.get(EDITOR_KIND_KEY,DEFAULT_EDITOR_KIND))}function cycleEditorKind(){let i2=EDITOR_KINDS.indexOf(editorKind()),next=EDITOR_KINDS[(i2+1)%EDITOR_KINDS.length];if(next)kv.set(EDITOR_KIND_KEY,next)}function editorCustomCommand(){let v3=kv.get(EDITOR_CUSTOM_KEY,"");return typeof v3==="string"?v3:""}async function editEditorCustom(){let next=await RenameTaskDialog.show(dialog,editorCustomCommand(),{dialogTitle:t3("settings.general.editorCustomTitle"),fieldLabel:t3("settings.field.command"),submitLabel:t3("settings.action.save"),allowEmpty:!0});if(next===void 0)return;let cmd=next.trim();if(kv.set(EDITOR_CUSTOM_KEY,cmd),cmd)kv.set(EDITOR_KIND_KEY,"custom")}function scrollbackRows(){return normalizeScrollbackRows(kv.get(SCROLLBACK_ROWS_KEY,DEFAULT_SCROLLBACK_ROWS))}async function editScrollbackRows(){let next=await RenameTaskDialog.show(dialog,String(scrollbackRows()),{dialogTitle:t3("settings.general.scrollbackTitle"),fieldLabel:t3("settings.general.scrollbackField"),submitLabel:t3("settings.action.save"),placeholder:String(DEFAULT_SCROLLBACK_ROWS)});if(next===void 0)return;let n2=Number.parseInt(next.trim(),10);if(!Number.isFinite(n2)){await DialogConfirm.show(dialog,t3("settings.general.scrollbackInvalidTitle"),t3("settings.general.scrollbackInvalidBody"),"cancel");return}kv.set(SCROLLBACK_ROWS_KEY,normalizeScrollbackRows(n2))}function worktreeBasePath(){let v3=kv.get(WORKTREE_BASE_KEY,"");return typeof v3==="string"?v3:""}let worktreeKind=()=>worktreeBaseKindOf(worktreeBasePath());function worktreeKindLabel(){let kind=worktreeKind();if(kind==="default")return t3("settings.general.worktreeKindDefault");if(kind==="nextToProject")return t3("settings.general.worktreeKindNext");return t3("settings.general.worktreeKindCustom")}function worktreeCustomPath(){let v3=kv.get(WORKTREE_BASE_CUSTOM_KEY,"");return(typeof v3==="string"?v3.trim():"")||(worktreeKind()==="custom"?worktreeBasePath().trim():"")}function cycleWorktreeBase(){let kind=worktreeKind();if(kind==="default")kv.set(WORKTREE_BASE_KEY,PROJECT_SIBLING_BASE);else if(kind==="nextToProject")kv.set(WORKTREE_BASE_KEY,worktreeCustomPath());else kv.set(WORKTREE_BASE_CUSTOM_KEY,worktreeBasePath().trim()),kv.set(WORKTREE_BASE_KEY,"")}async function editWorktreeCustom(){let next=await RenameTaskDialog.show(dialog,worktreeCustomPath(),{dialogTitle:t3("settings.general.worktreeBaseTitle"),fieldLabel:t3("settings.general.worktreeBaseField"),submitLabel:t3("settings.action.save"),placeholder:`${PROJECT_DIR_TOKEN}/../worktrees`,allowEmpty:!0});if(next===void 0)return;let raw=next.trim();if(raw.includes(PROJECT_DIR_TOKEN)){if(!hasProjectDirToken(raw)){await DialogConfirm.show(dialog,t3("settings.general.worktreeBaseInvalidTitle"),t3("settings.general.worktreeBaseTokenBody",{token:PROJECT_DIR_TOKEN}),"cancel");return}}else if(raw){let resolved=normalizeWorktreeBase(raw)??raw;try{mkdirSync(resolved,{recursive:!0}),accessSync(resolved,fsConstants.W_OK)}catch(err){await DialogConfirm.show(dialog,t3("settings.general.worktreeBaseInvalidTitle"),t3("settings.general.worktreeBaseUnusableBody",{path:resolved,error:errorMessage(err)}),"cancel");return}}if(kv.set(WORKTREE_BASE_CUSTOM_KEY,raw),raw)kv.set(WORKTREE_BASE_KEY,raw);else if(worktreeKind()==="custom")kv.set(WORKTREE_BASE_KEY,"")}return{toastEnabled,toggleToast,soundEnabled,soundVolume,cycleSoundVolume,toggleSound,crossTaskEnabled,finishedAlertsEnabled,toggleFinishedAlerts,toggleCrossTask,prefixTapPresentation,selectPrefixTapPresentation,splitStyle,selectSplitStyle,zenDefaultOn,toggleZenDefaultOn,updateChannel,cycleUpdateChannel,updateNotify,toggleUpdateNotify,railFoldStyle,selectRailFoldStyle,workingBorder,selectWorkingBorder,taskColors,selectTaskColors,glyphSet,selectGlyphSet,colorblind,selectColorblind,runningTitle,selectRunningTitle,remoteProjectsEnabled,toggleRemoteProjects,autoStatusOn,toggleAutoStatus,dispatcherOn,toggleDispatcher,editorKind,cycleEditorKind,editorCustomCommand,editEditorCustom,scrollbackRows,editScrollbackRows,tabStripMode,cycleTabStripMode,worktreeKind,worktreeKindLabel,worktreeCustomPath,cycleWorktreeBase,editWorktreeCustom}}var import_react77=__toESM(require_react_production(),1);function useUpdateCheck(channel,openUpdatePage){let[checking,setChecking]=import_react77.useState(!1),[checked,setChecked]=import_react77.useState(null),current2=checked?.channel===channel?checked:null;async function run(){setChecking(!0);let info=await checkLatestVersion({force:!0,channel});setChecked({channel,info}),setChecking(!1)}return{state:checking?"checking":current2?"done":"idle",info:current2?.info??null,press:()=>{if(checking)return;if(current2?.info?.hasUpdate)openUpdatePage?.();else run()}}}var EMPTY_USAGE_SIGNAL=createStateCell(null);function SettingsDialog(props){let dialog=useDialog(),themeCtx=useTheme(),renderer=useRenderer(),{theme}=themeCtx,t3=useT(),padX=useDialogPaddingX(),[level,setLevel]=import_react79.useState("sidebar"),[section,setSection]=import_react79.useState(props.initialSection??"general"),[cursor,setCursor]=import_react79.useState(()=>Math.max(0,SECTIONS.findIndex((s2)=>s2.id===section))),[bodyRow,setBodyRow]=import_react79.useState(0),[feedbackTitle,setFeedbackTitle]=import_react79.useState(""),[feedbackBody,setFeedbackBody]=import_react79.useState(""),[feedbackStatus,setFeedbackStatus]=import_react79.useState(""),[reloadStatus,setReloadStatus]=import_react79.useState(""),hasDaemon=hasRestartableDaemon(props.orchestrator),remote2=props.orchestrator instanceof RemoteOrchestrator?props.orchestrator:null,prefs=useSettingsPrefs(props.kv,dialog),updateCheck=useUpdateCheck(prefs.updateChannel(),props.onCheckUpdate),appearance=useAppearanceSettings(props.kv,dialog,prefs),engines=useEngineSettings(props.kv,dialog,(max)=>setBodyRow((r6)=>Math.max(0,Math.min(r6,max)))),usage=useAccessor(remote2?remote2.usageSnapshotSignal():EMPTY_USAGE_SIGNAL),engineStatuses=useAccountProbes(section,engines.engineList()),integrations=useEngineIntegrations(section,engines.engineList()),needsHookInstall=enginesNeedingHookInstall(integrations.rows??[]),hooksInstalled=enginesWithHooksInstalled(integrations.rows??[]);async function runHookInstall(){await installEngineHooks(),integrations.reprobe()}async function runHookUninstall(){await uninstallEngineHooks(),integrations.reprobe()}let[skillError,setSkillError]=import_react79.useState(null);function runSkillInstall(){setSkillError(installSkillNow()),integrations.reprobe()}let autoRouting=useAutoRoutingSettings(props.kv,dialog,engines.engineList,engineStatuses),classifier=useClassifierSettings(props.kv,dialog,section==="autoRouting"),[keysFileExists,setKeysFileExists]=import_react79.useState(()=>userKeybindingsReport().exists);function createKeysFile(){try{createKeybindingsFile(userKeybindingsReport().path),reloadUserKeybindings()}catch{}setKeysFileExists(userKeybindingsReport().exists)}let plugins=usePluginSettings(section,dialog),marketplace=useMarketplace(section,dialog,plugins);function bodyRows(){return sectionRows(section,{engineList:engines.engineList(),plugins:plugins.rows.map((p3)=>({id:p3.id,settingKeys:p3.settings.map((s2)=>s2.key)})),marketplace:marketplace.rows.map((r6)=>r6.ref),hasDaemon,keybindingsFileExists:keysFileExists})}function bodyRowCount(){return bodyRows().length}function selectLanguage(locale){if(currentLang()===locale)return;setLocaleLang(locale),props.kv.set(LOCALE_KEY,locale)}function currentEngineRow(){if(section!=="engines"||level!=="body")return null;let row=rowAt(bodyRows(),bodyRow);return row?.kind==="engine"?row.vendor:null}async function sendFeedback(){setFeedbackStatus("submitting...");try{let result=submitFeedback({title:feedbackTitle,body:feedbackBody});setFeedbackStatus(`sent: ${result.url}`),setFeedbackTitle(""),setFeedbackBody(""),setBodyRow(0)}catch(err){setFeedbackStatus(`error: ${errorMessage(err)}
71
+ ${failureHint(err)}`)}}let editingFeedback=section==="feedback"&&level==="body";function feedbackFieldStep(delta){let next=bodyRow+delta;if(next<0||next>2){setLevel("sidebar");return}setBodyRow(next)}function enterBody(){if(level!=="sidebar"||bodyRowCount()===0)return;setLevel("body"),setBodyRow(0)}function moveCursor(delta){if(level==="sidebar"){let next=(cursor+delta+SECTIONS.length)%SECTIONS.length;setCursor(next);let nextSection=SECTIONS[next];if(nextSection)setSection(nextSection.id),setBodyRow(0);return}let len=bodyRowCount();if(len===0)return;setBodyRow((bodyRow+delta+len)%len)}function switchSection(id){setSection(id),setCursor(SECTIONS.findIndex((s2)=>s2.id===id)),setBodyRow(0),setLevel("sidebar")}let rowActivators={appearance:(row)=>appearance.open(row.setting),language:(row)=>selectLanguage(row.locale),toast:()=>prefs.toggleToast(),sound:()=>prefs.toggleSound(),soundVolume:()=>prefs.cycleSoundVolume(),crossTask:()=>prefs.toggleCrossTask(),finishedAlerts:()=>prefs.toggleFinishedAlerts(),keyHints:()=>toggleKeyHints(props.kv),prefixTapPresentation:(row)=>prefs.selectPrefixTapPresentation(row.presentation),zenDefaultOn:()=>prefs.toggleZenDefaultOn(),updateChannel:()=>prefs.cycleUpdateChannel(),updateNotify:()=>prefs.toggleUpdateNotify(),updateCheck:()=>updateCheck.press(),editorKind:()=>prefs.cycleEditorKind(),editorCustom:()=>void prefs.editEditorCustom(),worktreeBase:()=>prefs.cycleWorktreeBase(),worktreeCustom:()=>void prefs.editWorktreeCustom(),scrollbackRows:()=>void prefs.editScrollbackRows(),tabStripHideSingle:()=>prefs.cycleTabStripMode(),engine:(row)=>void engines.editEngine(row.vendor),engineAdd:()=>void engines.addEngineFlow(),engineHooksInstall:()=>void runHookInstall(),engineHooksUninstall:()=>void runHookUninstall(),engineSkillInstall:()=>runSkillInstall(),autoRoutingTier:(row)=>void autoRouting.edit(row.tier),autoRoutingClassifier:()=>classifier.cycle(),autoRoutingClassifierEndpoint:()=>void classifier.editEndpoint(),autoRoutingClassifierThreshold:()=>void classifier.editThreshold(),autoRoutingClassifierKey:()=>void classifier.editKey(),keysCreate:()=>createKeysFile(),pluginToggle:(row)=>plugins.toggle(row.pluginId),pluginSetting:(row)=>void plugins.editSetting(row.pluginId,row.key),pluginInstall:(row)=>void marketplace.install(row.ref),feedbackTitle:()=>setBodyRow(0),feedbackBody:()=>setBodyRow(1),feedbackSend:()=>void sendFeedback(),devReset:()=>void confirmResetState(dialog,props.kv,renderer),devRestartDaemon:()=>void confirmRestartDaemon(dialog,props.orchestrator,renderer),devReloadSettings:()=>setReloadStatus(reloadSettingsStatus(props.kv)),devRemoteProjects:()=>prefs.toggleRemoteProjects(),devAutoStatus:()=>prefs.toggleAutoStatus(),devDispatcher:()=>prefs.toggleDispatcher()};function activateBodyRow(){let row=rowAt(bodyRows(),bodyRow);if(!row)return;rowActivators[row.kind](row)}useBindings(()=>({enabled:dialog.stack.length===0&&!editingFeedback,bindings:[{key:"down",cmd:()=>moveCursor(1)},{key:"up",cmd:()=>moveCursor(-1)},{key:"j",cmd:()=>moveCursor(1)},{key:"k",cmd:()=>moveCursor(-1)},{key:"tab",cmd:()=>moveCursor(1)},{key:"right",cmd:enterBody},{key:"l",cmd:enterBody},{key:"left",cmd:()=>setLevel("sidebar")},{key:"h",cmd:()=>setLevel("sidebar")},{key:"return",cmd:()=>{if(level==="sidebar"){enterBody();return}activateBodyRow()}},{key:"r",cmd:()=>{let v3=currentEngineRow();if(v3)engines.renameEngine(v3)}},{key:"x",cmd:()=>{let v3=currentEngineRow();if(v3)engines.resetEngine(v3)}},{key:"d",cmd:()=>{let v3=currentEngineRow();if(v3)engines.chooseDefaultEngine(v3)}},{key:"space",cmd:()=>{let v3=currentEngineRow();if(v3)engines.toggleEngineEnabled(v3)}}]})),useBindings(()=>({enabled:editingFeedback,bindings:[{key:"tab",cmd:()=>feedbackFieldStep(1)},{key:"shift+tab",cmd:()=>feedbackFieldStep(-1)}]})),useBindings(()=>({enabled:editingFeedback&&bodyRow===2,bindings:[{key:"return",cmd:()=>void sendFeedback()}]}));let follow=useCursorFollow3(level==="body"?bodyRow:-1),cursorProps={level,bodyRow,setLevel,setBodyRow,rowRef:follow.rowRef},navHint=$jsx("box",{paddingTop:0,children:$jsx("text",{fg:theme.textMuted,children:editingFeedback?t3("settings.nav.feedback"):t3("settings.nav.default")})}),body=$jsxs("box",{paddingLeft:padX,paddingRight:padX,paddingBottom:1,gap:1,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",children:[$jsx("text",{attributes:TextAttributes39.BOLD,fg:theme.text,children:t3("settings.title")}),$jsx("text",{fg:theme.textMuted,onMouseUp:()=>props.onClose(),children:t3("settings.esc")})]}),$jsxs("box",{flexDirection:"row",gap:2,children:[$jsx(SettingsSectionSidebar,{level,cursor,switchSection}),$jsxs("box",{flexGrow:1,flexShrink:1,flexDirection:"column",gap:1,children:[section==="general"?$jsx(GeneralSettingsSection,{...cursorProps,prefs,appearance,currentLocale:currentLang(),selectLanguage,updateCheck,usage}):null,section==="engines"?$jsx(EngineSettingsSection,{...cursorProps,vendors:engines.engineList(),statuses:engineStatuses,isCustom:engines.isCustomEngine,engineProtocol:engines.engineProtocol,isEnabled:engines.isEngineEnabled,toggleEngine:engines.toggleEngineEnabled,chooseDefault:engines.chooseDefaultEngine,displayName:engines.engineName,renamedFrom:engines.engineRenamedFromName,commandText:engines.engineCommandText,hasCommandOverride:engines.engineHasCommandOverride,isDefaultEngine:(v3)=>engines.defaultEngine===v3,editEngine:(v3)=>void engines.editEngine(v3),onAddEngine:()=>void engines.addEngineFlow(),integrations:integrations.rows,needsHookInstall,hooksInstalled,onInstallHooks:()=>void runHookInstall(),onUninstallHooks:()=>void runHookUninstall(),skillError,onInstallSkill:runSkillInstall}):null,section==="autoRouting"?$jsx(AutoRoutingSettingsSection,{...cursorProps,autoRouting,classifier}):null,section==="plugins"?$jsx(PluginSettingsSection,{...cursorProps,plugins:plugins.rows,toggle:plugins.toggle,editSetting:(id,key)=>void plugins.editSetting(id,key)}):null,section==="marketplace"?$jsx(MarketplaceSettingsSection,{...cursorProps,rows:marketplace.rows,loading:marketplace.loading,offline:marketplace.offline,status:marketplace.status,install:(ref)=>void marketplace.install(ref)}):null,section==="keys"?$jsx(KeybindingsSettingsSection,{...cursorProps,prefs,onCreateFile:createKeysFile}):null,section==="feedback"?$jsx(FeedbackSettingsSection,{...cursorProps,title:feedbackTitle,setTitle:(v3)=>{setFeedbackTitle(v3),setFeedbackStatus("")},body:feedbackBody,setBody:(v3)=>{setFeedbackBody(v3),setFeedbackStatus("")},status:feedbackStatus,onTitleSubmit:()=>setBodyRow(1),submit:()=>void sendFeedback()}):null,section==="dev"?$jsx(DevSettingsSection,{...cursorProps,prefs,hasDaemon,confirmReset:()=>void confirmResetState(dialog,props.kv,renderer),confirmRestartDaemon:()=>void confirmRestartDaemon(dialog,props.orchestrator,renderer),reloadSettings:()=>setReloadStatus(reloadSettingsStatus(props.kv)),reloadStatus}):null]})]})]});return $jsxs("box",{flexDirection:"column",flexGrow:1,children:[$jsx("scrollbox",{ref:follow.scrollRef,flexGrow:1,flexShrink:1,flexBasis:0,verticalScrollbarOptions:{trackOptions:{foregroundColor:"transparent"}},children:body}),$jsx("box",{paddingLeft:padX,paddingRight:padX,children:navHint})]})}import{TextAttributes as TextAttributes40}from"@opentui/core";var import_react81=__toESM(require_react_production(),1);function systemOpenArgv(absPath,platform=process.platform){if(platform==="darwin")return["open",absPath];if(platform==="win32")return["cmd","/c","start","",absPath];return["xdg-open",absPath]}function openWithSystemViewer(absPath){let[cmd,...args]=systemOpenArgv(absPath);return spawnDetached(cmd??"",args)}function UpdatePage(props){let{theme}=useTheme(),t3=useT(),renderer=useRenderer(),[info,setInfo]=import_react81.useState(null),[checked,setChecked]=import_react81.useState(!1),[releaseNotes,setReleaseNotes]=import_react81.useState([]),[loadingNotes,setLoadingNotes]=import_react81.useState(!0),[selected,setSelected]=import_react81.useState("close"),[status,setStatus]=import_react81.useState(null),[channel]=import_react81.useState(()=>preferredReleaseChannel()),command=updateCommandFor(channel),latest=info?.latest??CURRENT_VERSION,latestUnknown=checked&&info===null,hasUpdate=info?.hasUpdate===!0,upToDate=checked&&info!==null&&!hasUpdate,releaseUrl=releaseNotes[0]?.url??releasePageUrl(latest),actions=[...hasUpdate?[{id:"update",key:"U",label:t3("update.actions.updateNow"),detail:command}]:[],{id:"release",key:"R",label:t3("update.actions.openRelease"),detail:releaseUrl??t3("update.releaseUrlUnavailable")},{id:"close",key:"Q",label:t3("update.actions.close"),detail:t3("update.actions.closeDetail")}];import_react81.useEffect(()=>{load()},[]);async function load(){let next=await checkLatestVersion({force:!0,channel});if(setInfo(next),setChecked(!0),next?.hasUpdate)setSelected("update");let fetched=next?.hasUpdate?await fetchReleaseNotesRange({current:CURRENT_VERSION,latest:next.latest,locale:currentLang()}):[];setReleaseNotes(fetched),setLoadingNotes(!1)}function move(delta){let ids=actions.map((a2)=>a2.id),next=(ids.indexOf(selected)+delta+ids.length)%ids.length;setSelected(ids[next]??"close")}function activate(id=selected){if(id==="close"){props.onClose();return}if(id==="update"&&!hasUpdate)return;if(id==="release"){setStatus(openWithSystemViewer(releaseUrl)?t3("update.statusReleaseOpened"):t3("update.statusReleaseError"));return}runUpdater()}async function runUpdater(){setStatus(t3("update.statusRunningUpdater")),await new Promise((resolve2)=>setTimeout(resolve2,30)),await runShellUpdater({renderer,t:t3,targetLabel:latest,command})}return useBindings(()=>({bindings:[{key:"up",cmd:()=>move(-1)},{key:"down",cmd:()=>move(1)},{key:"k",cmd:()=>move(-1)},{key:"j",cmd:()=>move(1)},{key:"return",cmd:()=>activate()},{key:"u",cmd:()=>activate("update")},{key:"r",cmd:()=>activate("release")},...pageCloseBindings(()=>activate("close"))]})),$jsxs("box",{flexDirection:"column",flexGrow:1,backgroundColor:theme.background,paddingTop:1,paddingLeft:2,paddingRight:2,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",flexShrink:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes40.BOLD,wrapMode:"none",children:t3("update.pageTitle")}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",onMouseUp:()=>activate("close"),children:t3("update.closeHint")})]}),$jsxs("box",{flexDirection:"row",gap:2,flexShrink:0,paddingTop:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("update.current")}),$jsxs("text",{fg:theme.text,attributes:TextAttributes40.BOLD,wrapMode:"none",children:["v",CURRENT_VERSION]}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("update.latest")}),latestUnknown?$jsx("text",{fg:theme.textMuted,attributes:TextAttributes40.BOLD,wrapMode:"none",children:t3("update.latestUnknown")}):$jsxs("text",{fg:hasUpdate?theme.warning:theme.success,attributes:TextAttributes40.BOLD,wrapMode:"none",children:["v",latest]})]}),latestUnknown?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("update.registryRetry")}):null,upToDate?$jsx("box",{flexShrink:0,paddingTop:1,children:$jsx("text",{fg:theme.success,wrapMode:"word",children:t3("update.upToDate")})}):null,$jsx("box",{flexDirection:"column",flexShrink:0,paddingTop:1,gap:0,children:actions.map((action)=>{let cursor=selected===action.id,chrome=resolveRowSelectionChrome2(theme,{cursor});return $jsxs("box",{flexDirection:"row",gap:0,backgroundColor:chrome.backgroundColor,onMouseUp:()=>activate(action.id),children:[$jsx("text",{fg:chrome.markerColor,wrapMode:"none",children:chrome.marker}),$jsxs("box",{flexDirection:"row",gap:1,flexGrow:1,paddingLeft:1,paddingRight:1,children:[$jsx("box",{width:4,flexShrink:0,children:$jsxs("text",{fg:theme.accent,attributes:TextAttributes40.BOLD,wrapMode:"none",children:["[",action.key,"]"]})}),$jsx("box",{width:14,flexShrink:0,children:$jsx("text",{fg:theme.text,attributes:cursor?TextAttributes40.BOLD:void 0,wrapMode:"none",children:action.label})}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:action.detail})]})]},action.id)})}),status?$jsx("text",{fg:theme.info,wrapMode:"word",children:status}):null,hasUpdate?$jsx("box",{flexShrink:0,paddingTop:1,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes40.DIM,wrapMode:"none",children:t3("update.changesSectionHeader",{from:CURRENT_VERSION,to:latest})})}):null,$jsx("scrollbox",{flexGrow:1,flexShrink:1,stickyScroll:!1,verticalScrollbarOptions:{trackOptions:{foregroundColor:"transparent"}},children:$jsxs("box",{flexDirection:"column",paddingRight:1,paddingBottom:1,gap:0,children:[loadingNotes?$jsx("text",{fg:theme.textMuted,children:t3("update.loadingNotes")}):null,!loadingNotes&&hasUpdate&&releaseNotes.length===0?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t3("update.notesUnavailable")}):null,releaseNotes.map((release)=>$jsxs("box",{flexDirection:"column",paddingBottom:1,gap:0,children:[$jsxs("text",{fg:theme.text,attributes:TextAttributes40.BOLD,wrapMode:"none",children:["v",release.version]}),$jsx(ReleaseNotesBody,{body:release.body})]},release.version))]})})]})}import{TextAttributes as TextAttributes41}from"@opentui/core";var import_react82=__toESM(require_react_production(),1);var LAND_CONFLICT_RE=/LAND_CONFLICT/,MAIN_DIRTY_RE=/MAIN_CHECKOUT_DIRTY/;async function landTaskAction(deps,taskId,branchLabel){let{t:t3}=deps,preflight;try{preflight=await deps.orchestrator.landPreflight(taskId)}catch(err){return deps.notifyError(t3("worktrees.land.failed",{error:err instanceof Error?err.message:String(err)})),console.error("[rove land] preflight failed:",err),!1}if(preflight.refusal){if(preflight.refusal==="MAIN_CHECKOUT_DIRTY")deps.notifyNeedsInput(t3("worktrees.land.dirtyBase"));else deps.notifyError(t3("worktrees.land.failed",{error:preflight.message??preflight.refusal}));return!1}let body=t3(preflight.ahead===1?"worktrees.land.confirmBodyOne":"worktrees.land.confirmBody",{branch:branchLabel,landedOn:preflight.landedOn,commits:preflight.ahead??"?"});if(!await deps.confirm(body))return!1;try{let res=await deps.orchestrator.landTask(taskId,{callerCwd:deps.callerCwd});deps.notifyInfo(t3("worktrees.land.done",{branch:res.branch,landedOn:res.landedOn,commit:res.commit}));let cleanup=res.worktree;if(cleanup&&!cleanup.removed)deps.notifyNeedsInput(t3("worktrees.land.worktreeKept",{reason:cleanup.reason??"refused"}));else if(cleanup?.reason)deps.notifyNeedsInput(t3("worktrees.land.worktreePathStale",{reason:cleanup.reason}));if(cleanup?.residue)deps.notifyNeedsInput(t3("worktrees.land.worktreeResidue",{path:cleanup.residue.path,reason:cleanup.residue.reason}));return!0}catch(err){let msg=err instanceof Error?err.message:String(err);if(LAND_CONFLICT_RE.test(msg))deps.notifyNeedsInput(t3("worktrees.land.conflict",{files:msg}));else if(MAIN_DIRTY_RE.test(msg))deps.notifyNeedsInput(t3("worktrees.land.dirtyBase"));else deps.notifyError(t3("worktrees.land.failed",{error:msg}));return console.error("[rove land] failed:",err),!1}}function flattenRows(projects){return projects.flatMap((p3)=>p3.worktrees)}function taskIdForPath(orch,wtPath){let norm=(p3)=>p3.replace(/^\/private\//,"/");return orch.listTasks().find((task)=>task.worktreePath&&samePath(norm(task.worktreePath),norm(wtPath)))?.id}function WorktreesPage(props){let{theme}=useTheme(),dialog=useDialog(),t3=useT(),notif=useNotifications();function notifyError(message){notif.notify({kind:"error",taskId:"",tabId:"",title:message})}function notifyNeedsInput(message){notif.notify({kind:"needs_input",taskId:"",tabId:"",title:message})}function notifyInfo(message){notif.notify({kind:"done",taskId:"",tabId:"",title:message})}let[projects,setProjects]=import_react82.useState(null),[reloadTick,setReloadTick]=import_react82.useState(0),refetch=()=>setReloadTick((tick3)=>tick3+1);import_react82.useEffect(()=>{let disposed=!1,fullLanded=!1,orch=props.orchestrator;if(!orch){setProjects([]);return}return orch.listWorktrees({network:!1}).then((rows)=>{if(!disposed&&!fullLanded)setProjects(rows)}).catch(()=>{}),orch.listWorktrees().then((rows)=>{if(fullLanded=!0,disposed)return;setProjects(rows);let live=new Set(flattenRows(rows).map((r6)=>r6.path));setRemovingPaths((paths)=>paths.filter((p3)=>live.has(p3)))}).catch(()=>{}),()=>{disposed=!0}},[props.orchestrator,reloadTick]);let[removingPaths,setRemovingPaths]=import_react82.useState([]),visibleProjects=(projects??[]).map((p3)=>({...p3,worktrees:p3.worktrees.filter((w4)=>!removingPaths.includes(w4.path))})),flatRows=flattenRows(visibleProjects),[cursor,setCursor]=import_react82.useState(0);import_react82.useEffect(()=>{setCursor((c2)=>clampCursor2(c2,flatRows.length))},[flatRows.length]);let follow=useCursorFollow3(cursor),[busyPath,setBusyPath]=import_react82.useState(null);async function deleteInBackground(row,force){let orch=props.orchestrator;if(!orch)return;setRemovingPaths((paths)=>[...paths,row.path]);try{let residue=await orch.removeWorktree(row.path,force);if(residue)notifyNeedsInput(t3("worktrees.delete.residue",{path:residue.path,reason:residue.reason}));refetch()}catch(err){setRemovingPaths((paths)=>paths.filter((p3)=>p3!==row.path));let reason=force?null:dirtyRefusalReason(err);if(reason!==null){if(await DialogConfirm.show(dialog,t3("worktrees.delete.forceTitle"),`${t3("worktrees.delete.forceBody",{branch:row.branch||row.path})}
72
72
 
73
73
  ${t3("worktrees.delete.forceReason",{reason})}`,t3("common.cancel"),t3("worktrees.delete.button"),{danger:!0})===!0)await deleteInBackground(row,!0);return}notifyError(t3("worktrees.delete.failed",{error:String(err)})),console.error("[rove worktrees] delete failed:",err)}}async function requestDelete(row){if(!props.orchestrator||busyPath||removingPaths.includes(row.path))return;if(await DialogConfirm.show(dialog,t3("worktrees.delete.confirmTitle"),t3("worktrees.delete.confirmBody",{branch:row.branch||row.path}),t3("common.cancel"),t3("worktrees.delete.button"),{danger:!0})!==!0)return;deleteInBackground(row,!1)}async function requestLand(row){let orch=props.orchestrator;if(!orch||busyPath)return;let taskId=taskIdForPath(orch,row.path);if(!taskId){notifyError(t3("worktrees.land.noTask")),console.error("[rove worktrees] land refused: no tracked task for",row.path);return}setBusyPath(row.path);try{await landTaskAction({orchestrator:orch,confirm:(body)=>DialogConfirm.show(dialog,t3("worktrees.land.confirmTitle"),body,t3("common.cancel"),t3("worktrees.land.button")).then((ok)=>ok===!0),notifyInfo,notifyNeedsInput,notifyError,t:t3,callerCwd:process.cwd()},taskId,row.branch||row.path),refetch()}finally{setBusyPath(null)}}useBindings(()=>({enabled:dialog.stack.length===0,bindings:[...pageCloseBindings(props.onClose),{key:"up",cmd:()=>setCursor((c2)=>clampCursor2(c2-1,flatRows.length))},{key:"k",cmd:()=>setCursor((c2)=>clampCursor2(c2-1,flatRows.length))},{key:"down",cmd:()=>setCursor((c2)=>clampCursor2(c2+1,flatRows.length))},{key:"j",cmd:()=>setCursor((c2)=>clampCursor2(c2+1,flatRows.length))},{key:"d",cmd:()=>{let row=flatRows[cursor];if(row)requestDelete(row)}},{key:"l",cmd:()=>{let row=flatRows[cursor];if(row)requestLand(row)}}]}));function remoteBadge(status){if(status===!0)return $jsxs("text",{fg:theme.success,children:[" ",t3("worktrees.badge.remoteOn")]});if(status===!1)return $jsxs("text",{fg:theme.warning,children:[" ",t3("worktrees.badge.remoteOff")]});return $jsxs("text",{fg:theme.textMuted,children:[" ",t3("worktrees.badge.remoteUnknown")]})}function verdictBadge(row){if(row.verdictReason==="dirty"||row.verdictReason==="fresh")return null;let fg=row.verdict==="merged"?theme.success:row.verdict==="stale"?theme.warning:theme.accent;return $jsxs("text",{fg,children:[" ",t3(`worktrees.verdict.${row.verdictReason}`)]})}let loading=projects===null,rowBase=0;return $jsxs("scrollbox",{ref:follow.scrollRef,flexGrow:1,backgroundColor:theme.background,paddingTop:1,paddingLeft:2,paddingRight:2,paddingBottom:1,verticalScrollbarOptions:{trackOptions:{foregroundColor:"transparent"}},children:[$jsx("box",{flexDirection:"row",justifyContent:"space-between",children:$jsx("text",{attributes:TextAttributes41.BOLD,fg:theme.text,children:t3("worktrees.title")})}),loading?$jsx("text",{fg:theme.textMuted,children:t3("worktrees.loading")}):visibleProjects.length===0?$jsx("text",{fg:theme.textMuted,children:t3("worktrees.noProjects")}):visibleProjects.map((project)=>{let base=rowBase;return rowBase+=project.worktrees.length,$jsxs("box",{gap:0,paddingTop:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:project.repo}),project.worktrees.length===0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("worktrees.noWorktrees")}):project.worktrees.map((row,i2)=>{let absoluteIndex=base+i2,isCursor=absoluteIndex===cursor,chrome=resolveRowSelectionChrome2(theme,{cursor:isCursor});return $jsxs("box",{ref:follow.rowRef(absoluteIndex),gap:0,backgroundColor:chrome.backgroundColor,onMouseUp:()=>setCursor(absoluteIndex),children:[$jsxs("box",{flexDirection:"row",children:[$jsx("text",{fg:chrome.markerColor,wrapMode:"none",children:chrome.marker}),$jsx("text",{fg:theme.text,attributes:isCursor?TextAttributes41.BOLD:void 0,wrapMode:"none",children:` ${row.branch||t3("worktrees.row.detached")}`}),row.roveManaged?$jsxs("text",{fg:theme.textMuted,children:[" ",t3("worktrees.badge.roveManaged")]}):null,row.dirty===!0?$jsxs("text",{fg:theme.warning,children:[" ",t3("worktrees.badge.dirty")]}):null,row.dirty===null?$jsxs("text",{fg:theme.textMuted,children:[" ",t3("worktrees.badge.dirtyUnknown")]}):null,remoteBadge(row.branchOnRemote),verdictBadge(row),busyPath===row.path?$jsx("text",{fg:theme.textMuted,children:" \u2026"}):null]}),$jsxs("box",{flexDirection:"row",children:[$jsx("text",{fg:chrome.markerColor,wrapMode:"none",children:chrome.marker}),$jsxs("box",{flexDirection:"row",justifyContent:"space-between",flexGrow:1,paddingLeft:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:row.path}),row.createdAtMs>0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("worktrees.row.created",{age:relativeAge(row.createdAtMs)})}):null]})]})]},row.path)})]},project.repo)})]})}function useHostPagesState(focus,opts={}){let[whatsNewFrom,setWhatsNewFrom]=import_react83.useState(opts.whatsNewFrom??null),closeWhatsNew=import_react83.useCallback(()=>setWhatsNewFrom(null),[]),[welcome,setWelcome]=import_react83.useState(opts.welcome??null),closeWelcome=import_react83.useCallback(()=>setWelcome(null),[]),[settingsOpen,setSettingsOpen]=import_react83.useState(!1),[settingsSection,setSettingsSection]=import_react83.useState(void 0),[worktreesOpen,setWorktreesOpen]=import_react83.useState(!1),[updateOpen,setUpdateOpen]=import_react83.useState(!1),[nav,setNav]=import_react83.useState("terminal"),goToNav=(next)=>{setNav(next),focus.setFocused(focusPaneForNav(next))};return{nav,setNav,goToNav,settingsOpen,settingsSection,openSettings:(section)=>{setSettingsSection(section),setSettingsOpen(!0)},closeSettings:()=>setSettingsOpen(!1),worktreesOpen,openWorktrees:()=>setWorktreesOpen(!0),closeWorktrees:()=>setWorktreesOpen(!1),updateOpen,openUpdate:()=>setUpdateOpen(!0),closeUpdate:()=>setUpdateOpen(!1),openPage:goToNav,closePage:()=>goToNav("terminal"),whatsNewFrom,closeWhatsNew,welcome,closeWelcome}}function renderFullWindowPage(deps){if(deps.worktreesOpen)return $jsx(WorktreesPage,{orchestrator:deps.orchestrator,onClose:deps.closeWorktrees});if(deps.updateOpen)return $jsx(UpdatePage,{onClose:deps.closeUpdate});return null}function openTaskOnTab(closePage,activateTask){return(taskId,tabId)=>{if(closePage(),activateTask(taskId),tabId)requestTabActivation(taskId,tabId)}}function renderContentPage(deps){let Page=deps.pages.find((page)=>page.id===deps.nav)?.component;if(!Page)return null;return $jsx(Page,{orchestrator:deps.orchestrator,focused:deps.contentFocused,onClose:deps.closePage,onOpenTask:openTaskOnTab(deps.closePage,deps.activateTask),selectedTask:deps.selectedTask,engineStates:deps.engineStates})}function useHostPagesRender(opts){let{orchestrator,pages,focus,dialog,kv,dims,selectedTask,activeTaskId,tasks:tasks2,engineState,activateTask}=opts,pageEntries2=usePageEntries(),activePane=dialog.stack.length>0?null:focus.focused,pageDeps=import_react83.useMemo(()=>({orchestrator,selectedTask,nav:pages.nav,pages:pageEntries2,worktreesOpen:pages.worktreesOpen,updateOpen:pages.updateOpen,closeWorktrees:pages.closeWorktrees,closePage:pages.closePage,closeUpdate:pages.closeUpdate,activateTask:(taskId)=>void activateTask(taskId),engineStates:engineState,contentFocused:activePane==="workspace"}),[orchestrator,selectedTask,pages,pageEntries2,engineState,activePane,activateTask]),fullWindowPage=import_react83.useMemo(()=>renderFullWindowPage(pageDeps),[pageDeps]),contentPage=import_react83.useMemo(()=>renderContentPage(pageDeps),[pageDeps]),narrow=isNarrowWidth(dims.width);import_react83.useEffect(()=>{if(narrow&&focus.focused==="files")focus.setFocused("workspace")},[narrow,focus]);let surface=narrow?narrowSurface({focusedPane:focus.focused,hasSelection:selectedTask!=null,hasOpenPage:contentPage!=null}):null,showSidebar=surface!=="content",showContent=surface!=="sidebar",recentTask=import_react83.useMemo(()=>(narrow?tasks2.find((task)=>task.id===activeTaskId&&!task.deletion):null)??null,[narrow,tasks2,activeTaskId]);return{settingsPage:pages.settingsOpen?$jsx("box",{flexGrow:1,backgroundColor:"transparent",paddingTop:1,children:$jsx(SettingsDialog,{kv,orchestrator,initialSection:pages.settingsSection,onCheckUpdate:()=>{pages.closeSettings(),pages.openUpdate()},onClose:pages.closeSettings})}):null,fullWindowPage,contentPage,showSidebar,showContent,recentTask}}var import_react92=__toESM(require_react_production(),1);var import_react91=__toESM(require_react_production(),1);function createSidebarController(opts){let schedule=opts.scheduleTimeout??((cb,ms)=>{let t3=setTimeout(cb,ms);return()=>clearTimeout(t3)}),pendingG=!1,cancelTimer=null,armChord=()=>{pendingG=!0,cancelTimer?.(),cancelTimer=schedule(()=>{pendingG=!1,cancelTimer=null},700)},disarm=()=>{pendingG=!1,cancelTimer?.(),cancelTimer=null},move=(delta)=>{let ids=opts.getFlatIds();if(ids.length===0)return;let cur=opts.getCursor(),start=cur<0?0:cur,next=Math.min(ids.length-1,Math.max(0,start+delta));opts.setCursor(next)},jumpTo=(index)=>{let ids=opts.getFlatIds();if(ids.length===0)return;opts.setCursor(Math.min(ids.length-1,Math.max(0,index)))};return{moveDown(){disarm(),move(1)},moveUp(){disarm(),move(-1)},selectCurrent(){disarm();let ids=opts.getFlatIds(),cur=opts.getCursor();if(cur<0||cur>=ids.length)return;let id=ids[cur];if(id!==void 0)opts.onSelect(id)},pressG(){if(pendingG)disarm(),jumpTo(0);else armChord()},pressShiftG(){disarm(),jumpTo(opts.getFlatIds().length-1)},isChordArmed(){return pendingG},disarmChord(){disarm()}}}import{MouseButton as MouseButton3,TextAttributes as TextAttributes42}from"@opentui/core";function zenChipGlyph(platform=process.platform){return platform==="darwin"?"\u262F":"\u25D0"}function SectionHeader(props){let{theme,transparentBackground}=useTheme(),dividerColor=transparentBackground?theme.border:theme.borderSubtle,dims=useTerminalSize();return $jsxs("box",{flexDirection:"column",flexShrink:0,children:[props.topPad?$jsx("box",{flexShrink:0,children:$jsx("text",{wrapMode:"none",children:" "})}):null,$jsxs("box",{flexDirection:"row",flexShrink:0,gap:1,paddingLeft:1+(props.depth??0)*2,paddingRight:1,onMouseUp:props.onPress||props.onContextMenu?(evt)=>{if(evt.button===MouseButton3.RIGHT&&props.onContextMenu){props.onContextMenu(evt.x,evt.y);return}props.onPress?.()}:void 0,children:[props.prefix?$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:props.prefix}):null,$jsx("text",{fg:theme.textMuted,attributes:TextAttributes42.BOLD,wrapMode:"none",flexShrink:0,children:props.label}),$jsx("text",{fg:dividerColor,wrapMode:"none",flexBasis:0,flexGrow:1,flexShrink:1,children:dividerRule(dims.width)}),props.suffix?$jsx("text",{fg:theme.info,attributes:TextAttributes42.BOLD,wrapMode:"none",flexShrink:0,children:props.suffix}):null]})]})}function SidebarSearchInput(props){let{theme}=useTheme(),t3=useT();return $jsxs("box",{flexDirection:"row",gap:0,flexShrink:0,paddingBottom:1,paddingLeft:1,children:[$jsx("text",{fg:theme.info,wrapMode:"none",children:"/"}),$jsx("text",{fg:theme.text,wrapMode:"none",children:props.query}),$jsx("text",{fg:theme.info,attributes:TextAttributes42.BLINK,wrapMode:"none",children:"\u2588"}),props.query.length===0?$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:[" ",t3("tasks.search.placeholder")]}):$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:[" ",props.matchCount,"/",props.totalCount]})]})}function SidebarSortLine(props){let{theme}=useTheme(),t3=useT(),mode={default:t3("tasks.sort.modes.default"),recent:t3("tasks.sort.modes.recent"),attention:t3("tasks.sort.modes.attention"),name:t3("tasks.sort.modes.name")}[props.mode];return $jsx("box",{flexShrink:0,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("tasks.sort.label",{mode})})})}function SidebarBrandHeader(props){let{theme}=useTheme();return $jsxs("box",{flexDirection:"row",justifyContent:"space-between",gap:1,flexShrink:0,paddingLeft:1,paddingRight:1,children:[$jsxs("box",{flexDirection:"row",gap:1,children:[$jsx("text",{fg:props.focused?theme.focusAccent:theme.textMuted,attributes:TextAttributes42.BOLD,wrapMode:"none",children:"ROVE"}),props.status?$jsxs("box",{position:"relative",onMouseUp:()=>props.onStatusClick?.(),children:[$jsx("text",{fg:props.status.emphasize?theme.warningOnHost:theme.textMuted,attributes:props.status.emphasize?TextAttributes42.BOLD:TextAttributes42.DIM,wrapMode:"none",children:props.status.label}),props.onStatusClick?$jsx(ShortcutRevealBadge,{bindingId:"inbox.show"}):null]}):null]}),props.update?$jsxs("box",{position:"relative",flexShrink:0,onMouseUp:()=>props.onUpdateClick?.(),children:[$jsx("text",{fg:theme.warningOnHost,attributes:TextAttributes42.BOLD,wrapMode:"none",children:props.update.label}),props.onUpdateClick?$jsx(ShortcutRevealBadge,{bindingId:"tasks.update"}):null]}):null]})}function SidebarCreateAction(props){let{theme,transparentBackground}=useTheme(),t3=useT(),keycap=legendCap("task.new");if(!props.onAddTask)return null;return $jsx("box",{flexShrink:0,paddingRight:1,children:$jsxs("box",{position:"relative",flexDirection:"row",flexShrink:0,gap:1,paddingLeft:1,paddingRight:1,backgroundColor:transparentBackground?void 0:theme.backgroundElement,onMouseUp:()=>props.onAddTask?.(),children:[$jsx("text",{fg:theme.text,attributes:TextAttributes42.BOLD,wrapMode:"none",flexGrow:1,children:t3("tasks.menu.newTask")}),$jsx("text",{fg:theme.primary,attributes:TextAttributes42.BOLD,wrapMode:"none",flexShrink:0,children:"+"}),keycap?$jsx("text",{fg:theme.textMuted,attributes:TextAttributes42.DIM,wrapMode:"none",flexShrink:0,children:keycap}):null,$jsx(ShortcutRevealBadge,{bindingId:"task.new"})]})})}function SidebarNavRail(props){let{theme}=useTheme();useT();let pages=usePageEntries();if(pages.length===0)return null;return $jsx("box",{flexDirection:"column",flexShrink:0,paddingBottom:1,children:pages.map((item)=>{let active=props.nav===item.id;return $jsxs("box",{position:"relative",flexDirection:"row",flexShrink:0,paddingLeft:1,paddingRight:1,onMouseUp:(e2)=>{e2.stopPropagation(),props.setNav(item.id)},children:[$jsx("text",{fg:active?theme.text:theme.textMuted,attributes:active?TextAttributes42.BOLD:void 0,wrapMode:"none",flexGrow:1,children:item.title()}),item.action?$jsx(ShortcutRevealBadge,{bindingId:item.action}):null]},item.id)})})}function SidebarZenChip(props){let{theme}=useTheme();return $jsxs("box",{position:"relative",flexShrink:0,children:[$jsx("text",{fg:theme.accent,attributes:TextAttributes42.BOLD,wrapMode:"none",onMouseUp:(e2)=>{e2.stopPropagation(),props.onZenClick?.()},children:`${zenChipGlyph()} ZEN`}),$jsx(ShortcutRevealBadge,{bindingId:"workspace.zenToggle"})]})}function RoutinesTreeRow(props){let{theme}=useTheme(),t3=useT(),engineState=props.shared.engineState,activityOf=(taskId)=>engineState?.get(taskId),settling=!props.expanded&&props.tasks.some((task)=>isSettlingActivity(activityOf(task.id)?.state));useClockTick(settling);let waiting=props.expanded?0:countWaitingOnYou(props.tasks,activityOf),chip=waiting>0?` \xB7 ${t3("tasks.group.waitingOnYou")}: ${waiting}`:"",label=truncateEndCells(props.count===1?t3("tasks.routinesRowOne"):t3("tasks.routinesRow",{count:String(props.count)}),treeLabelBudget(props.shared,2+displayWidth(chip)),charWidth);return $jsxs(RowShell,{rowId:props.rowId,flatIndex:props.flatIndex,depth:1,shared:props.shared,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",width:2,flexShrink:0,children:props.expanded?"\u25BE ":"\u25B8 "}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:1,children:label}),chip?$jsx("text",{fg:theme.error,wrapMode:"none",flexShrink:0,children:chip}):null]})}function isSettlingActivity(state){return state==="error"||state==="dead"}function ArchivedTreeRow(props){let{theme}=useTheme(),t3=useT(),label=truncateEndCells(t3("tasks.archivedRow",{count:String(props.count)}),treeLabelBudget(props.shared,2),charWidth);return $jsxs(RowShell,{rowId:props.rowId,flatIndex:props.flatIndex,depth:0,shared:props.shared,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",width:2,flexShrink:0,children:props.expanded?"\u25BE ":"\u25B8 "}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:1,children:label})]})}function SidebarTreeBody(props){let{theme}=useTheme(),t3=useT();return $jsx("scrollbox",{ref:props.setScrollRef,flexGrow:1,minHeight:0,stickyScroll:!1,verticalScrollbarOptions:{visible:!1},children:$jsxs("box",{flexShrink:0,gap:0,children:[props.rows.map((row,i2)=>{if(row.kind==="project"){let isScratch=row.id===SCRATCH_SECTION_ID;return $jsx(SectionHeader,{label:isScratch?t3("tasks.header.scratch"):row.label,suffix:props.movingProjectId===row.id?t3("tasks.moveChip"):void 0,topPad:i2>0,depth:row.depth,onContextMenu:props.onProjectContextMenu?(x2,y3)=>props.onProjectContextMenu?.(row.id,x2,y3):void 0},row.id)}if(row.kind==="recent")return $jsx(RecentJumpRow,{rowId:row.id,flatIndex:props.flatIndexOf.get(row.id)??-1,task:row.task,shared:props.shared},row.id);if(row.kind==="routines")return $jsx(RoutinesTreeRow,{rowId:row.id,flatIndex:props.flatIndexOf.get(row.id)??-1,count:row.count,tasks:row.tasks,expanded:row.expanded,shared:props.shared},row.id);if(row.kind==="archived")return $jsx(ArchivedTreeRow,{rowId:row.id,flatIndex:props.flatIndexOf.get(row.id)??-1,count:row.count,expanded:row.expanded,shared:props.shared},row.id);return $jsx(WorktreeTreeRow,{rowId:row.id,flatIndex:props.flatIndexOf.get(row.id)??-1,task:row.task,depth:row.depth,level:row.level,fold:row.fold,title:row.title,remote:row.remote,shared:props.shared},row.id)}),props.rows.length===0?$jsx("box",{paddingTop:1,paddingLeft:1,children:$jsx("text",{fg:theme.textMuted,children:t3(sidebarEmptyStateKey({searching:props.searching,projectFilter:!1}))})}):null]})})}function cursorTaskIdOf(rowId){if(rowId===void 0||rowId===RECENT_ROW_ID)return null;return parseRowId(rowId).taskId}function useTreeBindings(opts){let{focused,search,menu,moveMode,onMoveModeExit,controller,flatIdsRef,cursorRef,moveCursorRow,onDeleteRequest,onRenameRequest,onPinRequest,onLocalMergeRequest,markKeysUsed}=opts;function withCursorTask(fn){let taskId=cursorTaskIdOf(flatIdsRef.current[cursorRef.current]);if(taskId!==null&&fn)fn(taskId)}useBindings(()=>({enabled:focused&&!search.active&&!menu.open,bindings:bindByIds({"sidebar.nav":(_evt,slot)=>{markKeysUsed();let down=(slot??0)%2===0;if(moveMode){moveCursorRow(down?1:-1);return}if(down)controller.moveDown();else controller.moveUp()},"sidebar.select":()=>{if(markKeysUsed(),moveMode){onMoveModeExit?.();return}controller.selectCurrent()},"sidebar.goto":(_evt,slot)=>{if(moveMode)return;if((slot??0)%2===1)controller.pressShiftG();else controller.pressG()},"sidebar.tree.open":()=>{if(moveMode)return;controller.selectCurrent()},"sidebar.search.enter":()=>{if(moveMode)return;search.enter()},"sidebar.delete":()=>{if(moveMode)return;markKeysUsed(),withCursorTask(onDeleteRequest)},"sidebar.rename":()=>{if(moveMode)return;markKeysUsed(),withCursorTask(onRenameRequest)},"sidebar.localMerge":()=>withCursorTask(onLocalMergeRequest),"sidebar.pin":()=>{if(moveMode)return;markKeysUsed(),withCursorTask(onPinRequest)}})})),useBindings(()=>({enabled:focused&&moveMode,bindings:[{key:"escape",cmd:()=>onMoveModeExit?.()}]})),useBindings(()=>({enabled:focused&&search.active,bindings:bindByIds({"sidebar.search.nav":(_evt,slot)=>{if((slot??0)%2===0)controller.moveDown();else controller.moveUp()},"sidebar.search.submit":()=>{controller.selectCurrent(),search.exit()},"sidebar.search.cancel":()=>search.exit()})})),useBindings(()=>({enabled:focused&&menu.open,bindings:[...bindByIds({"sidebar.nav":(_evt,slot)=>menu.moveCursor((slot??0)%2===0?1:-1),"sidebar.select":()=>menu.pickCurrent()}),{key:"escape",cmd:()=>menu.close()}]}))}var import_react84=__toESM(require_react_production(),1);import{existsSync as existsSync2,readFileSync,statSync}from"fs";import{isAbsolute,join as join3,resolve as resolve2}from"path";var GIT_TIMEOUT_MS=1e4;function gitDirOf(worktree){let dotGit=join3(worktree,".git");try{if(statSync(dotGit).isDirectory())return dotGit;let match=/^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit,"utf8"));if(!match?.[1])return null;let dir=match[1].trim();return isAbsolute(dir)?dir:resolve2(worktree,dir)}catch{return null}}function pausedGitOperation(worktree){if(worktree==="")return null;let gitDir=gitDirOf(worktree);if(!gitDir)return null;let has=(name)=>existsSync2(join3(gitDir,name));if(has("rebase-merge")||has("rebase-apply")&&!has("rebase-apply/applying"))return"rebase";if(has("CHERRY_PICK_HEAD"))return"cherry-pick";if(has("REVERT_HEAD"))return"revert";if(has("MERGE_HEAD"))return"merge";return null}async function conflictedPaths(worktree){let controller=new AbortController,timer3=setTimeout(()=>controller.abort(),GIT_TIMEOUT_MS),args=["diff","--name-only","--diff-filter=U"];try{recordSpawn("tui.conflictPrompt",["git",...args],worktree);let out=await spawnCapture("git",args,{cwd:worktree,env:readOnlyGitProcessEnv(),signal:controller.signal});if(controller.signal.aborted||out.status!==0)return null;return out.stdout.split(`
74
74
  `).map((line)=>line.trim()).filter((line)=>line.length>0)}finally{clearTimeout(timer3)}}var CONTINUE_COMMAND={merge:"git commit --no-edit",rebase:"GIT_EDITOR=true git rebase --continue","cherry-pick":"GIT_EDITOR=true git cherry-pick --continue",revert:"GIT_EDITOR=true git revert --continue"};function filesSentence(files){if(files.length===0)return"Git reports no unmerged files left, so the conflicts may already be resolved but not yet committed.";return`The conflicted files are: