@sma1lboy/rove 0.9.281 → 0.9.282

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 (68) hide show
  1. package/dist/cli/{chunk-f23manyf.js → chunk-03a986ba.js} +1 -1
  2. package/dist/cli/{chunk-3m0ydze9.js → chunk-084a4eq5.js} +1 -1
  3. package/dist/cli/{chunk-kt5ngemc.js → chunk-0mr6cckm.js} +1 -1
  4. package/dist/cli/{chunk-6wt08a28.js → chunk-0ramhr3v.js} +1 -1
  5. package/dist/cli/{chunk-cx78tyg1.js → chunk-0ws6j7zf.js} +1 -1
  6. package/dist/cli/{chunk-twy9bfps.js → chunk-1k6expt9.js} +1 -1
  7. package/dist/cli/{chunk-7911jkq6.js → chunk-231mqmk5.js} +1 -1
  8. package/dist/cli/{chunk-v3ecphrz.js → chunk-3m6m1994.js} +1 -1
  9. package/dist/cli/{chunk-hmy01yg2.js → chunk-3xz0dmnc.js} +6 -5
  10. package/dist/cli/{chunk-a5xbsvx2.js → chunk-4d5xp2p0.js} +1 -1
  11. package/dist/cli/{chunk-vtay379p.js → chunk-4g463eqt.js} +1 -1
  12. package/dist/cli/{chunk-08mb3qss.js → chunk-55e3pt18.js} +1 -1
  13. package/dist/cli/{chunk-q6cwy6v5.js → chunk-5bnhecx3.js} +1 -1
  14. package/dist/cli/{chunk-ejfs22aq.js → chunk-5z02j1em.js} +1 -1
  15. package/dist/cli/{chunk-k2rmj0v3.js → chunk-6jj8perx.js} +2 -2
  16. package/dist/cli/{chunk-y2v1x23z.js → chunk-7r1wt7qp.js} +1 -1
  17. package/dist/cli/{chunk-nkgn0bqq.js → chunk-7zwehmay.js} +1 -1
  18. package/dist/cli/{chunk-cx8wnz54.js → chunk-8ccc9v77.js} +1 -1
  19. package/dist/cli/{chunk-c9ptxthj.js → chunk-8ew9sqwa.js} +1 -1
  20. package/dist/cli/{chunk-w3kvkax7.js → chunk-8kspedny.js} +1 -1
  21. package/dist/cli/{chunk-gzkes5bw.js → chunk-92hpkjkk.js} +1 -1
  22. package/dist/cli/{chunk-bbt217yd.js → chunk-97er67dc.js} +1 -1
  23. package/dist/cli/{chunk-j5y7hhc2.js → chunk-9q8wwfs1.js} +1 -1
  24. package/dist/cli/{chunk-cs410j8b.js → chunk-ae8dj2fd.js} +1 -1
  25. package/dist/cli/{chunk-9vwb9f7q.js → chunk-b4egks20.js} +1 -1
  26. package/dist/cli/{chunk-w6ft4djp.js → chunk-b64w1jh6.js} +1 -1
  27. package/dist/cli/{chunk-bm6qhcck.js → chunk-h0wp2ghf.js} +1 -1
  28. package/dist/cli/{chunk-q2nhmaq9.js → chunk-h81h0arp.js} +2 -2
  29. package/dist/cli/{chunk-3pgp6z3k.js → chunk-h8v2jzth.js} +1 -1
  30. package/dist/cli/{chunk-kp43j420.js → chunk-h9cjzh9j.js} +1 -1
  31. package/dist/cli/{chunk-ww0zctb7.js → chunk-jp354m6j.js} +1 -1
  32. package/dist/cli/{chunk-yn01fet6.js → chunk-jxqhq9va.js} +1 -1
  33. package/dist/cli/{chunk-03fv92ya.js → chunk-nb0be8dz.js} +1 -1
  34. package/dist/cli/{chunk-46qs744w.js → chunk-nbf3attz.js} +1 -1
  35. package/dist/cli/{chunk-k9xabf0t.js → chunk-nh4dd7q4.js} +1 -1
  36. package/dist/cli/{chunk-sqdmngys.js → chunk-pg48v2kc.js} +1 -1
  37. package/dist/cli/{chunk-01tghgf3.js → chunk-ph9m6y5j.js} +1 -1
  38. package/dist/cli/{chunk-14tevt5v.js → chunk-pm6j59da.js} +1 -1
  39. package/dist/cli/{chunk-3qj9yw5c.js → chunk-pv3c4vgt.js} +2 -2
  40. package/dist/cli/{chunk-0nkk13z9.js → chunk-q012n1t1.js} +1 -1
  41. package/dist/cli/{chunk-y07cp9mb.js → chunk-qkdc5tc7.js} +1 -1
  42. package/dist/cli/{chunk-4vkrv4eb.js → chunk-qx6d4bbb.js} +1 -1
  43. package/dist/cli/{chunk-ga82ras9.js → chunk-s5eat30g.js} +1 -1
  44. package/dist/cli/{chunk-xekk4k54.js → chunk-s7tbwn04.js} +1 -1
  45. package/dist/cli/{chunk-btxfcc77.js → chunk-swcfg2vb.js} +2 -2
  46. package/dist/cli/{chunk-xxz3np4w.js → chunk-swzdd5aj.js} +1 -1
  47. package/dist/cli/{chunk-vx44yxra.js → chunk-t2418v0z.js} +1 -1
  48. package/dist/cli/{chunk-b5fdqynx.js → chunk-tcdz7sx9.js} +1 -1
  49. package/dist/cli/{chunk-x119xqa6.js → chunk-tg4swhr1.js} +1 -1
  50. package/dist/cli/{chunk-jar50zcp.js → chunk-v5bn5fnd.js} +1 -1
  51. package/dist/cli/{chunk-5swmvt20.js → chunk-v8c4n8by.js} +1 -1
  52. package/dist/cli/{chunk-j2e7jgh8.js → chunk-vcj2x6ne.js} +1 -1
  53. package/dist/cli/{chunk-9qpea48c.js → chunk-w3f993d8.js} +2 -2
  54. package/dist/cli/{chunk-453qpfae.js → chunk-y8n6trr4.js} +1 -1
  55. package/dist/cli/{chunk-32y7f5dr.js → chunk-ydaj339x.js} +1 -1
  56. package/dist/cli/{chunk-tgv90744.js → chunk-yeq2pc68.js} +1 -1
  57. package/dist/cli/{chunk-hnxs5shy.js → chunk-z204mctb.js} +4 -4
  58. package/dist/cli/{chunk-1a57ejnh.js → chunk-za8pnw78.js} +1 -1
  59. package/dist/cli/{chunk-ap3fgbbt.js → chunk-zd61a32g.js} +1 -1
  60. package/dist/cli/{chunk-w8dmmnys.js → chunk-ze4v7eda.js} +1 -1
  61. package/dist/cli/{chunk-sm96b61g.js → chunk-zjsfr4y7.js} +1 -1
  62. package/dist/cli/{chunk-q72w3dsx.js → chunk-zypkjg5t.js} +1 -1
  63. package/dist/cli/index.js +2 -2
  64. package/dist/cli/rove.js +1 -1
  65. package/dist/web/assets/{index-Ct8dDnCc.js → index-Bpal5sTS.js} +31 -31
  66. package/dist/web/index.html +1 -1
  67. package/dist/web/relay/index.html +5 -5
  68. package/package.json +3 -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-twy9bfps.js";import{machineOfTask,useMachineRows,useMergedTasks}from"./chunk-stng29vp.js";import{trackWelcomeWrite}from"./chunk-14tevt5v.js";import{installSkillNow,skillMissing}from"./chunk-4yr1534j.js";import{fetchMarketplace}from"./chunk-grr2fn38.js";import"./chunk-c25vea1q.js";import{failureHint}from"./chunk-ejfs22aq.js";import{preparePluginInstall}from"./chunk-v3ecphrz.js";import{formatBytes}from"./chunk-my20q579.js";import"./chunk-p2cbtrzg.js";import{humanOnlyFix,noEngineFix}from"./chunk-4vkrv4eb.js";import{embeddedTerminalEnv}from"./chunk-7bgbansg.js";import{deriveTitleFromSessionId,startTaskSessionWithPromptAdapter}from"./chunk-w8dmmnys.js";import{buildCIPromptForWorktree}from"./chunk-vkz6kkmm.js";import{canonPath,checkResolutionNotify}from"./chunk-zr058kbe.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-0gbg7bg8.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-ap3fgbbt.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-bbq6wc47.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-3m0ydze9.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-32y7f5dr.js";import"./chunk-w3kvkax7.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-tgv90744.js";import{reloadPluginEngines}from"./chunk-kdnk8m5j.js";import{listPaneLaunches}from"./chunk-rjfdzjhj.js";import{detectEngineStatus,detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-zpxpwgds.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-01tghgf3.js";import{forwardVerb,requireMachine}from"./chunk-y07cp9mb.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-vx44yxra.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-gzkes5bw.js";import"./chunk-rxqdw6s5.js";import"./chunk-8ng1756g.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-1a57ejnh.js";import{AUTO_STATUS_KEY,DISPATCHER_KEY,repoEnv}from"./chunk-qecygh3f.js";import{ENGINE_PROTOCOLS,applyTabOps,defaultEngineCommand,diffTabs,engineCommandKey,engineDisplayName,engineLaunchArgv,engineNameKey,engineProtocolKey,engineRenamedFrom,humanizeSlug,interactiveEngineCommand,pickUnclaimedSessionId,protocolEntry,roveApiInvocation,withPinnedSessionId}from"./chunk-rjq38twt.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-5rgrde6b.js";import{createEngineHookAdapter,engineEntry,engineSessionIdFromTitle,engineTitleTurnHint,getCapabilities,stripEngineStatusPrefix}from"./chunk-4gjvmfa9.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-yn01fet6.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-a5xbsvx2.js";import{LOCALES}from"./chunk-9vwb9f7q.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{defaultDaemonLogPath,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-1k6expt9.js";import{machineOfTask,useMachineRows,useMergedTasks}from"./chunk-stng29vp.js";import{trackWelcomeWrite}from"./chunk-pm6j59da.js";import{installSkillNow,skillMissing}from"./chunk-4yr1534j.js";import{fetchMarketplace}from"./chunk-grr2fn38.js";import"./chunk-c25vea1q.js";import{failureHint}from"./chunk-5z02j1em.js";import{preparePluginInstall}from"./chunk-3m6m1994.js";import{formatBytes}from"./chunk-my20q579.js";import"./chunk-p2cbtrzg.js";import{humanOnlyFix,noEngineFix}from"./chunk-qx6d4bbb.js";import{embeddedTerminalEnv}from"./chunk-7bgbansg.js";import{deriveTitleFromSessionId,startTaskSessionWithPromptAdapter}from"./chunk-ze4v7eda.js";import{buildCIPromptForWorktree}from"./chunk-vkz6kkmm.js";import{canonPath,checkResolutionNotify}from"./chunk-zr058kbe.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-0gbg7bg8.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-zd61a32g.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-bbq6wc47.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-084a4eq5.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-ydaj339x.js";import"./chunk-8kspedny.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-yeq2pc68.js";import{reloadPluginEngines}from"./chunk-kdnk8m5j.js";import{listPaneLaunches}from"./chunk-rjfdzjhj.js";import{detectEngineStatus,detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-zpxpwgds.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-ph9m6y5j.js";import{forwardVerb,requireMachine}from"./chunk-qkdc5tc7.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-t2418v0z.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-92hpkjkk.js";import"./chunk-rxqdw6s5.js";import"./chunk-8ng1756g.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-za8pnw78.js";import{AUTO_STATUS_KEY,DISPATCHER_KEY,repoEnv}from"./chunk-qecygh3f.js";import{ENGINE_PROTOCOLS,applyTabOps,defaultEngineCommand,diffTabs,engineCommandKey,engineDisplayName,engineLaunchArgv,engineNameKey,engineProtocolKey,engineRenamedFrom,humanizeSlug,interactiveEngineCommand,pickUnclaimedSessionId,protocolEntry,roveApiInvocation,withPinnedSessionId}from"./chunk-rjq38twt.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-5rgrde6b.js";import{createEngineHookAdapter,engineEntry,engineSessionIdFromTitle,engineTitleTurnHint,getCapabilities,stripEngineStatusPrefix}from"./chunk-4gjvmfa9.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-jxqhq9va.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-4d5xp2p0.js";import{LOCALES}from"./chunk-b4egks20.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{defaultDaemonLogPath,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-ww0zctb7.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-jp354m6j.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,7 +61,7 @@ ${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_react135=__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-bm6qhcck.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-h0wp2ghf.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.
@@ -93,4 +93,4 @@ ${t("worktrees.delete.forceReason",{reason:reason.replace(`task ${taskId} `,"")}
93
93
  ${result.prompt}`}:result,{taskId:deps.taskId,branch:getCurrentBranch(deps.worktree)})};return{requestRename,requestNewChat:(preset={})=>{(async()=>{let tabVendor=(active.kind==="engine"?active.vendor:void 0)??deps.vendor,source=liveSourceProtocol(active,tabVendor),available=await availableEngineIds(),panes=[];try{panes=listPaneLaunches({socketPath:defaultDaemonSocketPath(),binPath:ROVE_PRODUCT_NAME,taskId:deps.taskId})}catch{}let choice=await NewChatDialog.show(dialog,available,preset.context==="continue"?tabVendor:deps.vendor,{allowShell:!0,allowScratch:deps.onOpenScratch!==void 0,extraChoices:panes.map((p3)=>({key:`pane:${p3.pluginId}.${p3.paneId}`,label:p3.title})),initialDestination:preset.destination,initialContext:preset.context});if(choice===void 0)return;if(choice.destination==="fork"){await forkChildTask(choice,source,available);return}if(choice.destination==="scratch"){deps.onOpenScratch?.(choice.pick==="shell"?void 0:choice.pick);return}let pane=panes.find((p3)=>`pane:${p3.pluginId}.${p3.paneId}`===choice.pick);if(pane){update(openPluginPane(state,pane.argv,pane.title,pane.placement,void 0,deps.activeLeafSize()));return}if(choice.pick==="shell"){newShell();return}await openTabHere(choice,tabVendor,source)})()},newConversation,newShell}}var import_react112=__toESM(require_react_production(),1);function resolveEnginePty(io){let{stateRef,propsRef,engineTabSpawnRef}=io,activeTab=stateRef.current.tabs.find((tab)=>tab.id===stateRef.current.activeId),target=activeTab?.kind==="engine"?activeTab:stateRef.current.tabs.find((t3)=>t3.kind==="engine");if(!target)return null;let reg=getDefaultPtyRegistry(),key=tabPtyKey(propsRef.current.taskId,target.id),pty=reg.get(key);if(!pty&&target.kind==="engine")try{pty=reg.acquire(key,propsRef.current.worktree,{...engineTabSpawnRef.current(target)})}catch{return null}if(!pty||pty.killed)return null;return pty}function buildEngineSend(io){return(text)=>{let pty=resolveEnginePty(io);if(!pty)return!1;return pty.paste(text),pty.write("\r"),!0}}function buildEnginePaste(io){return(text)=>{let pty=resolveEnginePty(io);if(!pty)return!1;return pty.paste(text),!0}}function useTabHandoffs(io){let{stateRef,propsRef,update}=io,sendToEngine=buildEngineSend(io),pasteToEngine=buildEnginePaste(io);return import_react112.useEffect(()=>{propsRef.current.onEditorTabReady?.((command,label)=>{let current2=stateRef.current,existing=findEditorTab(current2);if(existing){let key=tabPtyKey(propsRef.current.taskId,existing.id);releaseSplitLeaves(key,existing.splitTree??null),getDefaultPtyRegistry().release(key)}if(update(openEditorTab(current2,command,label)),existing?.id===current2.activeId)io.bumpResetToken()})},[]),import_react112.useEffect(()=>{propsRef.current.onDiffTabReady?.((relPath,label,base)=>{update(openContentTab(stateRef.current,relPath,label,base))})},[]),import_react112.useEffect(()=>{propsRef.current.onEngineSendReady?.(sendToEngine)},[]),import_react112.useEffect(()=>{propsRef.current.onEnginePasteReady?.(pasteToEngine)},[]),{sendToEngine,pasteToEngine}}async function sessionIds(vendor,worktree){if(!worktree)return[];try{return await protocolEntry(vendor).history.listSessionIdsForWorktree(worktree)}catch{return[]}}async function engineSessionExists(vendor,worktree,sessionId){if(!sessionId)return!1;return(await sessionIds(vendor,worktree)).includes(sessionId)}async function discoverSessionId(vendor,worktree,claimed){return pickUnclaimedSessionId(await sessionIds(vendor,worktree),claimed)}var import_react113=__toESM(require_react_production(),1);var NAMING_POLL_MS=5000;function claimedIds(io){return new Set(io.stateRef.current.tabs.flatMap((t3)=>t3.kind==="engine"&&t3.sessionId?[t3.sessionId]:[]))}function useTabHydration(rehydrated,io){let[hydrating,setHydrating]=import_react113.useState(rehydrated);return import_react113.useEffect(()=>{if(!rehydrated)return;let cancelled=!1;return(async()=>{try{let engines=io.stateRef.current.tabs.filter((tab)=>tab.kind==="engine"),worktree=io.propsRef.current.worktree,vendorOfTab=(tab)=>tab.vendor??io.propsRef.current.vendor;for(let tab of engines){let vendor=vendorOfTab(tab);if(tab.sessionId){let exists=await engineSessionExists(vendor,worktree,tab.sessionId);if(cancelled)return;if(io.update(setTabSpawned(io.stateRef.current,tab.id,exists)),exists||protocolEntry(vendor).sessionIdentity?.pinFlag)continue}let found=await discoverSessionId(vendor,worktree,claimedIds(io));if(cancelled)return;if(!found)continue;io.update(setTabSpawned(setTabSessionId(io.stateRef.current,tab.id,found),tab.id,!0))}}finally{if(!cancelled)setHydrating(!1)}})(),()=>{cancelled=!0}},[]),hydrating}function useTabNaming(io){import_react113.useEffect(()=>{let namingBusy=!1,cancelled=!1,vendorOf=(tab)=>tab.vendor??io.propsRef.current.vendor,namingSessionId=(tab)=>tab.sessionId??engineSessionIdFromTitle(vendorOf(tab),tab.lastTitle??""),timer3=setInterval(()=>{if(namingBusy)return;let undiscovered=io.stateRef.current.tabs.filter((tab)=>tab.kind==="engine"&&!namingSessionId(tab)),candidates=io.stateRef.current.tabs.filter((tab)=>tab.kind==="engine"&&!!namingSessionId(tab)&&(!tab.spawned||!tab.title&&!tab.autoTitle));if(candidates.length===0&&undiscovered.length===0)return;namingBusy=!0,(async()=>{try{for(let tab of undiscovered){let found=await discoverSessionId(vendorOf(tab),io.propsRef.current.worktree,claimedIds(io));if(cancelled)return;if(!found)continue;io.update(setTabSpawned(setTabSessionId(io.stateRef.current,tab.id,found),tab.id,!0))}for(let tab of candidates){let sessionId=namingSessionId(tab);if(!sessionId)continue;let title=await deriveTitleFromSessionId(vendorOf(tab),sessionId);if(cancelled)return;if(!title)continue;let next=setTabSpawned(io.stateRef.current,tab.id,!0);if(!tab.title&&!tab.autoTitle)next=setTabAutoTitle(next,tab.id,title);io.update(next)}}finally{namingBusy=!1}})()},NAMING_POLL_MS);return()=>{cancelled=!0,clearInterval(timer3)}},[])}var import_react114=__toESM(require_react_production(),1);function engineExitOf(tab,status,hook,retriedSince,engineRunning=!1){if(tab.kind!=="engine"||status?.reason!=="dead"||engineRunning)return null;if(retriedSince===status.since)return null;let code=hook?.detail?.exit?.code;return{code:typeof code==="number"?code:null}}function useEngineExit(io){let status=useTabRowStatus(io.taskId,io.tab.id),[retried,setRetried]=import_react114.useState(null),[,redraw]=import_react114.useState(0);import_react114.useEffect(()=>getDefaultLiveEngines().subscribe(()=>redraw((n2)=>n2+1)),[]);let key=tabPtyKeyFor(io.taskId,io.tab),view=engineExitOf(io.tab,status,io.hook,retried?.tabId===io.tab.id?retried.since:void 0,!!getDefaultLiveEngines().resolve(key));if(!view)return;return{code:view.code,onRetry:()=>{if(getDefaultLiveEngines().resolve(key)){redraw((n2)=>n2+1);return}if(status)setRetried({tabId:io.tab.id,since:status.since});io.retry()},onSettings:io.onOpenSettings?()=>io.onOpenSettings?.("engines"):void 0,onAnotherEngine:()=>io.requestNewChat(),onContinueInEngine:()=>io.requestNewChat({context:"continue"})}}var import_react115=__toESM(require_react_production(),1);function useUsageLimit(io){let status=useTabRowStatus(io.taskId,io.tab.id),[dismissed,setDismissed]=import_react115.useState(null);if(io.tab.kind!=="engine"||io.suppressed||status?.reason!=="rate_limited")return;if(dismissed?.tabId===io.tab.id&&dismissed.since===status.since)return;return{onContinueInEngine:()=>io.requestNewChat({context:"continue"}),onDismiss:()=>setDismissed({tabId:io.tab.id,since:status.since})}}function useTabNotices(io){let engineExit=useEngineExit(io),usageLimit=useUsageLimit({...io,suppressed:engineExit!==void 0});return{engineExit,usageLimit}}var import_react116=__toESM(require_react_production(),1);function useTabRequests(io){let{stateRef,propsRef,updateRef,tabCloseRef,activeLeafSizeRef,openNewConversationRef,openNewShellRef,continueInEngineRef}=io;import_react116.useEffect(()=>{let consume=()=>{let taskId=propsRef.current.taskId,tabId=takeTabActivation(taskId);if(tabId){let s2=stateRef.current;if(s2.activeId!==tabId&&s2.tabs.some((tab)=>tab.id===tabId))updateRef.current(selectTab(s2,tabId))}let open=takeTabOpen(taskId);if(open){let size=activeLeafSizeRef.current();updateRef.current(openPluginPane(stateRef.current,open.argv,open.title,open.placement,open.direction,size,open.tabId))}let paneClose=takePaneClose(taskId);if(paneClose){let prev=stateRef.current,{next,closedLeaves,closedTabIds}=closePluginPanes(prev,paneClose.title,paneClose.tabId);if(next!==prev)updateRef.current(next);for(let{tabId:id,leafId}of closedLeaves){let tab=prev.tabs.find((x2)=>x2.id===id);if(tab)getDefaultPtyRegistry().release(splitLeafPtyKey(tabPtyKeyFor(taskId,tab),leafId))}for(let id of closedTabIds)tabCloseRef.current.closeById(id)}let newTab=takeNewTab(taskId);if(newTab==="chat")openNewConversationRef.current();else if(newTab==="shell")openNewShellRef.current();else if(newTab==="continue")continueInEngineRef.current();let adopt=takeTabAdopt(taskId);if(adopt){let prev=stateRef.current,next=adoptTabs(prev,adopt);if(next!==prev)updateRef.current(next)}let move=takeTabMove(taskId);if(move){let prev=stateRef.current,next=moveTab(prev,move.tabId,move.delta);if(next!==prev)updateRef.current(next)}let rename=takeTabRename(taskId);if(rename){let prev=stateRef.current,next=setTabTitle(prev,rename.tabId,rename.title);if(next!==prev)updateRef.current(next)}let added=takeTabAdd(taskId);if(added){let prev=stateRef.current,next=absorbTab(prev,added);if(next!==prev)updateRef.current(next)}let closeId=takeTabClose(taskId);if(closeId)tabCloseRef.current.closeById(closeId)};return consume(),tabActivationListeners.add(consume),()=>{tabActivationListeners.delete(consume)}},[])}var import_react118=__toESM(require_react_production(),1);function tabStripMenuItems(tab,tabCount){let items=[{action:"rename",labelKey:"terminal.tab.menu.rename",bindingId:"chat.tab.rename"}];if(tab.kind==="engine")items.push({action:"continueEngine",labelKey:"terminal.tab.menu.continueEngine",bindingId:"chat.tab.fork"});if(tab.kind!=="content")items.push({action:"copyAddress",labelKey:"terminal.tab.menu.copyAddress"});if(tabCount>1)items.push({action:"closeOthers",labelKey:"terminal.tab.menu.closeOthers",danger:!0});return items.push({action:"close",labelKey:"terminal.tab.menu.close",bindingId:"chat.tab.close"}),items}function useTabStripMenu(deps){let t3=useT(),kv=useKV(),notif=useNotifications(),dialog=useDialog(),renderer=useRenderer(),anchor=import_react118.useRef(null),[openMenu,setMenu]=import_react118.useState(null),menu=openMenu?.tabId===deps.activeId&&deps.tabs.some((tab)=>tab.id===openMenu.tabId)?openMenu:null;if(openMenu&&!menu)setMenu(null);let[cursor,setCursor]=import_react118.useState(0),close=()=>setMenu(null),openForTab=(tabId,x2,y3)=>{let tab=deps.tabs.find((candidate)=>candidate.id===tabId);if(!tab)return;deps.select(tabId);let box=anchor.current;setMenu({tabId,items:tabStripMenuItems(tab,deps.tabs.length),x:x2-(box?.x??0),y:y3-(box?.y??0)}),setCursor(0)};useGlobalMouseDown2(menu!==null,close);let closeOthers=async(tabId)=>{let count=deps.tabs.length-1;if(count<1)return;if(await DialogConfirm.show(dialog,t3("terminal.tab.closeOthersTitle"),t3("terminal.tab.closeOthersBody",{count:String(count)}),t3("terminal.tab.closeOthersCancel"),t3("terminal.tab.closeOthersConfirm"),{danger:!0})!==!0)return;if(closeOtherTaskTabs(kv,deps.taskId,tabId)===0)notif.notify({kind:"error",taskId:deps.taskId,tabId,title:t3("terminal.tab.tabGone")})},copyAddress=async(tabId)=>{let text=tabAddress(deps.taskId,tabId),copied=await copyTextToSystemClipboard(text,(payload)=>renderer?.copyToClipboardOSC52(payload));notif.notify({kind:copied?"done":"error",taskId:deps.taskId,tabId,title:copied?t3("tasks.toast.copiedTab",{text}):t3("tasks.toast.copyFailed")})},fire=(action)=>{if(!menu||action===void 0)return;let tabId=menu.tabId;if(setMenu(null),action==="rename")deps.rename();else if(action==="continueEngine")deps.continueEngine();else if(action==="close")deps.closeActive();else if(action==="closeOthers")closeOthers(tabId);else copyAddress(tabId)},move=(delta)=>{let count=menu?.items.length??0;if(count>0)setCursor((prev)=>(prev+delta+count)%count)};useBindings(()=>({enabled:menu!==null,bindings:[{key:"up",cmd:()=>move(-1)},{key:"k",cmd:()=>move(-1)},{key:"down",cmd:()=>move(1)},{key:"j",cmd:()=>move(1)},{key:"return",cmd:()=>fire(menu?.items[cursor]?.action)},{key:"escape",cmd:close}]}));let overlay=menu?$jsx(ContextMenu2,{entries:menu.items.map((item)=>{let cap=item.bindingId?legendCap(item.bindingId):void 0;return{id:item.action,label:t3(item.labelKey),danger:item.danger,cap:cap?formatChord(cap):void 0}}),cursor,x:menu.x,y:menu.y,dims:{width:anchor.current?.width??0,height:anchor.current?.height??0},onPick:(id)=>fire(menu.items.find((item)=>item.action===id)?.action)}):null;return{anchorRef:(box)=>{anchor.current=box},openForTab,overlay}}var import_react120=__toESM(require_react_production(),1);var INTERRUPT_CONFIRM_MS=2500;function disagrees(obs){if(!obs.hookRunning||!obs.vendor||obs.rawTitle===void 0)return!1;return engineTitleTurnHint(obs.vendor,obs.rawTitle)==="rest"}class InterruptObserver{opts;pending=new Map;constructor(opts){this.opts=opts}observe(tabId,obs){if(disagrees(obs)){if(this.pending.has(tabId))return;let timer3=setTimeout(()=>{if(this.pending.delete(tabId),this.opts.confirm(tabId))this.opts.report(tabId)},this.opts.confirmMs??INTERRUPT_CONFIRM_MS);timer3.unref?.(),this.pending.set(tabId,timer3);return}this.disarm(tabId)}disarm(tabId){let timer3=this.pending.get(tabId);if(timer3===void 0)return;clearTimeout(timer3),this.pending.delete(tabId)}dispose(){for(let timer3 of this.pending.values())clearTimeout(timer3);this.pending.clear()}}function createTabIdentityObserver(){let observed=new Map;return(tab,live,shell)=>{let previous=observed.get(tab.id);if(live)observed.set(tab.id,live);else observed.delete(tab.id);return demoteExitedEngine(tab,previous,live,shell)}}function demoteExitedEngine(tab,prev,live,shell){if(tab.kind!=="engine"||live!==null||!prev)return tab;if(tab.ptyTask)return tab;return{kind:"command",command:shell,id:tab.id,title:tab.title,ordinal:tab.ordinal,...tab.autoTitle!==void 0?{autoTitle:tab.autoTitle}:{},...tab.splitTree!==void 0?{splitTree:tab.splitTree}:{},lastTitle:null,liveVendor:null}}function soloKey(taskId,tab){let tabKey=tabPtyKey(taskId,tab.id);if(!tab.splitTree)return tabKey;let ls=leaves(tab.splitTree.root);return ls.length===1?splitLeafPtyKey(tabKey,ls[0].id):null}function targetFor(taskId,tab,taskVendor,vendorOf){let key=soloKey(taskId,tab),pinned=tab.kind==="engine"&&hasEngineLeaf(tab.splitTree)?tab.vendor??taskVendor:null;if(!key)return pinned?{vendor:pinned,key:tabPtyKey(taskId,tab.id)}:null;let live=vendorOf(key);if(live)return{vendor:live,key};if(live===void 0&&pinned)return{vendor:pinned,key};return null}var import_react119=__toESM(require_react_production(),1);import{createHash}from"crypto";var TURN_STATUS_POLL_MS=1500;function nextTurnStatusPollDelay(currentMs,sessionMtimeAdvanced,published){if(sessionMtimeAdvanced)return 1500;if(published==="running")return 1500;return Math.min(currentMs*2,6000)}function sameSession(a2,b3){return a2?.id===b3?.id&&a2?.transcriptPath===b3?.transcriptPath}function startTurnStatusPoll(opts,io){let disposed=!1,primed=!1,session=null,baseline=null,paneHash="",changed=!1,stable=0,published=null,lastMtime=0,delay=TURN_STATUS_POLL_MS,timer3;async function publish3(state){if(disposed||state===published)return;published=state,await io.setTurnState(state)}function screenState(text){if(!opts.screenManifest)return"unknown";switch(classifyScreen(opts.screenManifest,text)){case"working":return"running";case"blocked":return"needs_input";case"idle":return"idle";default:return published===null||published==="needs_input"?"unknown":null}}async function poll(){try{if(!await io.sessionAttached()||disposed)return;let current2=opts.session(),text=await io.capturePane();if(disposed||!sameSession(current2,opts.session()))return;if(opts.screenManifest)await io.setScreenBlocked?.(classifyScreen(opts.screenManifest,text)==="blocked");let markerMode=opts.detector.supportsCompletionMarkers()&&current2!==null,scan=markerMode?await opts.detector.latestActivityInFile(current2.transcriptPath):null;if(disposed||!sameSession(current2,opts.session()))return;let hash=createHash("sha1").update(text).digest("hex");if(!primed||!sameSession(session,current2)){session=current2,baseline=scan?.marker?.id??null,paneHash=hash,changed=!1,stable=0,lastMtime=scan?.mtimeMs??0,primed=!0,published=null,await publish3(markerMode?scan?"idle":"unknown":screenState(text)??"unknown"),delay=TURN_STATUS_POLL_MS;return}if(hash!==paneHash){if(paneHash=hash,changed=!0,stable=0,markerMode)await publish3("running")}else if(changed)stable++;if(!markerMode){let state=screenState(text);if(state!==null)await publish3(state)}else if(scan&&changed&&stable>=2&&scan.marker&&scan.marker.id!==baseline)baseline=scan.marker.id,changed=!1,stable=0,await publish3("done");let mtime=scan?.mtimeMs??0;delay=nextTurnStatusPollDelay(delay,mtime>lastMtime,published),lastMtime=mtime}catch{delay=TURN_STATUS_POLL_MS}finally{if(!disposed)timer3=setTimeout(()=>void poll(),delay)}}return poll(),()=>{if(disposed=!0,opts.screenManifest)io.setScreenBlocked?.(!1).catch(()=>{});if(timer3)clearTimeout(timer3)}}var TURN_POLL_ATTACH_MS=2000;function useTurnPolls(deps){let[liveTitles,setLiveTitles]=import_react119.useState(new Map),[rawTitles,setRawTitles]=import_react119.useState(new Map),[turnVendors,setTurnVendors]=import_react119.useState(new Map),turnPollsRef=import_react119.useRef(new Map),titleStoreRef=import_react119.useRef(null);if(titleStoreRef.current===null)titleStoreRef.current=createTitleSubscriptions();let hookTabStatesRef=useLatest(deps.hookTabStates),screenInputRef=useLatest(deps.onScreenInput),stateRef=useLatest(deps.state),taskIdRef=useLatest(deps.taskId),vendorRef=useLatest(deps.vendor),reconcile=import_react119.useCallback(()=>{let reg=getDefaultPtyRegistry(),attached=new Set,turnPolls=turnPollsRef.current,titleStore=titleStoreRef.current,liveEngines=getDefaultLiveEngines();if(!titleStore)return;let taskId=taskIdRef.current,state=stateRef.current,soloKeys=new Map;for(let tab of state.tabs){let key=soloKey(taskId,tab);if(key)soloKeys.set(key,tab.id)}titleStore.reconcile(soloKeys.keys()),setRawTitles((prev)=>{let next=new Map;for(let[key,tabId]of soloKeys){let title=titleStore.get(key);if(title!==void 0)next.set(tabId,title)}if(next.size===prev.size&&[...next].every(([id,v3])=>prev.get(id)===v3))return prev;return next}),setLiveTitles((prev)=>{let next=new Map;for(let[key,tabId]of soloKeys){let title=titleStore.get(key);if(title===void 0)continue;next.set(tabId,stripEngineStatusPrefix(title,liveEngines.resolve(key)))}if(next.size===prev.size&&[...next].every(([id,v3])=>prev.get(id)===v3))return prev;return next});for(let tab of state.tabs){let target=targetFor(taskId,tab,vendorRef.current,(key)=>liveEngines.resolve(key));if(!target)continue;let existing=turnPolls.get(tab.id);if(existing&&existing.vendor===target.vendor&&existing.key===target.key){attached.add(tab.id);continue}if(existing)existing.dispose(),turnPolls.delete(tab.id);if(!reg.has(target.key))continue;let tabId=tab.id,entry2=engineEntry(target.vendor);if(!entry2.screenManifest){turnPolls.set(tabId,{dispose:()=>{},vendor:target.vendor,key:target.key}),attached.add(tabId);continue}let screenManifest=entry2.screenManifest,detector=entry2.createTurnDetector(),dispose=startTurnStatusPoll({detector,screenManifest,session:()=>{let state2=hookTabStatesRef.current?.get(tabId);return state2?.sessionId&&state2.transcriptPath?{id:state2.sessionId,transcriptPath:state2.transcriptPath}:null}},{setScreenBlocked:(blocked)=>screenInputRef.current?.(tabId,blocked)??Promise.resolve(),sessionAttached:async()=>!0,capturePane:async()=>{let pty=getDefaultPtyRegistry().get(target.key);if(!pty)throw Error("pty gone");return pty.capture().map((row)=>row.map((chunk)=>chunk.text).join("")).join(`
94
94
  `)},setTurnState:async()=>{}});turnPolls.set(tabId,{dispose,vendor:target.vendor,key:target.key}),attached.add(tabId)}for(let[id,poll]of turnPolls){if(attached.has(id))continue;poll.dispose(),turnPolls.delete(id)}setTurnVendors((prev)=>{let next=new Map;for(let[id,poll]of turnPolls)next.set(id,poll.vendor);if(next.size===prev.size&&[...next].every(([id,v3])=>prev.get(id)===v3))return prev;return next})},[]);return import_react119.useEffect(()=>{let active=!0,scheduled=!1,unsub=titleStoreRef.current?.subscribe(()=>{if(scheduled)return;scheduled=!0,queueMicrotask(()=>{if(scheduled=!1,active)reconcile()})});return()=>{active=!1,unsub?.()}},[reconcile]),import_react119.useEffect(()=>{return getDefaultLiveEngines().subscribe(reconcile)},[reconcile]),import_react119.useEffect(()=>{let timer3=setInterval(reconcile,TURN_POLL_ATTACH_MS);return()=>clearInterval(timer3)},[reconcile]),import_react119.useEffect(()=>{deps.taskId,deps.worktree,deps.vendor,deps.state,reconcile()},[deps.taskId,deps.worktree,deps.vendor,deps.state,reconcile]),import_react119.useEffect(()=>{return()=>{for(let poll of turnPollsRef.current.values())poll.dispose();titleStoreRef.current?.dispose()}},[]),{liveTitles,rawTitles,turnVendors}}function useTabTurnState(deps){let{liveTitles,rawTitles,turnVendors}=useTurnPolls(deps),tabStatuses=useRowStatusMap()[deps.taskId]?.tabs,turnStates=import_react120.useMemo(()=>notifyTurns(tabStatuses),[tabStatuses]),hookStatesRef=useLatest(deps.hookTabStates),onInterruptRef=useLatest(deps.onEngineInterrupt),observerRef=import_react120.useRef(null);if(observerRef.current===null)observerRef.current=new InterruptObserver({confirm:(tabId)=>hookStatesRef.current?.get(tabId)?.state==="running",report:(tabId)=>onInterruptRef.current?.(tabId)});import_react120.useEffect(()=>{let observer=observerRef.current;if(!observer)return;let running=new Set;for(let[tabId,entry2]of deps.hookTabStates??[])if(entry2.state==="running")running.add(tabId);let tabIds=new Set([...running,...rawTitles.keys()]);for(let tabId of tabIds)observer.observe(tabId,{rawTitle:rawTitles.get(tabId),vendor:turnVendors.get(tabId),hookRunning:running.has(tabId)})},[deps.hookTabStates,rawTitles,turnVendors]),import_react120.useEffect(()=>()=>observerRef.current?.dispose(),[]);let updateRef=useLatest(deps.update),titleStateRef=useLatest(deps.state),identityObserver=import_react120.useRef(null);if(!identityObserver.current)identityObserver.current=createTabIdentityObserver();import_react120.useEffect(()=>{let apply=updateRef.current;if(!apply)return;let engines=getDefaultLiveEngines(),record=()=>{let current2=titleStateRef.current,next=current2;for(let[tabId,title]of liveTitles){let tab=next.tabs.find((t3)=>t3.id===tabId);if(!tab)continue;let key=soloKey(deps.taskId,tab),live=key?engines.resolve(key):void 0,demoted=identityObserver.current?.(tab,live,[defaultShell()]);if(demoted&&demoted!==tab){next={...next,tabs:next.tabs.map((t3)=>t3.id===tabId?demoted:t3)};continue}if(next=setTabLastTitle(next,tabId,title),live!==void 0)next=setTabLiveVendor(next,tabId,live)}if(next!==current2)apply(next)};return record(),engines.subscribe(record)},[liveTitles,deps.taskId]);let prevRef=import_react120.useRef(null),stateRef=useLatest(deps.state),notifRef=useLatest(deps.notif),vendorRef=useLatest(deps.vendor),taskIdRef=useLatest(deps.taskId),taskTitleRef=useLatest(deps.taskTitle),dispatchedRef=useLatest(deps.taskDispatched);return import_react120.useEffect(()=>{if(turnStates===null)return;let next=turnStates,edges=attentionEdges(prevRef.current,next,stateRef.current.activeId,chipAttentionKind);prevRef.current=next;for(let{key:tabId,kind}of edges){let tab=stateRef.current.tabs.find((tb)=>tb.id===tabId);if(!tab)continue;notifRef.current.notify({kind,taskId:taskIdRef.current,tabId,title:tabTitle(tab,vendorRef.current),body:taskTitleRef.current,silent:dispatchedRef.current,turnEnd:!0})}},[turnStates]),{liveTitles,turnVendors}}function notifyTurns(tabs){if(tabs===void 0)return null;let out=new Map;for(let[tabId,status]of Object.entries(tabs))switch(status.kind){case"unseen":out.set(tabId,"done");break;case"needs-input":out.set(tabId,"needs_input");break;case"attention":out.set(tabId,status.reason??"error");break;default:out.set(tabId,status.kind)}return out}function TerminalTabs(props){let{theme}=useTheme(),dialog=useDialog(),notif=useNotifications(),kv=useKV(),t3=useT(),persistKey=terminalTabsKey(props.taskId),propsRef=useLatest(props),pinSession=(s2,vendor)=>{let base=vendor?engineLaunchArgv({vendor,effort:props.modelEffort}):props.command,{sessionId}=withPinnedSessionId(base,vendor??props.vendor);return setTabSessionId(s2,s2.activeId,sessionId)},rehydratedRef=import_react121.useRef(!1),initState=()=>{let saved=tabsByTask.get(props.taskId)??taskTabsView(props.taskId)??(tabsLoaded()?null:kv.get(persistKey,null)),fromDaemon=saved&&Array.isArray(saved.tabs)?rehydrateTabs(saved,[defaultShell()]):null;if(rehydratedRef.current=fromDaemon!==null,fromDaemon)return fromDaemon;return props.scratch===!0&&!engineScratchTasks.delete(props.taskId)?initialShellTabs(defaultShell()):pinSession(initialTabs(),void 0)},[state,setState]=import_react121.useState(initState),stateRef=useLatest(state),update=(next)=>{reportTabsDelta(propsRef.current.taskId,stateRef.current.tabs,next.tabs);let shown=setTaskTabs2(propsRef.current.taskId,next,stateRef.current);stateRef.current=shown,setState(shown)};import_react121.useEffect(()=>{let taskId=props.taskId;if(!tabsByTask.has(taskId)){let shown=setTaskTabs2(taskId,stateRef.current);stateRef.current=shown,setState(shown)}ensureTabReservation(taskId);let off=tabsRevision.subscribe(()=>{let live=tabsByTask.get(taskId);if(!live||live===stateRef.current)return;stateRef.current=live,setState(live)});return()=>{off(),releaseTabReservation(taskId)}},[props.taskId]);let updateRef=useLatest(update),activeLeafSize=()=>activeLeafCells(stateRef.current,propsRef.current.taskId),activeLeafSizeRef=useLatest(activeLeafSize),engineTabSpawn=(tab)=>{let base=tab.engineCommand||tab.vendor?engineLaunchArgv({command:tab.engineCommand,vendor:tab.vendor,effort:props.modelEffort}):props.command,live=getDefaultPtyRegistry().has(tabPtyKeyFor(props.taskId,tab));return engineTabSpawnFor(stateRef.current,tab,base,{live,shell:defaultShell(),prompt:propsRef.current.initialPrompt,task:{id:props.taskId,kind:props.taskKind,vendor:tab.vendor??props.vendor,repo:props.repo,repos:props.repos},worktreePath:props.worktree,inlineImages:terminalDrawsKitty()})},engineTabSpawnRef=useLatest(engineTabSpawn),[resetToken,setResetToken]=import_react121.useState(0),hydrating=useTabHydration(rehydratedRef.current,{stateRef,propsRef,update}),{sendToEngine}=useTabHandoffs({stateRef,propsRef,update,engineTabSpawnRef,bumpResetToken:()=>setResetToken((n2)=>n2+1)});import_react121.useEffect(()=>{warmHostedShell(props.worktree)},[props.worktree]);let active=state.tabs.find((tab)=>tab.id===state.activeId)??state.tabs[0];useTabNaming({stateRef,propsRef,update});let{liveTitles,turnVendors}=useTabTurnState({taskId:props.taskId,worktree:props.worktree,vendor:props.vendor,state,hookTabStates:props.hookTabStates,taskTitle:props.taskTitle,taskDispatched:props.taskDispatched,notif,update,onEngineInterrupt:props.onEngineInterrupt,onScreenInput:props.onScreenInput});import_react121.useEffect(()=>{notif.markRead(props.taskId,state.activeId),propsRef.current.onTabVisited?.(state.activeId)},[state.activeId]);let activeSpawn=()=>active.kind==="command"?{command:active.command,...active.purpose!=="editor"&&active.command.length===1&&active.command[0]===defaultShell()?{initialInput:shellIdentityInput(props.taskId,active.id,props.repos&&repoEnv(props.repos))}:{}}:active.kind==="content"?{command:[]}:engineTabSpawn(active),resumeTriedRef=import_react121.useRef(new Set),tabClose=useTabClose({stateRef,propsRef,updateRef,active,pinSession,bumpResetToken:()=>setResetToken((n2)=>n2+1),resumeTriedRef,notifyCannotCloseLast:(tabId)=>notif.notify({kind:"error",taskId:props.taskId,tabId,title:t3("terminal.tab.cannotCloseLast")}),onScratchExit:props.scratch===!0?props.onScratchExit:void 0}),tabCloseRef=useLatest(tabClose),engineDeadRef=import_react121.useRef(!1),{requestRename,requestNewChat,newConversation,newShell}=useTabDialogs({dialog,t:t3,state,active,vendor:props.vendor,taskId:props.taskId,taskTitle:props.taskTitle,worktree:props.worktree,liveTitles,update,pinSession,activeLeafSize,onChooseEngine:props.onChooseEngine,onSpawnChild:remoteOf(props.taskId)?void 0:props.onSpawnChild,onQuickFork:props.onQuickFork,onOpenScratch:props.onOpenScratch,notifyError:(title)=>notif.notify({kind:"error",taskId:props.taskId,tabId:active.id,title}),sourceDead:()=>engineDeadRef.current,restartActive:tabClose.retryActive}),{engineExit,usageLimit}=useTabNotices({taskId:props.taskId,tab:active,hook:props.hookTabStates?.get(active.id),retry:tabClose.retryActive,requestNewChat,onOpenSettings:props.onOpenSettings});engineDeadRef.current=engineExit!==void 0;let openNewConversation=()=>{let vendor=props.vendor;try{vendor=resolvePreferredVendor(resolveMainRepoRoot(props.worktree))}catch{}return newConversation(vendor)},openNewConversationRef=useLatest(openNewConversation),openNewShellRef=useLatest(newShell),continueInEngineRef=useLatest(()=>requestNewChat({context:"continue"}));useTabRequests({stateRef,propsRef,updateRef,tabCloseRef,activeLeafSizeRef,openNewConversationRef,openNewShellRef,continueInEngineRef}),useBindings(()=>({enabled:props.focused,bindings:bindByIds({"chat.tab.new":prefixAction(()=>{if(!openNewConversation())return;showSharedFilesHint(kv,(title,body)=>notif.notify({kind:"done",silent:!0,taskId:props.taskId,tabId:active.id,title,body}),t3)}),"chat.tab.chooseEngine":prefixAction(()=>requestNewChat()),"chat.tab.fork":prefixAction(()=>requestNewChat({context:"continue"})),"chat.tab.cycle-next":prefixAction(()=>update(cycleTab(state,1))),"chat.tab.cycle-prev":prefixAction(()=>update(cycleTab(state,-1))),"chat.tab.goto":(_evt,slot)=>update(gotoTab(state,slot??0)),"chat.fork.new":prefixAction(()=>requestNewChat({destination:"fork"}))})}));let activeIsSplit=isTabSplit(active.splitTree),spawn3=activeSpawn();useBindings(()=>({enabled:props.focused&&!activeIsSplit,bindings:bindByIds({"chat.tab.close":prefixAction(()=>tabClose.closeActive()),"chat.tab.rename":prefixAction(requestRename)})}));let tabMenu=useTabStripMenu({taskId:props.taskId,tabs:state.tabs,activeId:state.activeId,select:(tabId)=>update(selectTab(stateRef.current,tabId)),rename:requestRename,continueEngine:()=>requestNewChat({context:"continue"}),closeActive:()=>tabClose.closeActive()});return $jsxs("box",{ref:tabMenu.anchorRef,flexDirection:"column",flexGrow:1,children:[$jsx(TabStrip,{taskId:props.taskId,tabs:state.tabs,activeId:state.activeId,onSelect:(tabId)=>update(selectTab(state,tabId)),onContextMenu:tabMenu.openForTab,vendor:props.vendor,liveTitles,turnVendors}),active.kind==="engine"?$jsx(EngineHookReadiness,{vendor:active.vendor??props.vendor,hookSessionId:props.hookTabStates?.get(active.id)?.sessionId},active.id):null,hydrating?$jsx("box",{flexGrow:1,paddingLeft:1,paddingTop:1,children:$jsx("text",{fg:theme.textMuted,children:t3("terminal.restoring")})}):active.kind==="content"?$jsx(PreviewScreen,{worktree:props.worktree,relPath:active.relPath,base:active.base,remote:remoteOf(props.taskId),focused:props.focused,onClose:()=>tabClose.closeExited(active.id),review:buildDiffReview(kv,props.taskId,sendToEngine)}):$jsx(TerminalSplit,{tabKey:tabPtyKeyFor(props.taskId,active),cwd:tabCwdFor(active,props.worktree),command:spawn3.command,initialInput:spawn3.initialInput,firstMessage:spawn3.firstMessage,engineBin:spawn3.engineBin,terminalPresentation:active.kind==="engine"?getCapabilities(active.vendor??props.vendor)?.terminalPresentation:void 0,onUserInput:active.kind==="engine"?(data)=>noteAnswerInput(data,props.taskId,active.id):void 0,splitTree:active.splitTree??null,engineExit,usageLimit,onSplitChange:(next)=>update(setTabSplit(state,active.id,next)),onExit:tabClose.handleActiveExit,resetToken,focused:props.focused,onRequestFocus:props.onRequestFocus,engineTitle:active.title??active.autoTitle??null}),tabMenu.overlay]})}function remoteOf(taskId){let machine=machineOfTask(taskId);return machine?{machine,taskId}:void 0}var import_react122=__toESM(require_react_production(),1);function EmptyWorkspacePane(props){let{theme}=useTheme(),t3=useT(),kv=useOptionalKV(),dialog=useDialog(),vendor=props.vendor??DEFAULT_TASK_VENDOR,reopen=()=>{reviveEmptiedTabs(kv,props.taskId,defaultShell(),knownTabsState(kv,props.taskId)?void 0:{vendor,engineCommand:props.command??vendor})},chooseEngine=()=>{(async()=>{let choice=await NewChatDialog.show(dialog,await availableEngineIds(),vendor,{freshTabOnly:!0});if(!choice)return;reviveEmptiedTabs(kv,props.taskId,defaultShell(),{vendor:choice.pick,engineCommand:choice.pick})})()},startRequestedTab=useLatest((kind)=>{if(kind!=="shell")chooseEngine();else if(props.onSpawnChild)props.onSpawnChild({parentTaskId:props.taskId,vendor,title:SHELL_TASK_TITLE,tabs:initialShellTabs(defaultShell())});else{let empty=knownTabsState(kv,props.taskId)??{tabs:[],activeId:"",nextOrdinal:1};setTaskTabs2(props.taskId,openCommandTab(empty,[defaultShell()],null))}});import_react122.useEffect(()=>{let consume=()=>{let kind=takeNewTab(props.taskId);if(kind)startRequestedTab.current(kind)};return consume(),tabActivationListeners.add(consume),()=>{tabActivationListeners.delete(consume)}},[props.taskId]),useBindings(()=>({enabled:props.focused,bindings:bindByIds({"workspace.reopenSession":reopen,"chat.tab.chooseEngine":chooseEngine})}));let reopensShell=knownTabsState(kv,props.taskId)?.reopenAs?.kind==="command";return $jsx("box",{flexGrow:1,alignItems:"center",justifyContent:"center",children:$jsx("text",{fg:theme.info,onMouseUp:(event)=>{if(event.button===0)reopen()},children:reopensShell?t3("workspace.empty.noSessionsShell"):t3("workspace.empty.noSessions",{engine:engineDisplayName(vendor)})})})}var import_react123=__toESM(require_react_production(),1);var POLL_MS4=2000;async function verbOn(machine,verb,params){let envelope=await forwardVerb(requireMachine(machine),verb,params);if(!envelope.ok)throw Error(envelope.error.message);return envelope.result}function sessionKey(taskId,tab){return tab.viewOf?`${tab.viewOf}::tab-1`:`${taskId}::${tab.id}`}function tabLabel(tab){return tab.title??tab.autoTitle??tab.lastTitle??tab.liveVendor??tab.vendor??tab.id}function RemoteTerminalTabs(props){let{theme}=useTheme(),t3=useT(),[tabs,setTabs]=import_react123.useState(null),[activeId,setActiveId]=import_react123.useState(null),[error,setError]=import_react123.useState(null),[tick3,setTick]=import_react123.useState(0);import_react123.useEffect(()=>{let live=!0,load=()=>verbOn(props.machine,"get-task",{"task-id":props.taskId}).then((res)=>{if(!live)return;let rows=(res.tabs??[]).filter((tab)=>tab.kind!=="content");setTabs(rows),setError(null),setActiveId((cur)=>cur&&rows.some((tab)=>tab.id===cur)?cur:rows[0]?.id??null)},(err)=>live&&setError(err instanceof Error?err.message:String(err)));load();let timer3=setInterval(load,POLL_MS4);return()=>{live=!1,clearInterval(timer3)}},[props.machine,props.taskId,tick3]);let refresh=()=>setTick((n2)=>n2+1),list=tabs??[],index=Math.max(0,list.findIndex((tab)=>tab.id===activeId)),active=list[index]??null,step=(dir)=>{if(list.length===0)return;setActiveId(list[(index+dir+list.length)%list.length]?.id??null)},run=(verb,params)=>void verbOn(props.machine,verb,{"task-id":props.taskId,...params}).then((res)=>{if(res?.tabId)setActiveId(res.tabId);refresh()}).catch((err)=>setError(err instanceof Error?err.message:String(err)));return useBindings(()=>({enabled:props.focused,bindings:bindByIds({"chat.tab.new":prefixAction(()=>run("tab-new",{kind:"engine"})),"chat.tab.cycle-next":prefixAction(()=>step(1)),"chat.tab.cycle-prev":prefixAction(()=>step(-1)),"chat.tab.goto":(_evt,slot)=>setActiveId(list[slot??0]?.id??activeId),"chat.tab.close":prefixAction(()=>active&&run("tab-close",{tab:active.id}))})})),$jsxs("box",{flexDirection:"column",flexGrow:1,children:[$jsxs("box",{flexDirection:"row",gap:2,paddingLeft:1,flexShrink:0,children:[$jsx("text",{fg:theme.textMuted,children:t3("tasks.machine.runsOn",{host:props.host})}),list.map((tab,i2)=>$jsx("text",{fg:tab.id===active?.id?theme.focusAccent:theme.textMuted,children:`${i2+1} ${tabLabel(tab)}${tab.alive===!1?" \u2715":""}`},tab.id))]}),error?$jsx("text",{fg:theme.textMuted,paddingLeft:1,children:error}):null,tabs===null?$jsx("text",{fg:theme.textMuted,paddingLeft:1,children:t3("terminal.restoring")}):active?$jsx(Terminal,{taskId:sessionKey(props.taskId,active),machine:props.machine,cwd:props.worktree,command:[],focused:props.focused},sessionKey(props.taskId,active)):$jsx("text",{fg:theme.textMuted,paddingLeft:1,children:t3("tasks.machine.noTabs",{host:props.host})})]})}function ShowWorkspace(props){let{theme}=useTheme(),t3=useT(),kv=useOptionalKV();useAccessor(tabsRevision);let engineTabStates=useAccessor(props.orchestrator.engineTabStatesSignal()),tasks2=useAccessor(props.orchestrator.tasksSignal()),viewingTaskId=props.worktree&&props.task&&(props.task.origin?.machineId??"local")==="local"&&props.task?String(props.task.id):null;if(useViewingReport(viewingTaskId,viewingTaskId?knownTaskTabs(kv,viewingTaskId)?.activeId??null:null),!props.worktree){if(!tasks2.some((task)=>!task.deletion))return $jsx(WelcomePane,{onQuickTask:props.onQuickFork});return $jsx("box",{flexGrow:1,alignItems:"center",justifyContent:"center",children:$jsx("text",{fg:theme.textMuted,children:t3("workspace.empty.selectTask")})})}let path=props.task?taskCwd({worktreePath:props.worktree,cwdSubpath:props.task.cwdSubpath}):props.worktree,remoteKey=remoteKeyForRepo(props.task?.repo)??remoteKeyForRepo(path);if(remoteKey)return $jsx("box",{flexGrow:1,alignItems:"center",justifyContent:"center",children:$jsx("text",{fg:theme.textMuted,children:t3("workspace.empty.remoteUnsupported",{host:remoteKey})})});let origin=props.task?.origin&&props.task.origin.machineId!=="local"?props.task.origin:null;if(origin&&props.task){if(origin.stale)return $jsx("box",{flexGrow:1,alignItems:"center",justifyContent:"center",children:$jsx("text",{fg:theme.textMuted,children:t3("tasks.machine.terminalElsewhere",{host:origin.hostLabel})})});return $jsx(RemoteTerminalTabs,{taskId:String(props.task.id),machine:origin.machineId,host:origin.hostLabel,worktree:path??"",focused:props.focused})}let known=props.task?knownTaskTabs(kv,String(props.task.id)):null;if(props.task&&(known?known.tabs.length===0:!props.task.scratch&&(props.task.kind==="main"||props.task.kind==="dir")))return $jsx(EmptyWorkspacePane,{taskId:String(props.task.id),focused:props.focused,vendor:props.task.vendor,command:props.task.command,onSpawnChild:props.onSpawnChild});let taskReposView=props.task?taskRepos(props.task,tasks2):void 0,taskReposIfMulti=taskReposView&&taskReposView.length>1?taskReposView:void 0;return $jsx(TerminalTabs,{repos:taskReposIfMulti,taskId:props.task?.id??path,worktree:path,repo:props.task?.repo,taskKind:props.task?.kind,scratch:props.task?.scratch===!0,onScratchExit:()=>{let taskId=props.task?.id;if(taskId)props.onScratchExit?.(taskId)},onOpenScratch:props.onOpenScratch,command:engineLaunchArgv({command:props.task?.command,vendor:props.task?.vendor,effort:props.task?.modelEffort,model:props.task?.model}),vendor:props.task?.vendor??DEFAULT_TASK_VENDOR,modelEffort:props.task?.modelEffort,onChooseEngine:props.task?(vendor)=>{let taskId=props.task?.id;if(!taskId)return;props.onEngineChosen?.(taskId,vendor)}:void 0,focused:props.focused,onRequestFocus:props.onRequestFocus,onEditorTabReady:props.onEditorTabReady,onEngineSendReady:props.onEngineSendReady,onEnginePasteReady:props.onEnginePasteReady,onDiffTabReady:props.onDiffTabReady,onSpawnChild:props.onSpawnChild,onOpenSettings:props.onOpenSettings,onQuickFork:props.onQuickFork,initialPrompt:props.initialPrompt,hookTabStates:props.task?engineTabStates.get(props.task.id):void 0,taskTitle:props.task?.title,taskDispatched:props.task?.dispatcher!==void 0,onTabVisited:(tabId)=>{let taskId=props.task?.id;if(taskId)props.onTabVisited?.(taskId,tabId)},onScreenInput:async(tabId,blocked)=>{if(props.task)await props.orchestrator.reportScreenInput(props.task.id,tabId,blocked)},onEngineInterrupt:(tabId)=>{let taskId=props.task?.id;if(taskId)props.orchestrator.reportEngineInterrupt(taskId,tabId)}},props.task?.id??path)}var import_react124=__toESM(require_react_production(),1),DOUBLE_CLICK_MS=400;function useSidebarResizeGesture(opts){let armed=import_react124.useRef(null),lastRelease=import_react124.useRef(0);return{onGripDown:(event)=>{armed.current={x:event.x,width:opts.width,moved:!1}},onPaneDrag:(event)=>{let from=armed.current;if(from==null)return;let delta=event.x-from.x;if(delta===0)return;from.moved=!0,opts.onResize(from.width+delta)},onPaneRelease:()=>{let from=armed.current;if(from==null)return;if(armed.current=null,from.moved){lastRelease.current=0;return}let now=Date.now();if(now-lastRelease.current<DOUBLE_CLICK_MS){lastRelease.current=0,opts.onReset();return}lastRelease.current=now}}}function SidebarResizeGrip(props){return $jsx("box",{position:"absolute",top:0,bottom:0,left:props.width-1,width:1,onMouseDown:props.onGripDown})}var import_react125=__toESM(require_react_production(),1);function isVisit(value){if(typeof value!=="object"||value===null)return!1;let candidate=value;return typeof candidate.taskId==="string"&&(candidate.tabId===null||typeof candidate.tabId==="string")&&typeof candidate.at==="number"}function parseInboxVisits(stored){if(!Array.isArray(stored))return[];return stored.filter(isVisit).slice(0,60)}function inboxVisitKey(visit){return`${visit.taskId}\x00${visit.tabId??""}`}function recordInboxVisit(visits,visit,limit=60){let key=inboxVisitKey(visit),rest=visits.filter((entry2)=>inboxVisitKey(entry2)!==key);return[visit,...rest].slice(0,limit)}function inboxVisitIndex(visits){let byTarget=new Map;for(let visit of visits){let key=inboxVisitKey(visit);if(!byTarget.has(key))byTarget.set(key,visit)}return byTarget}function readInboxVisits(kv){return parseInboxVisits(kv.get("inboxVisits"))}function writeInboxVisit(kv,visit){let visits=readInboxVisits(kv),[previous]=visits;if(previous?.taskId===visit.taskId&&previous.tabId===visit.tabId)return;kv.setQuiet("inboxVisits",recordInboxVisit(visits,visit))}var attentionInboxKey=attentionInboxItemKey;function attentionInboxCounts(items){return{total:items.length}}function visitResolvedEpisodes(items,visit){return items.filter((item)=>item.state!=="decision_needed"&&item.state!=="report_missing"&&item.taskId===visit.taskId&&(item.tabId===null||item.tabId===visit.tabId))}function isAttentionInboxItemAvailable(item,task,hasTab){if(isRoutineInboxState(item.state))return!0;if(item.state==="decision_needed")return!0;if(item.state==="report_missing")return item.taskId!==null&&task!==void 0&&!task.deletion;if(item.taskId===null||task===void 0||task.deletion)return!1;if(item.tabId===null)return!0;return hasTab(item.tabId)!==!1}function partitionAttentionInboxAvailability(items,tasks2,hasTab){let tasksById=new Map(tasks2.map((task)=>[task.id,task])),availableItems=[],unavailableItems=[];for(let item of items){let taskId=item.taskId;if(isAttentionInboxItemAvailable(item,taskId===null?void 0:tasksById.get(taskId),(tabId)=>taskId===null?void 0:hasTab(taskId,tabId)))availableItems.push(item);else unavailableItems.push(item)}return{availableItems,unavailableItems}}function inboxBand(item){return item.state==="turn_complete"?1:0}function sortAttentionInbox(items,taskOrder){let taskIndex=new Map(taskOrder.map((id,index)=>[id,index]));return[...items].sort((a2,b3)=>{let band=inboxBand(a2)-inboxBand(b3);if(band!==0)return band;let age=a2.at-b3.at;if(age!==0)return age;let task=(taskIndex.get(a2.taskId??"")??Number.MAX_SAFE_INTEGER)-(taskIndex.get(b3.taskId??"")??Number.MAX_SAFE_INTEGER);if(task!==0)return task;return attentionInboxItemKey(a2).localeCompare(attentionInboxItemKey(b3))})}var INBOX_RECENT_LIMIT=5;function inboxRows(items,tasks2,options={}){let attention=sortAttentionInbox(items,tasks2.map((task)=>task.id)),tasksById=new Map(tasks2.map((task)=>[String(task.id),task])),pendingTasks=new Set(items.map((item)=>item.taskId)),coveredTab=(taskId,tabId)=>items.some((item)=>item.taskId===taskId&&(item.tabId===null||item.tabId===tabId)),visited=[...inboxVisitIndex(options.visits??[]).values()],isSelected=(taskId,tabId)=>taskId===options.selectedId&&(options.selectedTabId==null||tabId===options.selectedTabId),tabAlive=(visit)=>visit.tabId===null||options.tabExists?.(visit.taskId,visit.tabId)!==!1,visitedRows=visited.map((visit)=>({visit,task:tasksById.get(visit.taskId)})).filter((entry2)=>entry2.task!==void 0&&!entry2.task.deletion&&tabAlive(entry2.visit)&&!coveredTab(entry2.visit.taskId,entry2.visit.tabId)&&!isSelected(entry2.visit.taskId,entry2.visit.tabId)).map(({visit,task})=>({kind:"recent",id:visit.tabId?`r:${visit.taskId}:${visit.tabId}`:`r:${visit.taskId}`,task,tabId:visit.tabId,at:visit.at})),seenTasks=new Set(visitedRows.map((row)=>row.task.id)),unvisitedRows=tasks2.filter((task)=>!task.deletion&&!seenTasks.has(task.id)&&!pendingTasks.has(task.id)&&task.id!==options.selectedId).sort(compareRecent).map((task)=>({kind:"recent",id:`r:${task.id}`,task,tabId:null,at:taskMtime(task)})),recent=[...visitedRows,...unvisitedRows].slice(0,options.recentLimit??INBOX_RECENT_LIMIT),rows=[];if(attention.length>0){rows.push({kind:"header",id:"header:attention",section:"attention"});for(let item of attention)rows.push({kind:"attention",id:`a:${attentionInboxItemKey(item)}`,item})}if(recent.length>0)rows.push({kind:"header",id:"header:recent",section:"recent"}),rows.push(...recent);return rows}function taskMtime(task){let parsed=Date.parse(task.updatedAt||task.createdAt);return Number.isFinite(parsed)?parsed:0}function nextSelectableRow(rows,from,delta){let total=rows.length,index=from;for(let step=0;step<total;step++)if(index=(index+delta+total)%total,rows[index]?.kind!=="header")return index;return from}function clampSelectableRow(rows,cursor){if(rows.length===0)return 0;let bounded=Math.min(Math.max(cursor,0),rows.length-1);return rows[bounded]?.kind==="header"?nextSelectableRow(rows,bounded,1):bounded}function windowInboxRows(rows,cursor,budget){let cardIndexes=rows.reduce((acc,row,index)=>{if(row.kind!=="header")acc.push(index);return acc},[]);if(cardIndexes.length<=budget)return{visible:[...rows],hiddenAbove:0,hiddenBelow:0};let cursorCard=Math.max(0,cardIndexes.indexOf(clampSelectableRow(rows,cursor))),firstCard=Math.max(0,Math.min(cursorCard-budget+1,cardIndexes.length-budget)),lastCard=firstCard+budget-1,start=firstCard===0?0:cardIndexes[firstCard]??0,startWithHeader=start>0&&rows[start-1]?.kind==="header"?start-1:start,end=(cardIndexes[lastCard]??rows.length-1)+1;return{visible:rows.slice(startWithHeader,end),hiddenAbove:firstCard,hiddenBelow:cardIndexes.length-lastCard-1}}function nextAttentionInboxTarget(items,taskOrder,current2,isAvailable=()=>!0){let liveTasks=new Set(taskOrder),ordered=sortAttentionInbox(items,taskOrder).filter((item)=>(isRoutineInboxState(item.state)||item.taskId===null||liveTasks.has(item.taskId))&&isAvailable(item));if(ordered.length===0)return null;let currentKey=current2.taskId===null?null:attentionInboxItemKey(current2),currentIndex=currentKey===null?-1:ordered.findIndex((item)=>attentionInboxItemKey(item)===currentKey);if(currentIndex<0)return ordered[0]??null;if(ordered.length===1)return ordered[0]??null;return ordered[(currentIndex+1)%ordered.length]??null}var CROSS_TASK_KEY="notifications.crossTask.enabled";function notifyTargetKey(taskId,tabId){return`${taskId}:${tabId}`}function notifyTargetStates(engineState,engineTabState){let states=new Map,targets=new Map;for(let[taskId,es]of engineState){let tabs=engineTabState?.get(taskId),liveTabs=tabs?[...tabs].filter(([,tabEs])=>tabEs.state!=="idle"):[];if(liveTabs.length>0){for(let[tabId,tabEs]of liveTabs){let key2=notifyTargetKey(taskId,tabId);states.set(key2,tabEs.state),targets.set(key2,{taskId,tabId})}continue}let key=notifyTargetKey(taskId,"");states.set(key,es.state),targets.set(key,{taskId,tabId:""})}return{states,targets}}function useAttention(args){let{tasks:tasks2,engineState,engineTabState,inboxItems,selectedId,kv,notif,openAttention,noTasksMessage}=args,prevStates=import_react125.useRef(null);import_react125.useEffect(()=>{let{states:next,targets}=notifyTargetStates(engineState,engineTabState),edges=attentionEdges(prevStates.current,next,null,attentionKindFor);if(prevStates.current=next,kv.get(CROSS_TASK_KEY,!0)===!1)return;let repos=[...new Set(tasks2.map((t3)=>t3.repo))],taskById=new Map(tasks2.map((task)=>[task.id,task]));for(let{key,kind}of edges){let target=targets.get(key);if(!target||target.taskId===selectedId)continue;let task=taskById.get(target.taskId),project=task?sidebarProjectLabel(task.repo,repos):"",tab=target.tabId?knownTaskTab(kv,target.taskId,target.tabId):void 0,tabLabel2=tab?tabTitleStable(tab,task?.vendor??DEFAULT_TASK_VENDOR):"";notif.notify({kind,taskId:target.taskId,tabId:target.tabId,title:task?.title??target.taskId,body:tabLabel2?`${project} \u203A ${tabLabel2}`:project||void 0,silent:task?.dispatcher!==void 0,turnEnd:!0})}},[engineState,engineTabState,selectedId,tasks2,kv,notif]);function jumpToNextAttention(){let order=tasks2.filter((t3)=>!t3.deletion).map((t3)=>t3.id),target=nextAttentionInboxTarget(inboxItems,order,{taskId:selectedId,tabId:selectedId?activeTabIdFor(selectedId):null},(item)=>isAttentionInboxItemAvailable(item,tasks2.find((task)=>task.id===item.taskId),(tabId)=>item.taskId===null?void 0:taskTabExists(kv,item.taskId,tabId)));if(!target){notif.notify({kind:"done",taskId:selectedId??"",tabId:"",title:noTasksMessage});return}openAttention(target)}return{jumpToNextAttention}}function createPRAction(deps){let gather=deps.gather??gatherPRPromptState,build=deps.build??buildPRPrompt;return async function(){let wt=deps.worktree,send2=deps.sendToEngineFn.current;if(!wt||!send2)return;let state=await gather(wt);if(state.branch===state.targetBranch)return deps.notifyError(deps.t("files.toast.prOnTargetBranch",{branch:state.branch}));let prompt=await build(wt,state);if(deps.selectedWorktreeRef.current!==wt||deps.sendToEngineFn.current!==send2)return;send2(prompt)}}var pendingCreatePR=null;function requestCreatePR(taskId){pendingCreatePR=taskId}function takeCreatePR(taskId){if(taskId===null||pendingCreatePR!==taskId)return!1;return pendingCreatePR=null,!0}function useCreatePR(args){let t3=useT();return createPRAction({...args,t:t3})}function useDaemonState(orchestrator){let tasks2=useMergedTasks(orchestrator),activeTaskId=useAccessor(orchestrator.activeTaskSignal()),engineState=useAccessor(orchestrator.engineStateSignal()),engineLifecycle=useAccessor(orchestrator.engineLifecycleSignal()),engineTabState=useAccessor(orchestrator.engineTabStatesSignal()),inboxItems=useAccessor(orchestrator.attentionInboxSignal()),taskJobs=useAccessor(orchestrator.taskJobsSignal()),rowTokens=useAccessor(orchestrator.rowTokensSignal()),worktreeChanges2=useAccessor(orchestrator.worktreeChangesSignal());return{tasks:tasks2,activeTaskId,engineState,engineLifecycle,engineTabState,inboxItems,taskJobs,rowTokens,worktreeChanges:worktreeChanges2}}var import_react126=__toESM(require_react_production(),1);import{join as join4}from"path";import{basename}from"path";function tryPluginFileOpen(absPath){let handler=null;try{handler=findFileHandler(basename(absPath))}catch{return!1}if(!handler)return!1;let[cmd,...rest]=[...roveCliInvocation(),"plugin","action","invoke",handler.qualifiedAction,absPath];return spawnDetached(cmd,rest,{onError:(err)=>console.warn(`[rove/plugins] ${handler?.qualifiedAction}: ${String(err)}`)})}function useFileOpenActions(deps){let{orch,worktree,selectedId,focus,openEditorTabFn,openDiffTabFn,selectedWorktreeRef}=deps;async function openFileInEditor(relPath){let wt=worktree;if(!wt)return;let abs=join4(wt,relPath);orch.reportUiEvent("file.will-open",selectedId??void 0,{path:abs});let opened=(via)=>orch.reportUiEvent("file.opened",selectedId??void 0,{path:abs,via});if(tryPluginFileOpen(abs))return opened("plugin");let openEditorTab2=openEditorTabFn.current,launch=openEditorTab2?await resolveEditorLaunch(wt,abs):null;if(!launch)return openExternally(abs),opened("external");if(selectedWorktreeRef.current!==wt||openEditorTabFn.current!==openEditorTab2)return;openEditorTab2?.(["sh","-c",launch.command],launch.label),opened("editor"),focus.setFocused("workspace")}function openDiff(relPath,base){let label=relPath==="."?"all":relPath.endsWith("/")?relPath:pathLeaf(relPath);openDiffTabFn.current?.(relPath,label,base)}return{openFileInEditor,openDiff}}function firstLine2(detail){return detail.split(`
95
95
  `).find((line)=>line.trim().length>0)?.trim()??detail.trim()}function fixCIAction(deps){let build=deps.build??buildCIPromptForWorktree;return async function(taskId){let wt=deps.worktree,send2=deps.sendToEngineFn.current,task=deps.getTask(taskId);if(!wt||!send2||!task)return;let{checks,totalFailing,unavailable}=await deps.fetchChecks(taskId);if(unavailable)return deps.notifyError(deps.t("files.toast.ciChecksUnavailable",{detail:firstLine2(unavailable.detail)}));if(checks.length===0)return deps.notifyError(deps.t("files.toast.ciNoFailingChecks"));let prompt=await build(wt,{branch:task.branch||"HEAD",...task.prNumber===void 0?{}:{prNumber:task.prNumber},checks,totalFailing});if(deps.selectedWorktreeRef.current!==wt||deps.sendToEngineFn.current!==send2)return;send2(prompt)}}var pendingFixCI=null;function requestFixCI(taskId){pendingFixCI=taskId}function takeFixCI(taskId){if(taskId===null||pendingFixCI!==taskId)return null;return pendingFixCI=null,taskId}function useFixCI(args){let t3=useT();return fixCIAction({...args,t:t3})}function resolveConflictsAction(deps){let readOperation=deps.readOperation??pausedGitOperation,readConflicts=deps.readConflicts??conflictedPaths;return async function(taskId){let wt=deps.worktree,send2=deps.sendToEngineFn.current,branch=deps.getBranch(taskId);if(!wt||!send2||branch===null)return;let operation=readOperation(wt);if(!operation)return deps.notifyError(deps.t("files.toast.noPausedOperation"));let files=await readConflicts(wt);if(deps.selectedWorktreeRef.current!==wt||deps.sendToEngineFn.current!==send2)return;if(files===null)return deps.notifyError(deps.t("files.toast.conflictReadFailed"));if(!send2(buildConflictPrompt({operation,branch:branch||"HEAD",files})))deps.notifyError(deps.t("files.toast.conflictSendFailed"))}}var pendingResolve=null;function requestResolveConflicts(taskId){pendingResolve=taskId}function takeResolveConflicts(taskId){if(taskId===null||pendingResolve!==taskId)return null;return pendingResolve=null,taskId}function useResolveConflicts(args){let t3=useT();return resolveConflictsAction({...args,t:t3})}function mentionText(relPath){return`@${relPath}`}function mentionAction(pasteToEngineFn,onRefused){return(relPath)=>{let paste=pasteToEngineFn.current;if(!paste||!paste(mentionText(relPath)))onRefused()}}function useEditorHandles(opts){let{orchestrator,worktree,selectedId,focus,notifyError,activateTask}=opts,t3=useT(),openEditorTabFn=import_react126.useRef(null),sendToEngineFn=import_react126.useRef(null),pasteToEngineFn=import_react126.useRef(null),openDiffTabFn=import_react126.useRef(null),selectedWorktreeRef=useLatest(worktree),createPR=useCreatePR({worktree,sendToEngineFn,selectedWorktreeRef,notifyError}),fixCI=useFixCI({worktree,sendToEngineFn,selectedWorktreeRef,notifyError,getTask:(taskId)=>{let task=orchestrator.getTask(taskId);return task?{branch:task.branch,...task.prStatus?.number===void 0?{}:{prNumber:task.prStatus.number}}:null},fetchChecks:(taskId)=>orchestrator.failingChecks(taskId)}),resolveConflicts=useResolveConflicts({worktree,sendToEngineFn,selectedWorktreeRef,notifyError,getBranch:(taskId)=>orchestrator.getTask(taskId)?.branch??null}),{openFileInEditor,openDiff}=useFileOpenActions({orch:orchestrator,worktree,selectedId,focus,openEditorTabFn,openDiffTabFn,selectedWorktreeRef});return{onEditorTabReady:(open)=>{openEditorTabFn.current=open},onEngineSendReady:(send2)=>{if(sendToEngineFn.current=send2,takeCreatePR(selectedId))createPR();let parked=takeFixCI(selectedId);if(parked)fixCI(parked);let parkedResolve=takeResolveConflicts(selectedId);if(parkedResolve)resolveConflicts(parkedResolve)},onEnginePasteReady:(paste)=>{pasteToEngineFn.current=paste},onDiffTabReady:(open)=>{openDiffTabFn.current=open},onOpenFile:openFileInEditor,onOpenDiff:openDiff,onCreatePR:()=>void createPR(),onFixChecks:(taskId)=>{if(taskId===selectedId)return void fixCI(taskId);requestFixCI(taskId),activateTask(taskId)},onResolveConflicts:(taskId)=>{if(taskId===selectedId)return void resolveConflicts(taskId);requestResolveConflicts(taskId),activateTask(taskId)},onMention:mentionAction(pasteToEngineFn,()=>notifyError(t3("files.mentionNoEngine")))}}function useHostNotifiers(args){let{notif,t:t3,selectedId}=args,post=(kind,title)=>{notif.notify({kind,taskId:selectedId()??"",tabId:"",title})};return{notifyError:(message)=>post("error",message),notifyInfo:(message)=>post("done",message),notifyNeedsInput:(message)=>post("needs_input",message),notifyWorktreeGone:(event)=>notif.notify({kind:"error",taskId:event.taskId,tabId:"",title:t3("tasks.toast.worktreeGoneTitle",{title:event.title}),body:t3("tasks.toast.worktreeGoneBody",{count:String(event.closed),branch:event.branch||"\u2014"})})}}var import_react129=__toESM(require_react_production(),1);var import_react127=__toESM(require_react_production(),1);var CONTEXT_MAX_CHARS=400;function GateDecisionDialogView(props){let dialog=useDialog(),t3=useT(),padX=useDialogPaddingX(),{theme}=useTheme(),{options,recommended,question,context}=props.gate,hasOptions=options.length>0,[cursor,setCursor]=import_react127.useState(()=>Math.max(0,options.findIndex((o2)=>o2.key===recommended))),[note,setNote]=import_react127.useState(""),[field,setField]=import_react127.useState(hasOptions?"options":"note"),[error,setError]=import_react127.useState(null);function commit(){let text=note.trim();if(!hasOptions&&isBlankText(text)){setError(t3("gates.decision.needsText"));return}let option=hasOptions?options[cursor]?.key:void 0;props.onSubmit({...option!==void 0?{option}:{},...isBlankText(text)?{}:{text}}),dialog.clear()}function toggleField(){if(hasOptions)setField((f2)=>f2==="options"?"note":"options")}useBindings(()=>({bindings:[{key:"tab",cmd:toggleField},{key:"shift+tab",cmd:toggleField},...field==="options"?[{key:"up",cmd:()=>setCursor((c2)=>clampCursor2(c2-1,options.length))},{key:"down",cmd:()=>setCursor((c2)=>clampCursor2(c2+1,options.length))},{key:"return",cmd:()=>commit()}]:[]]}));let window2={items:options.map((o2)=>o2.key),start:0,total:options.length},rows=options.map((option)=>({key:option.key,body:`${option.key} ${option.label}`,accent:option.key===recommended,dim:option.key===recommended?t3("gates.decision.recommended"):option.detail})),clippedContext=context&&context.length>CONTEXT_MAX_CHARS?`${context.slice(0,CONTEXT_MAX_CHARS)}\u2026`:context;return $jsxs("box",{paddingLeft:padX,paddingRight:padX,gap:1,children:[$jsx(DialogHeader2,{title:`${t3("gates.decision.title")} \xB7 ${props.taskTitle}`,onClose:()=>props.onCancel()}),$jsx("text",{fg:theme.text,wrapMode:"word",children:question}),clippedContext?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:clippedContext}):null,hasOptions?$jsx(DialogSection2,{label:t3("gates.decision.optionsLabel"),focused:field==="options",children:$jsx(PickerList,{window:window2,cursor,focused:field==="options",rows,onPick:(index)=>{setCursor(index),setField("options")}})}):null,$jsx(DialogSection2,{label:t3("gates.decision.noteLabel"),focused:field==="note",hint:hasOptions?t3("gates.decision.noteOptionalHint"):t3("gates.decision.noteRequiredHint"),onPress:()=>setField("note"),children:$jsx(DialogField2,{focused:field==="note",children:$jsx("input",{value:note,placeholder:t3("gates.decision.notePlaceholder"),focused:field==="note",onInput:(v3)=>{setNote(stripNewlines2(v3)),setError(null)},onSubmit:()=>commit()})})}),error?$jsx("text",{fg:theme.error,wrapMode:"word",children:error}):null,$jsx(DialogFooter2,{children:hasOptions?field==="options"?t3("gates.decision.footerOptions"):t3("gates.decision.footerNoteWithOptions"):t3("gates.decision.footerNote")})]})}function show15(dialog,opts){return showDialog(dialog,(resolve3)=>$jsx(GateDecisionDialogView,{gate:opts.gate,taskTitle:opts.taskTitle,onSubmit:(answer)=>resolve3(answer),onCancel:()=>resolve3(void 0)}))}var GateDecisionDialog={show:show15};var import_react128=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes49}from"@opentui/core";function itemColor(state,theme){if(state==="permission_needed")return theme.warning;if(state==="turn_complete")return theme.success;if(state==="rate_limited"||state==="report_missing")return theme.warning;if(state==="decision_needed")return theme.warning;return theme.error}function itemGlyph(state,glyphs=DEFAULT_GLYPHS){if(state==="permission_needed")return glyphs.needsInput;if(state==="turn_complete")return glyphs.done;if(state==="rate_limited")return glyphs.rateLimited;if(state==="dead")return glyphs.dead;if(state==="routine_failed")return glyphs.routineFailed;if(state==="decision_needed")return glyphs.needsInput;return glyphs.attention}var GATE_ANSWERED_STATE_KEY="workspace.inbox.state.gateAnswered";function itemStateKey(state){if(state==="permission_needed")return"workspace.inbox.state.needsInput";if(state==="turn_complete")return"workspace.inbox.state.done";if(state==="rate_limited")return"workspace.inbox.state.rateLimited";if(state==="dead")return"workspace.inbox.state.dead";if(state==="routine_failed")return"workspace.inbox.state.routineFailed";if(state==="report_missing")return"workspace.inbox.state.reportMissing";if(state==="decision_needed")return"workspace.inbox.state.decisionNeeded";return"workspace.inbox.state.error"}function reportMissingNote(item){if(item.state!=="report_missing")return null;return item.detail?.note?.trim()||null}function quotaResumeNote(state,task,t3){if(state!=="rate_limited")return null;let raw=task?.quotaResume?.resumeAt;if(!raw)return null;let at2=Date.parse(raw);if(!Number.isFinite(at2))return null;return t3("workspace.inbox.resumesAt",{time:new Date(at2).toLocaleTimeString(intlLocale(),{hour:"numeric",minute:"2-digit"})})}function isDismissible(row){if(row?.kind!=="attention")return!1;return row.item.state!=="decision_needed"||row.item.detail?.gate?.undelivered===!0}var MAX_VISIBLE_CARDS=6,CARD_ROWS_WITH_GAP=3,DIALOG_CHROME_ROWS=12,AGE_REFRESH_MS=30000,IDENTITY_FLOOR_CELLS=16;function taskTabLabel(taskId,tabId,task,kv){let tab=tabId&&taskId?knownTaskTab(kv,taskId,tabId):void 0;return tab?tabTitleStable(tab,task?.vendor??DEFAULT_TASK_VENDOR):""}function tabLabel2(item,task,kv){return{label:taskTabLabel(item.taskId,item.tabId,task,kv),available:isAttentionInboxItemAvailable(item,task,(tabId)=>item.taskId===null?void 0:taskTabExists(kv,item.taskId,tabId))}}function runningBadge(opts){if(opts.activity?.state!=="running")return;return{glyph:breathGlyph(opts.glyphs.spinner,opts.frame),label:opts.t("workspace.inbox.state.running"),color:opts.theme.textMuted}}var NOOP_SUBSCRIBE2=()=>()=>{},ZERO_FRAME2=()=>0;function useSpinnerFrame2(active){return import_react128.useSyncExternalStore(active?subscribeSpinnerFrame:NOOP_SUBSCRIBE2,active?spinnerFrameSnapshot:ZERO_FRAME2)}function InboxCard(props){let{theme}=useTheme(),dimensions=useTerminalSize(),rowCells=Math.min(80,dimensions.width-2)-6,ageText=` ${props.age}`,fullBadge=props.badge?` ${props.badge.glyph} ${props.badge.label}`:"",cells=(s2)=>[...s2].reduce((n2,ch)=>n2+approxCharCells(ch.codePointAt(0)??0),0),identityRoom=rowCells-cells(ageText)-cells(fullBadge),dropLabel=props.badge!==void 0&&identityRoom<IDENTITY_FLOOR_CELLS,badgeText=props.badge?dropLabel?` ${props.badge.glyph}`:fullBadge:"",identity=truncateEndCells(props.identity,rowCells-cells(ageText)-cells(badgeText),approxCharCells),subtitle=truncateEndCells(props.subtitle,rowCells,approxCharCells),selection=resolveRowSelectionChrome2(theme,{cursor:props.active});return $jsxs("box",{flexDirection:"row",paddingRight:2,backgroundColor:selection.backgroundColor,onMouseUp:(event)=>{event.stopPropagation(),props.onOpen()},children:[$jsxs("box",{flexDirection:"column",flexShrink:0,paddingRight:1,children:[$jsx("text",{fg:selection.markerColor,wrapMode:"none",children:selection.marker}),$jsx("text",{fg:selection.markerColor,wrapMode:"none",children:selection.marker})]}),$jsxs("box",{flexDirection:"column",flexBasis:0,flexGrow:1,flexShrink:1,children:[$jsxs("box",{flexDirection:"row",children:[$jsx("text",{fg:theme.text,attributes:props.active?TextAttributes49.BOLD:void 0,wrapMode:"none",flexBasis:0,flexGrow:1,flexShrink:1,children:identity}),props.badge?$jsx("text",{fg:props.badge.color,wrapMode:"none",flexShrink:0,children:badgeText}):null,$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:ageText})]}),$jsx("box",{flexDirection:"row",children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexBasis:0,flexGrow:1,flexShrink:1,children:subtitle})})]})]})}function AttentionInboxPane(props){let{theme}=useTheme(),t3=useT(),dimensions=useTerminalSize(),[cursor,setCursor]=import_react128.useState(0),[now,setNow]=import_react128.useState(()=>Date.now()),tabsRev=useAccessor(tabsRevision),{availableItems}=import_react128.useMemo(()=>{return partitionAttentionInboxAvailability(props.items,props.tasks,(taskId,tabId)=>taskTabExists(props.kv,taskId,tabId))},[props.items,props.tasks,props.kv,tabsRev]),visits=import_react128.useMemo(()=>readInboxVisits(props.kv),[props.kv]),selectedTabId=props.selectedId?activeTabIdFor(props.selectedId):null,rows=import_react128.useMemo(()=>{return inboxRows(availableItems,props.tasks,{selectedId:props.selectedId,selectedTabId,visits,tabExists:(taskId,tabId)=>taskTabExists(props.kv,taskId,tabId)})},[availableItems,props.tasks,props.selectedId,selectedTabId,visits,props.kv,tabsRev]),attentionCount=rows.filter((row)=>row.kind==="attention").length,anyRunning=rows.some((row)=>row.kind==="recent"&&props.engineStates?.get(row.task.id)?.state==="running"),spinnerFrame=useSpinnerFrame2(anyRunning),glyphs=useGlyphs(),maxVisibleCards=Math.max(1,Math.min(MAX_VISIBLE_CARDS,Math.floor((dimensions.height-DIALOG_CHROME_ROWS)/CARD_ROWS_WITH_GAP))),safeCursor=clampSelectableRow(rows,cursor),{visible,hiddenAbove,hiddenBelow}=windowInboxRows(rows,safeCursor,maxVisibleCards),repos=[...new Set(props.tasks.map((task)=>task.repo))];import_react128.useEffect(()=>{if(cursor!==safeCursor)setCursor(safeCursor)},[cursor,safeCursor]),import_react128.useEffect(()=>{let timer3=setInterval(()=>setNow(Date.now()),AGE_REFRESH_MS);return()=>clearInterval(timer3)},[]);function move(delta){if(rows.length===0)return;setCursor(nextSelectableRow(rows,safeCursor,delta))}function selected(){return rows[safeCursor]}function open(row){if(row.kind==="recent"){props.onOpenTask(row.task.id,row.tabId);return}if(row.kind!=="attention")return;let task=props.tasks.find((candidate)=>candidate.id===row.item.taskId);props.onOpen(row.item,tabLabel2(row.item,task,props.kv).available)}return useBindings(()=>({bindings:bindByIds({"inbox.nav":(_event,slot)=>move((slot??0)%2===0?1:-1),"inbox.open":()=>{let row=selected();if(row)open(row)},"inbox.delete":()=>{let row=selected();if(row?.kind==="attention"&&isDismissible(row))props.onDelete(row.item)},"inbox.deleteAll":()=>{for(let row of rows)if(row.kind==="attention"&&isDismissible(row))props.onDelete(row.item)}})})),$jsxs("box",{flexDirection:"column",paddingLeft:1,paddingRight:1,children:[$jsxs("box",{flexDirection:"row",flexShrink:0,justifyContent:"space-between",children:[$jsxs("box",{flexDirection:"row",children:[$jsx("text",{fg:theme.focusAccent,attributes:TextAttributes49.BOLD,wrapMode:"none",children:t3("workspace.inbox.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:` ${attentionCount}`})]}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",onMouseUp:props.onClose,children:"esc"})]}),rows.length===0?$jsx("box",{paddingTop:1,paddingBottom:1,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("workspace.inbox.empty")})}):$jsxs("box",{flexDirection:"column",gap:1,paddingTop:1,paddingBottom:1,children:[hiddenAbove>0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:t3("workspace.inbox.more",{count:String(hiddenAbove)})}):null,visible.map((row)=>{let absoluteIndex=rows.indexOf(row);if(row.kind==="header")return $jsx("text",{fg:theme.textMuted,attributes:TextAttributes49.BOLD,wrapMode:"none",flexShrink:0,children:t3(`workspace.inbox.section.${row.section}`)},row.id);let active=absoluteIndex===safeCursor,openRow=()=>{setCursor(absoluteIndex),open(row)};if(row.kind==="recent"){let project2=sidebarProjectLabel(row.task.repo,repos),title2=row.task.kind==="main"?project2:row.task.title,tab2=taskTabLabel(row.task.id,row.tabId,row.task,props.kv);return $jsx(InboxCard,{identity:tab2?`${project2} \u203A ${tab2}`:title2===project2?project2:`${project2} \u203A ${title2}`,subtitle:title2,badge:runningBadge({activity:props.engineStates?.get(row.task.id),task:row.task,frame:spinnerFrame,glyphs,theme,t:t3}),age:relativeAge(row.at,now),active,onOpen:openRow},row.id)}let item=row.item,task=props.tasks.find((candidate)=>candidate.id===item.taskId),tab=tabLabel2(item,task,props.kv),routine=item.detail?.routine,gate=item.detail?.gate,title=routine?.name??task?.title??item.taskId??"",resumeNote=quotaResumeNote(item.state,task,t3)??reportMissingNote(item),contextLine=resumeNote?`${title} \xB7 ${resumeNote}`:title,project=task?sidebarProjectLabel(task.repo,repos):"";return $jsx(InboxCard,{identity:routine?`${t3("automations.title")} \u203A ${routine.name}`:tab.label?`${project} \u203A ${tab.label}`:project||title,subtitle:routine?routine.error??routine.status:gate?gate.question:contextLine,badge:{glyph:gate?.undelivered?glyphs.done:itemGlyph(item.state,glyphs),label:t3(gate?.undelivered?GATE_ANSWERED_STATE_KEY:itemStateKey(item.state)),color:itemColor(item.state,theme)},age:relativeAge(item.at,now),active,onOpen:openRow},row.id)}),hiddenBelow>0?$jsx("text",{fg:theme.textMuted,wrapMode:"none",flexShrink:0,children:t3("workspace.inbox.more",{count:String(hiddenBelow)})}):null]}),$jsxs("box",{flexDirection:"row",flexShrink:0,gap:2,paddingTop:1,children:[$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:t3("workspace.inbox.openHint")}),$jsx("text",{fg:theme.textMuted,attributes:isDismissible(selected())?void 0:TextAttributes49.DIM,wrapMode:"none",children:t3("workspace.inbox.clearHint")}),$jsx("text",{fg:theme.textMuted,attributes:rows.some(isDismissible)?void 0:TextAttributes49.DIM,wrapMode:"none",children:t3("workspace.inbox.clearAllHint")})]})]})}function AttentionInboxDialog(props){let dialog=useDialog(),kv=useKV(),items=useAccessor(props.orchestrator.attentionInboxSignal()),tasks2=useAccessor(props.orchestrator.tasksSignal()),engineStates=useAccessor(props.orchestrator.engineStateSignal());return $jsx(AttentionInboxPane,{items,tasks:tasks2,kv,selectedId:props.selectedId,engineStates,onOpen:props.onOpen,onOpenTask:props.onOpenTask,onDelete:props.onDelete,onClose:()=>dialog.clear()})}AttentionInboxDialog.show=(dialog,props)=>{dialog.replace(()=>$jsx(AttentionInboxDialog,{...props})),dialog.setSize("medium"),dialog.setPlacement("upper-fifth")};var FAILURE_KEY={"mark read":"tasks.toast.inboxMarkReadFailed",dismiss:"tasks.toast.inboxDismissFailed"};function notifyInboxRpcFailure(request,action,notifyError){request.catch((err)=>notifyError(t(FAILURE_KEY[action],{error:userFacingErrorMessage(err)})))}function requestInboxItemOpen(item,available,rpc,notifyError){return notifyInboxRpcFailure(dismissEpisode(item,rpc),"dismiss",notifyError),available}function dismissEpisode(item,rpc,explicit=!1){let automationId=item.detail?.routine?.automationId;if(isRoutineInboxState(item.state)&&automationId)return rpc.dismissRoutineAttention(automationId);if(item.state==="decision_needed")return Promise.resolve(!1);if(item.state==="report_missing"&&!explicit)return Promise.resolve(!1);if(item.taskId===null)return Promise.resolve(!1);let deliveryId=item.state==="report_missing"?item.detail?.delivery?.id:void 0;if(deliveryId===void 0)return rpc.dismissAttention(item.taskId,item.tabId,item.at);return rpc.dismissAttention(item.taskId,item.tabId,item.at,deliveryId)}function episodeKey(item){return`${attentionInboxKey(item)}\x00${item.at}`}function episodeSignature(items){return items.map(episodeKey).sort().join(`
96
- `)}function useInboxHost(args){let{orchestrator:orch}=args,tabsRev=useAccessor(tabsRevision),{availableItems,unavailableItems}=import_react129.useMemo(()=>{return partitionAttentionInboxAvailability(args.items,args.tasks,(taskId,tabId)=>taskTabExists(args.kv,taskId,tabId))},[args.items,args.tasks,args.kv,tabsRev]),viewingResolved=args.selectedId?new Set(visitResolvedEpisodes(availableItems,{taskId:args.selectedId,tabId:activeTabIdFor(args.selectedId)}).map(episodeKey)):null,visibleItems=viewingResolved&&viewingResolved.size>0?availableItems.filter((item)=>!viewingResolved.has(episodeKey(item))):availableItems,counts=attentionInboxCounts(visibleItems),notifyErrorRef=useLatest(args.notifyError),unavailableItemsRef=useLatest(unavailableItems),unavailableSignature=episodeSignature(unavailableItems),attemptedUnavailable=import_react129.useRef(new Set);import_react129.useEffect(()=>{let currentItems=unavailableItemsRef.current;if(episodeSignature(currentItems)!==unavailableSignature)return;let currentKeys=new Set(currentItems.map(episodeKey));for(let attempted of attemptedUnavailable.current)if(!currentKeys.has(attempted))attemptedUnavailable.current.delete(attempted);for(let item of currentItems){let key=episodeKey(item);if(attemptedUnavailable.current.has(key))continue;attemptedUnavailable.current.add(key),notifyInboxRpcFailure(dismissEpisode(item,orch),"dismiss",notifyErrorRef.current)}},[unavailableSignature,orch]);function openItem(item,knownAvailable){if(isRoutineInboxState(item.state)){if(notifyInboxRpcFailure(dismissEpisode(item,orch),"dismiss",args.notifyError),args.dialog.stack.length>0)args.dialog.clear({refocus:!1});args.openAutomations();return}let gate=item.state==="decision_needed"?item.detail?.gate:void 0;if(gate&&!gate.undelivered&&item.taskId!==null){let taskTitle=orch.getTask(item.taskId)?.title??item.taskId;GateDecisionDialog.show(args.dialog,{gate,taskTitle}).then((answer)=>{if(!answer)return;orch.answerGate(gate.id,answer).catch((err)=>args.notifyError(t("gates.toast.answerFailed",{error:userFacingErrorMessage(err)})))});return}let taskId=item.taskId;if(taskId===null)return;let task=orch.getTask(taskId),available=knownAvailable??isAttentionInboxItemAvailable(item,task,(tabId)=>taskTabExists(args.kv,taskId,tabId));if(!requestInboxItemOpen(item,available,orch,args.notifyError))return;if(args.dialog.stack.length>0)args.dialog.clear({refocus:!1});if(args.selectTask(taskId),item.tabId)requestTabActivation(taskId,item.tabId);args.focusWorkspace()}function openTask(taskId,tabId){if(args.dialog.stack.length>0)args.dialog.clear({refocus:!1});if(args.selectTask(taskId),tabId)requestTabActivation(taskId,tabId);args.focusWorkspace()}function closeItem(item){let gate=item.state==="decision_needed"?item.detail?.gate:void 0;if(!gate){notifyInboxRpcFailure(dismissEpisode(item,orch,!0),"dismiss",args.notifyError);return}if(!gate.undelivered)return;orch.withdrawGate(gate.id).catch((err)=>args.notifyError(t("gates.toast.withdrawFailed",{error:userFacingErrorMessage(err)})))}function show16(){AttentionInboxDialog.show(args.dialog,{orchestrator:orch,selectedId:args.selectedId,onOpen:openItem,onOpenTask:openTask,onDelete:closeItem})}let availableItemsRef=useLatest(availableItems),availableSignature=episodeSignature(availableItems),selectedIdRef=useLatest(args.selectedId),attemptedResolved=import_react129.useRef(new Set),resolveEpisodes=import_react129.useCallback((items,visit)=>{let currentKeys=new Set(items.map(episodeKey));for(let attempted of attemptedResolved.current)if(!currentKeys.has(attempted))attemptedResolved.current.delete(attempted);for(let item of visitResolvedEpisodes(items,visit)){let key=episodeKey(item);if(attemptedResolved.current.has(key))continue;attemptedResolved.current.add(key),notifyInboxRpcFailure(dismissEpisode(item,orch),"dismiss",notifyErrorRef.current)}},[orch]);function resolveVisited(taskId,tabId){resolveEpisodes(availableItemsRef.current,{taskId,tabId}),writeInboxVisit(args.kv,{taskId,tabId,at:Date.now()})}return import_react129.useEffect(()=>{let currentItems=availableItemsRef.current;if(episodeSignature(currentItems)!==availableSignature)return;let selectedId=selectedIdRef.current;if(!selectedId)return;let activeTab=activeTabIdFor(selectedId);if(!activeTab)return;resolveEpisodes(currentItems,{taskId:selectedId,tabId:activeTab})},[availableSignature,resolveEpisodes]),{availableItems:visibleItems,counts,openItem,show:show16,resolveVisited}}function buildIssueChatBackgroundSpawn(input){let base=interactiveEngineCommand(input.vendor),{sessionId}=withPinnedSessionId(base,input.vendor),fresh=initialTabs(),tab={...fresh.tabs[0],sessionId},state={...fresh,tabs:[tab]},spawn3=engineTabSpawnFor(state,tab,base,{live:!1,shell:input.shell??defaultShell(),prompt:input.prompt??issueWorktreePrompt(input.issue,input.api),task:{id:input.taskId,kind:input.kind??"task",vendor:input.vendor,repo:input.repoRoot},worktreePath:input.worktreePath,inlineImages:terminalDrawsKitty()});return{ptyKey:tabPtyKey(input.taskId,tab.id),command:spawn3.command,initialInput:spawn3.initialInput,firstMessage:spawn3.firstMessage,engineBin:spawn3.engineBin,tabsSnapshot:setTabSpawned(state,tab.id,!0)}}function useIssueChat(orch,hooks){let t3=useT();async function enter(taskId){hooks.closeKanban(),hooks.selectTask(taskId),await hooks.enterTask(taskId)}async function finish(request,enterTaskId){if(request.jump)await enter(enterTaskId);else hooks.notifyInfo(t3("kanban.detail.startedBackground",{title:issueChatTaskTitle(request.issue)}))}async function startProjectTab(request,api){let{repoRoot,issue,vendor}=request,main=await orch.ensureMainTask(repoRoot);await orch.mutateIssue(repoRoot,{type:"setStatus",id:issue.id,status:"doing"}).catch((err)=>{console.error("[rove kanban] issue setStatus failed:",err),hooks.notifyError(t3("kanban.statusFailed",{id:String(issue.id),error:userFacingErrorMessage(err)}))});let{task:child}=await orch.spawnChildTask({parentTaskId:main.id,worktree:!1,vendor}),spawn3=buildIssueChatBackgroundSpawn({issue,taskId:child.id,repoRoot,worktreePath:taskCwd(child),vendor,api,kind:child.kind,prompt:issueProjectPrompt(issue,api)});getDefaultPtyRegistry().acquire(spawn3.ptyKey,taskCwd(child),{command:spawn3.command,initialInput:spawn3.initialInput,firstMessage:spawn3.firstMessage,engineBin:spawn3.engineBin}),setTaskTabs2(child.id,spawn3.tabsSnapshot),await finish(request,child.id)}async function startWorktreeTask(request,api){let{repoRoot,issue,vendor}=request;setRepoLastActiveVendor(repoRoot,vendor),addSavedRepo(repoRoot);let task=await orch.createTask({repo:repoRoot,title:issueChatTaskTitle(issue),vendor});await orch.mutateIssue(repoRoot,{type:"link",id:issue.id,taskId:task.id}).catch((err)=>{console.error("[rove kanban] issue link failed:",err),hooks.notifyError(t3("kanban.linkFailed",{id:String(issue.id),error:userFacingErrorMessage(err)}))});let worktreePath=await orch.ensureWorktree(task.id),spawn3=buildIssueChatBackgroundSpawn({issue,taskId:task.id,repoRoot,worktreePath,vendor,api});return getDefaultPtyRegistry().acquire(spawn3.ptyKey,worktreePath,{command:spawn3.command,initialInput:spawn3.initialInput,firstMessage:spawn3.firstMessage,engineBin:spawn3.engineBin}),setTaskTabs2(task.id,spawn3.tabsSnapshot),{task,worktreePath,tab:spawn3.tabsSnapshot.tabs[0]}}async function start(request){try{let api=roveApiInvocation();if(request.placement==="project"){await startProjectTab(request,api);return}let{task,worktreePath,tab}=await startWorktreeTask(request,api);if(request.placement==="projectWorktree"){let main=await orch.ensureMainTask(request.repoRoot);await appendBackgroundEngineTab(main.id,{vendor:request.vendor,sessionId:tab.sessionId??null,ptyTask:{id:task.id,worktree:worktreePath}}),await finish(request,main.id);return}await finish(request,task.id)}catch(err){hooks.notifyError(t3("tasks.toast.issueChatFailed",{error:userFacingErrorMessage(err)}))}}return{start}}var import_react130=__toESM(require_react_production(),1);function usePrCheckNotifier(args){let notif=useLatest(args.notif),t3=useLatest(useT()),prev=import_react130.useRef(new Map);import_react130.useEffect(()=>{let next=new Map;for(let task of args.tasks){let pr=rollupPr(task),state=pr?.checkState;if(state===void 0)continue;next.set(task.id,state);let landed2=checkResolutionNotify(prev.current.get(task.id),state);if(!landed2)continue;notif.current.notify({kind:landed2==="passing"?"done":"error",taskId:task.id,tabId:"",title:t3.current(landed2==="passing"?"tasks.toast.checksPassingTitle":"tasks.toast.checksFailingTitle",{title:task.title}),body:t3.current("tasks.toast.checksResolvedBody",{pr:pr?.number===void 0?"\u2014":`#${pr.number}`,branch:task.branch||"\u2014"})})}prev.current=next},[args.tasks])}import{homedir}from"os";var import_react131=__toESM(require_react_production(),1);function decideScratchAdopt(input){if(!input.repoRoot||!input.harnessLive)return{kind:"stay"};let owners=input.ownerTasks.filter((task)=>task.dir!==""&&!task.sharesWorkspaceOf);if(input.cwd){let cwd=input.cwd,managed=owners.find((task)=>task.kind==="task"&&pathWithin(task.dir,cwd)!==null);if(managed)return{kind:"fold",taskId:managed.id}}for(let kind of["main","dir"]){let owned=owners.find((task)=>task.kind===kind&&(samePath(task.dir,input.cwd)||samePath(task.dir,input.repoRoot)));if(owned)return{kind:"fold",taskId:owned.id}}return{kind:"adopt",repo:input.repoRoot,known:[...input.knownRepos].some((repo)=>samePath(repo,input.repoRoot))}}async function renameHostedSession(from,to){if((process.env.ROVE_TERMINAL_BACKEND??"hosted")!=="hosted")return!1;try{return(await(await getSharedPtyClient()).request("pty.rename",{from,to})).renamed===!0}catch{return!1}}var tabNumber=(id)=>Number(/^tab-(\d+)$/.exec(id)?.[1]??0);async function foldScratchShell(io,scratchTaskId,targetTaskId){let rename=io.rename??renameHostedSession,scratchTabIds=(knownTaskTabs(io.kv,scratchTaskId)?.tabs??[{id:"tab-1"}]).map((tab)=>tab.id),reserved=await(io.reserve??reserveTabOrdinals)(targetTaskId,scratchTabIds.length*2).catch(()=>null),fallback=1+(knownTaskTabs(io.kv,targetTaskId)?.tabs??[]).reduce((max,tab)=>Math.max(max,tabNumber(tab.id)),0),nextId=()=>`tab-${reserved?.shift()??fallback++}`,folded=[];for(let tabId of scratchTabIds){let from=tabPtyKey(scratchTaskId,tabId),to=nextId(),ok=await rename(from,tabPtyKey(targetTaskId,to));if(!ok)to=nextId(),ok=await rename(from,tabPtyKey(targetTaskId,to));if(!ok)continue;folded.push(to)}if(folded.length===0)return null;return adoptTaskTabs(io.kv,targetTaskId,folded),{activeTabId:folded[0]}}var POLL_MS5=5000;function scratchOwnerTasks(tasks2){return tasks2.filter((task)=>!task.deletion&&task.scratch!==!0&&task.worktreePath!=="").map((task)=>({id:task.id,kind:task.kind??"task",dir:canonPath(task.worktreePath),...task.sharesWorkspaceOf?{sharesWorkspaceOf:task.sharesWorkspaceOf}:{}}))}function useScratchAdopt(deps){let{tasks:tasks2,orchestrator,kv,notifyInfo}=deps,onFoldRef=useLatest(deps.onFold),enabled=deps.enabled??!0,scratchIds=tasks2.filter((t3)=>t3.kind==="dir"&&t3.scratch===!0).map((t3)=>t3.id).join(",");import_react131.useEffect(()=>{if(!enabled||scratchIds==="")return;let cancelled=!1,inFlight=new Set,tick3=async()=>{let scratch=tasks2.filter((t3)=>t3.kind==="dir"&&t3.scratch===!0);if(scratch.length===0)return;let known=new Set([...getSavedRepos(),...tasks2.map((t3)=>t3.repo)]),owners=scratchOwnerTasks(tasks2),registry=getDefaultPtyRegistry(),liveEngines=getDefaultLiveEngines();for(let task of scratch){if(inFlight.has(task.id))continue;let key=tabPtyKey(task.id,"tab-1"),pid=registry.get(key)?.shellPid??null;if(pid===null||pid===void 0)continue;if(!liveEngines.get(key))continue;let rawCwd=await processCwd(pid);if(cancelled||!rawCwd)continue;let cwd=canonPath(rawCwd),repoRoot=canonPath(resolveMainRepoRoot(cwd)),decision=decideScratchAdopt({cwd,repoRoot:isGitRepo(repoRoot)?repoRoot:null,harnessLive:!0,knownRepos:known,ownerTasks:owners});if(cancelled||decision.kind==="stay")continue;inFlight.add(task.id);try{if(decision.kind==="fold"){let folded=await foldScratchShell({kv},task.id,decision.taskId);if(!folded)throw Error("fold did not move any session");await onFoldRef.current(task.id,decision.taskId,folded.activeTabId);continue}if(await orchestrator.adoptScratchRepo(task.id,decision.repo),!decision.known)notifyInfo(t("tasks.toast.scratchAdopted",{repo:repoBasename(decision.repo)}))}catch{inFlight.delete(task.id)}}};tick3();let timer3=setInterval(()=>void tick3(),POLL_MS5);return()=>{cancelled=!0,clearInterval(timer3)}},[enabled,scratchIds,orchestrator,kv,notifyInfo,tasks2])}var scratchTeardowns=new Set;function useScratchShell(deps){let{orchestrator,enterTask,forgetTaskTabs:forgetTaskTabs2,notifyError}=deps;useScratchAdopt({tasks:deps.tasks,orchestrator,kv:deps.kv,notifyInfo:deps.notifyInfo,onFold:async(scratchTaskId,targetTaskId,tabId)=>{if(deps.selectedId()===scratchTaskId)deps.selectTask(targetTaskId),requestTabActivation(targetTaskId,tabId);await orchestrator.deleteTask(scratchTaskId),forgetTaskTabs2(scratchTaskId)}});let openScratchShell=(vendor,prompt)=>{orchestrator.openDirectoryTask({dir:homedir(),scratch:!0,...vendor?{vendor}:{}}).then((task)=>{if(vendor)engineScratchTasks.add(task.id);if(vendor&&prompt)deps.seedPrompt(task.id,prompt);enterTask(task.id)}).catch((err)=>notifyError(t("tasks.toast.scratchOpenFailed",{message:userFacingErrorMessage(err)})))};return{openScratchShell,onScratchExit:(taskId)=>{if(scratchTeardowns.has(taskId))return;scratchTeardowns.add(taskId),(async()=>{try{await orchestrator.deleteTask(taskId),forgetTaskTabs2(taskId),await finishDeletedTaskFlow({orch:orchestrator,tasks:deps.tasks,taskId,logger:console,logPrefix:"[rove scratch]",updateActiveTask:!0})}catch(err){notifyError(t("tasks.toast.scratchCloseFailed",{message:userFacingErrorMessage(err)}))}})()},reportProblem:()=>openScratchShell(getGlobalDefaultVendor()??DEFAULT_TASK_VENDOR,t("help.reportPrompt",{logPath:defaultDaemonLogPath()}))}}var import_react132=__toESM(require_react_production(),1);function activationErrorMessage(error,translate){let message=errorMessage(error);if(message.includes(TASK_DELETING_CODE))return translate("tasks.toast.worktreeErrorDeleting");if(/not a git repository|does not appear to be a git repo/i.test(message))return translate("tasks.toast.worktreeErrorNotGit");return translate("tasks.toast.worktreeErrorGeneric",{message:userFacingErrorMessage(error)})}async function activateWorkspaceTask(opts,id){let task=opts.getTask(id);if(task?.deletion)return opts.reportError(new TaskDeletingError(id)),!1;if(task?.origin&&task.origin.machineId!=="local")return opts.selectTask(id),opts.focusWorkspace(),!0;if(!task?.worktreePath)try{await opts.ensureWorktree(id)}catch(error){return opts.reportError(error),!1}if(opts.isCurrent?.()===!1)return!1;return opts.selectTask(id),opts.focusWorkspace(),!0}function firstSelectableTask(tasks2,activeId,lastActiveId){let alive=(id)=>id?tasks2.find((task)=>task.id===id&&!task.deletion):void 0,active=alive(activeId)??alive(lastActiveId);if(active)return active;let live=tasks2.filter((task)=>!task.deletion),newest=(pool)=>pool.length>0?pool.reduce((best,task)=>task.updatedAt>best.updatedAt?task:best):void 0;return newest(live.filter((task)=>task.routine===void 0))??newest(live)??tasks2.find((task)=>!task.deletion)}function useWorkspaceSelection(args){let{orch,tasks:tasks2,activeTaskId,kv}=args,t3=useT(),[selectedId,setSelectedId]=import_react132.useState(()=>orch.activeTaskSignal()()??readLastActiveTaskId()),focusRestoredRef=import_react132.useRef(!1),userPickedRef=import_react132.useRef(!1),bootFocusRef=import_react132.useRef(!1),liveSelectedRef=import_react132.useRef(null);import_react132.useEffect(()=>{if(!focusRestoredRef.current&&activeTaskId&&tasks2.some((task)=>task.id===activeTaskId)){if(focusRestoredRef.current=!0,!userPickedRef.current&&selectedId!==activeTaskId){setSelectedId(activeTaskId);return}}if(!bootFocusRef.current&&!userPickedRef.current&&selectedId&&tasks2.some((task)=>task.id===selectedId))bootFocusRef.current=!0,args.focusWorkspace();let selected=selectedId?tasks2.find((task)=>task.id===selectedId):void 0,wasLive=selectedId!==null&&liveSelectedRef.current===selectedId;if(liveSelectedRef.current=selected&&selected.archived!==!0&&!selected.deletion?selectedId:null,wasLive&&selected?.archived===!0){setSelectedId(firstSelectableTask(tasks2.filter((task)=>task.archived!==!0),null)?.id??null);return}if(selectedId&&tasks2.some((task)=>task.id===selectedId&&!task.deletion))return;setSelectedId(firstSelectableTask(tasks2,activeTaskId,readLastActiveTaskId())?.id??null)},[tasks2,activeTaskId,selectedId,args.focusWorkspace]);let notifyWorktreeGoneRef=useLatest(args.notifyWorktreeGone),liveTaskIdsRef=import_react132.useRef(new Set),worktreePathsRef=import_react132.useRef(new Map);import_react132.useEffect(()=>{let next=new Set(tasks2.filter((task)=>!task.deletion).map((task)=>task.id)),registry=getDefaultPtyRegistry(),aliased=aliasedKeys(tasks2.filter((task)=>!task.deletion));for(let id of liveTaskIdsRef.current){if(next.has(id))continue;registry.releaseWhere((key)=>(key===id||key.startsWith(`${id}::`))&&!aliased.some((base)=>isUnderKey(key,base)))}liveTaskIdsRef.current=next;let paths=new Map;for(let task of tasks2)paths.set(task.id,task.worktreePath);for(let[id,prevPath]of worktreePathsRef.current)if(paths.get(id)===""&&prevPath!==""){let closed=knownTaskTabs(kv,id)?.tabs.length??0;registry.releaseWhere((key)=>key===id||key.startsWith(`${id}::`)),forgetTaskTabs(kv,id);let task=tasks2.find((candidate)=>candidate.id===id);notifyWorktreeGoneRef.current?.({taskId:id,title:task?.title??id,branch:task?.branch??"",closed})}worktreePathsRef.current=paths},[tasks2,kv]);function selectTask(id){if(userPickedRef.current=!0,selectedId===id){if(orch.activeTaskSignal()()!==id)orch.setActiveTask(id).catch((error)=>console.error("[rove workspace] setActiveTask failed:",error));return}setSelectedId(id),orch.setActiveTask(id).catch((error)=>console.error("[rove workspace] setActiveTask failed:",error));let kind=tasks2.find((task)=>task.id===id)?.kind==="main"?"project.opened":"task.opened";orch.reportUiEvent(kind,id)}let activationGenerationRef=import_react132.useRef(0);async function activateTask(id){let generation=++activationGenerationRef.current;reviveEmptiedTabs(kv,id,defaultShell()),await activateWorkspaceTask({getTask:(taskId)=>tasks2.find((task)=>task.id===taskId),ensureWorktree:(taskId)=>orch.ensureWorktree(taskId),selectTask,focusWorkspace:args.focusWorkspace,reportError:(error)=>{console.error("[rove workspace] task.ensureWorktree failed:",error),args.notifyError?.(activationErrorMessage(error,t3))},isCurrent:()=>activationGenerationRef.current===generation},id)}let selectedTask=selectedId?tasks2.find((task)=>task.id===selectedId):void 0;return{selectedId,setSelectedId,selectedTask,selectTask,activateTask}}var import_react133=__toESM(require_react_production(),1);function useZenMode(deps){let{kv,focus}=deps,[zen,setZen]=import_react133.useState(()=>kv.get(ZEN_ACTIVE_KEY,ZEN_DEFAULT)===!0);function toggleZen(){let next=!zen;if(setZen(next),kv.set(ZEN_ACTIVE_KEY,next),next)focus.setFocused("workspace")}return import_react133.useEffect(()=>{if(focus.focused==="files")setZen(!1)},[focus.focused]),{zen,toggleZen}}function WorkspaceRoot(props){let{theme}=useTheme(),inactiveBorder=theme.borderActive,dialog=useDialog(),kv=useKV(),focus=useFocus(),dims=useTerminalSize(),sidebarWidth=useSidebarWidth(),[sidebarCollapsed]=useSidebarCollapsed(),sidebarResize=useSidebarResizeGesture({width:sidebarWidth.width,onResize:sidebarWidth.pin,onReset:sidebarWidth.reset}),renderer=useRenderer(),notif=useNotifications(),orch=props.orchestrator;useDaemonNotices(orch,notif.notify,dialog);let{tasks:tasks2,activeTaskId,engineState,engineLifecycle,engineTabState,inboxItems,taskJobs,rowTokens,worktreeChanges:worktreeChanges2}=useDaemonState(orch),[searchActive,setSearchActive]=import_react135.useState(!1),t3=useT(),{notifyError,notifyInfo,notifyNeedsInput,notifyWorktreeGone}=useHostNotifiers({notif,t:t3,selectedId:()=>selectedId}),{selectedId,setSelectedId,selectedTask,selectTask,activateTask}=useWorkspaceSelection({orch,tasks:tasks2,activeTaskId,focusWorkspace:()=>focus.setFocused("workspace"),kv,notifyWorktreeGone,notifyError}),worktree=selectedTask?.worktreePath||null,workingFlow=selectedId!==null&&engineState?.get(selectedId)?.state==="running"&&normalizeWorkingBorder(kv.get(WORKING_BORDER_KEY,DEFAULT_WORKING_BORDER))==="flow",breath=useSpinnerFrame(workingFlow),taskInk=useTaskColor(selectedId),{sortMode,toggleSortMode,moveMode,setMoveMode,onLocalMergeRequest}=useSidebarHostState({kv,tasks:tasks2,focusSidebar:()=>focus.setFocused("sidebar"),notify:notifyInfo}),inbox=useInboxHost({orchestrator:orch,items:inboxItems,tasks:tasks2,kv,dialog,selectedId,selectTask,openAutomations:()=>pages.openPage("automations"),focusWorkspace:()=>focus.setFocused("workspace"),notifyError}),{jumpToNextAttention}=useAttention({tasks:tasks2,engineState,engineTabState,inboxItems:inbox.availableItems,selectedId,kv,notif,openAttention:inbox.openItem,noTasksMessage:t3("workspace.attention.none")});usePrCheckNotifier({tasks:tasks2,notif});let taskActions=useWorkspaceTaskActions({orchestrator:orch,tasks:()=>tasks2,dialog,notifyError,notifyInfo,notifyNeedsInput,t:t3,selectedId:()=>selectedId,setSelectedId,selectedTask:()=>selectedTask,activateTask,forgetTaskTabs:(id)=>forgetTaskTabs(kv,id),closeTaskTabs:(id)=>closeAllTaskTabs(kv,id),startWithPrompt:(repo,start)=>quickFork.onQuickFork(repo,{...start,attachments:[],attempts:1})}),editor=useEditorHandles({orchestrator:orch,worktree,selectedId,focus,notifyError,activateTask}),quickFork=useQuickFork(orch,{selectTask:setSelectedId,enterTask:activateTask,notifyError,notify:notifyInfo,t:t3}),scratch=useScratchShell({orchestrator:orch,tasks:tasks2,kv,selectedId:()=>selectedId,selectTask:setSelectedId,enterTask:(id)=>void activateTask(id),forgetTaskTabs:(id)=>forgetTaskTabs(kv,id),notifyError,notifyInfo,seedPrompt:quickFork.seedPrompt}),{zen,toggleZen}=useZenMode({kv,focus}),filesActions=useFilesPaneActions({onOpenFile:(relPath)=>void editor.onOpenFile(relPath),onOpenDiff:editor.onOpenDiff,onMention:editor.onMention,onZenToggle:toggleZen,onCreatePR:()=>void editor.onCreatePR()});import_react135.useEffect(()=>{return setUiEventReporter((kind,taskId,detail)=>orch.reportUiEvent(kind,taskId,detail)),()=>setUiEventReporter(null)},[orch]),useTabsSync(orch.tabs,orch.connectionStateSignal()),useRowStatusSync(orch.rowStatus,orch.connectionStateSignal());let pages=useHostPagesState(focus,props);useWhatsNewDialog(pages.whatsNewFrom,pages.closeWhatsNew),useWelcomeDialog(pages.welcome,pages.closeWelcome);let selectedTabId=selectedId===null?null:activeTabIdFor(selectedId),issueChat=useIssueChat(orch,{selectTask:setSelectedId,enterTask:activateTask,closeKanban:pages.closePage,notifyError,notifyInfo}),pageRender=useHostPagesRender({orchestrator:orch,pages,focus,dialog,kv,dims,selectedTask,activeTaskId,tasks:tasks2,engineState,activateTask}),openTaskWorktree=(id)=>openTaskWorktreeFor(id,{tasks:tasks2,ensureWorktree:orch.ensureWorktree.bind(orch),notifyError}),cursorTaskIdRef=import_react135.useRef(()=>null),banner=useHostBanner(orch,dims.width),refreshRove=()=>{selfRefreshAction({orchestrator:orch,renderer,confirm:()=>DialogConfirm.show(dialog,t3("update.refresh.confirmTitle"),t3("update.refresh.confirmBody"),t3("common.cancel"),t3("update.refresh.confirmLabel")).then((ok)=>ok===!0),notifyError,t:t3},banner.refresh.inputs)};useWorkspaceKeybindings({focus,dialog,pages,filesPaneVisible:!zen&&pages.nav==="terminal"&&pageRender.showSidebar&&pageRender.showContent,searchActive,selectedId,cursorTaskId:()=>cursorTaskIdRef.current(),openTaskWorktree,createTask:()=>void taskActions.createTask(),renameBranch:(id)=>void taskActions.renameBranch(id),cycleVendor:(id)=>void taskActions.cycleVendor(id),toggleZen,jumpToNextAttention,openInbox:inbox.show,reportProblem:scratch.reportProblem,paletteSearch:{orchestrator:orch,tasks:tasks2,openTask:openTaskOnTab(pages.closePage,activateTask)},createPR:()=>void editor.onCreatePR(),createPRFor:(id)=>{requestCreatePR(id),activateTask(id)},fixChecksFor:editor.onFixChecks,syncBaseFor:(id)=>void taskActions.syncBase(id),enterMoveMode:()=>{let target=selectedId??tasks2[0]?.id;if(!target)return;focus.setFocused("sidebar"),setSelectedId(String(target)),setMoveMode(!0)},toggleSortMode,refresh:{available:banner.refresh.available,run:refreshRove}});let activePane=dialog.stack.length>0?null:focus.focused,fullWindow=pageRender.settingsPage??pageRender.fullWindowPage,contentPageType=import_react135.isValidElement(pageRender.contentPage)?pageRender.contentPage.type:null;if(fullWindow)return $jsx(FullWindowPage,{banner:banner.element,background:theme.background,children:$jsx(PaneErrorBoundary,{region:"page",children:fullWindow})});return $jsxs(WorkspaceFrame,{orchestrator:orch,onOpenSettings:()=>pages.openSettings(),banner:banner.element,activeTaskId:selectedId,activeTabId:selectedTabId,onPaneDrag:sidebarResize.onPaneDrag,onPaneRelease:sidebarResize.onPaneRelease,children:[pageRender.showSidebar?$jsx(RenderProfiler,{id:"sidebar",children:$jsx(PaneErrorBoundary,{region:"sidebar",width:pageRender.showContent?sidebarWidth.width:dims.width,children:$jsx(HostSidebarMount,{terminalWidth:dims.width,showContent:pageRender.showContent,recentTask:pageRender.recentTask,tasks:tasks2,selectedId,selectTask,activateTask,daemon:{engineState,engineTabState,engineLifecycle,taskJobs,rowTokens,worktreeChanges:worktreeChanges2},actions:taskActions,pages,focus,inbox,update:banner.update,onFixChecks:editor.onFixChecks,onResolveConflicts:editor.onResolveConflicts,runAgain:quickFork.runAgain,openScratch:scratch.openScratchShell,activePane,zen,toggleZen,sortMode,moveMode,exitMoveMode:()=>setMoveMode(!1),onLocalMergeRequest,onSearchActiveChange:setSearchActive,cursorTaskIdRef,openTaskWorktree,t:t3})})}):null,pageRender.showContent?$jsxs("box",{flexGrow:1,flexShrink:1,borderStyle:"rounded",borderColor:focus.focused==="workspace"?theme.focusAccent:inactiveBorder,renderAfter:workingFlow?runningPaneFlow(taskInk??theme.focusAccent,inactiveBorder,focus.focused==="workspace",breath,taskInk?TASK_PARTNER_HUE_DEG:void 0):void 0,title:workingFlow&&selectedTask?runningPaneTitle(selectedTask.title,t3("workspace.inbox.state.running")):void 0,onMouseUp:()=>focus.setFocused("workspace"),children:[isNarrowWidth(dims.width)?$jsx(NarrowBackBar,{onBack:()=>focus.setFocused("sidebar")}):null,$jsx(PaneErrorBoundary,{region:"workspace",resetKeys:[selectedId,contentPageType],children:pageRender.contentPage?$jsx(PageServicesProvider,{value:{startIssueChat:issueChat.start},children:pageRender.contentPage}):$jsx(RenderProfiler,{id:"workspace",children:$jsx(ShowWorkspace,{task:selectedTask,worktree,orchestrator:orch,focused:activePane==="workspace",onRequestFocus:()=>focus.setFocused("workspace"),onEditorTabReady:editor.onEditorTabReady,onEngineSendReady:editor.onEngineSendReady,onEnginePasteReady:editor.onEnginePasteReady,onDiffTabReady:editor.onDiffTabReady,onSpawnChild:quickFork.onSpawnChild,onQuickFork:quickFork.onQuickFork,initialPrompt:quickFork.initialPromptFor(selectedTask?.id),onTabVisited:inbox.resolveVisited,onScratchExit:scratch.onScratchExit,onOpenScratch:scratch.openScratchShell,onEngineChosen:taskActions.setVendor,onOpenSettings:pages.openSettings})})})]}):null,!zen&&pageRender.contentPage==null&&pageRender.showSidebar&&pageRender.showContent?$jsx(HostFilesPane,{sidebarWidth:sidebarWidth.width,worktree,prBaseRef:selectedTask?.prStatus?.baseRef,focused:activePane==="files",actions:filesActions,taskKind:selectedTask?.kind,remoteHost:selectedTask?.origin&&selectedTask.origin.machineId!=="local"?selectedTask.origin.hostLabel:void 0,remote:selectedTask?.origin&&selectedTask.origin.machineId!=="local"&&!selectedTask.origin.stale?{machine:selectedTask.origin.machineId,taskId:String(selectedTask.id)}:void 0}):null,$jsx(ToastOverlay,{}),$jsx(PrefixHud,{left:1,width:sidebarWidth.width-2}),pageRender.showSidebar&&pageRender.showContent&&!sidebarCollapsed?$jsx(SidebarResizeGrip,{width:sidebarWidth.width,onGripDown:sidebarResize.onGripDown}):null]})}async function startWorkspaceHost(opts={}){await bootPaneHost({logContext:"workspace",providers:{kv:!0,focus:!0,notifications:!0},setup:async()=>{let cellPixelSize=await queryCellPixelSize({stdin:process.stdin,stdout:process.stdout}),client=await connectOrStartDaemon(),channels=CHANNEL_NAMES.filter((name)=>name!=="state"),orchestrator=new RemoteOrchestrator(client,{role:"gui",cellPixelSize,channels});await orchestrator.init(),process.env.ROVE_DAEMON_SOCKET_PATH=client.socketPath,installTerminalGraphics(createTerminalGraphics({env:process.env,stdoutIsTTY:process.stdout.isTTY===!0,cellPixelSize,write:(data)=>orchestrator.writeGraphics(data)}));let{MachineFeed}=await import("./chunk-08mb3qss.js"),{setMachineHub}=await import("./chunk-wv6d96t6.js"),machines=new MachineFeed(orchestrator);setMachineHub(machines);let stopRemoteStatus=followRemoteActivity(machines.liveSignal());registerCorePages();let stopModsPage=registerModsPage(orchestrator);registerBundledPlugins();let stopBundledPlugins=followBundledPlugins();return loadPluginPages(),{root:()=>$jsx(WorkspaceRoot,{orchestrator,whatsNewFrom:opts.whatsNewFrom??null,welcome:opts.welcome??null}),onDestroy:()=>{stopBundledPlugins(),stopModsPage(),stopRemoteStatus(),setMachineHub(null),machines.dispose(),orchestrator.dispose(),installTerminalGraphics(null),getDefaultPtyRegistry().detachAll()}}}})}export{startWorkspaceHost};
96
+ `)}function useInboxHost(args){let{orchestrator:orch}=args,tabsRev=useAccessor(tabsRevision),{availableItems,unavailableItems}=import_react129.useMemo(()=>{return partitionAttentionInboxAvailability(args.items,args.tasks,(taskId,tabId)=>taskTabExists(args.kv,taskId,tabId))},[args.items,args.tasks,args.kv,tabsRev]),viewingResolved=args.selectedId?new Set(visitResolvedEpisodes(availableItems,{taskId:args.selectedId,tabId:activeTabIdFor(args.selectedId)}).map(episodeKey)):null,visibleItems=viewingResolved&&viewingResolved.size>0?availableItems.filter((item)=>!viewingResolved.has(episodeKey(item))):availableItems,counts=attentionInboxCounts(visibleItems),notifyErrorRef=useLatest(args.notifyError),unavailableItemsRef=useLatest(unavailableItems),unavailableSignature=episodeSignature(unavailableItems),attemptedUnavailable=import_react129.useRef(new Set);import_react129.useEffect(()=>{let currentItems=unavailableItemsRef.current;if(episodeSignature(currentItems)!==unavailableSignature)return;let currentKeys=new Set(currentItems.map(episodeKey));for(let attempted of attemptedUnavailable.current)if(!currentKeys.has(attempted))attemptedUnavailable.current.delete(attempted);for(let item of currentItems){let key=episodeKey(item);if(attemptedUnavailable.current.has(key))continue;attemptedUnavailable.current.add(key),notifyInboxRpcFailure(dismissEpisode(item,orch),"dismiss",notifyErrorRef.current)}},[unavailableSignature,orch]);function openItem(item,knownAvailable){if(isRoutineInboxState(item.state)){if(notifyInboxRpcFailure(dismissEpisode(item,orch),"dismiss",args.notifyError),args.dialog.stack.length>0)args.dialog.clear({refocus:!1});args.openAutomations();return}let gate=item.state==="decision_needed"?item.detail?.gate:void 0;if(gate&&!gate.undelivered&&item.taskId!==null){let taskTitle=orch.getTask(item.taskId)?.title??item.taskId;GateDecisionDialog.show(args.dialog,{gate,taskTitle}).then((answer)=>{if(!answer)return;orch.answerGate(gate.id,answer).catch((err)=>args.notifyError(t("gates.toast.answerFailed",{error:userFacingErrorMessage(err)})))});return}let taskId=item.taskId;if(taskId===null)return;let task=orch.getTask(taskId),available=knownAvailable??isAttentionInboxItemAvailable(item,task,(tabId)=>taskTabExists(args.kv,taskId,tabId));if(!requestInboxItemOpen(item,available,orch,args.notifyError))return;if(args.dialog.stack.length>0)args.dialog.clear({refocus:!1});if(args.selectTask(taskId),item.tabId)requestTabActivation(taskId,item.tabId);args.focusWorkspace()}function openTask(taskId,tabId){if(args.dialog.stack.length>0)args.dialog.clear({refocus:!1});if(args.selectTask(taskId),tabId)requestTabActivation(taskId,tabId);args.focusWorkspace()}function closeItem(item){let gate=item.state==="decision_needed"?item.detail?.gate:void 0;if(!gate){notifyInboxRpcFailure(dismissEpisode(item,orch,!0),"dismiss",args.notifyError);return}if(!gate.undelivered)return;orch.withdrawGate(gate.id).catch((err)=>args.notifyError(t("gates.toast.withdrawFailed",{error:userFacingErrorMessage(err)})))}function show16(){AttentionInboxDialog.show(args.dialog,{orchestrator:orch,selectedId:args.selectedId,onOpen:openItem,onOpenTask:openTask,onDelete:closeItem})}let availableItemsRef=useLatest(availableItems),availableSignature=episodeSignature(availableItems),selectedIdRef=useLatest(args.selectedId),attemptedResolved=import_react129.useRef(new Set),resolveEpisodes=import_react129.useCallback((items,visit)=>{let currentKeys=new Set(items.map(episodeKey));for(let attempted of attemptedResolved.current)if(!currentKeys.has(attempted))attemptedResolved.current.delete(attempted);for(let item of visitResolvedEpisodes(items,visit)){let key=episodeKey(item);if(attemptedResolved.current.has(key))continue;attemptedResolved.current.add(key),notifyInboxRpcFailure(dismissEpisode(item,orch),"dismiss",notifyErrorRef.current)}},[orch]);function resolveVisited(taskId,tabId){resolveEpisodes(availableItemsRef.current,{taskId,tabId}),writeInboxVisit(args.kv,{taskId,tabId,at:Date.now()})}return import_react129.useEffect(()=>{let currentItems=availableItemsRef.current;if(episodeSignature(currentItems)!==availableSignature)return;let selectedId=selectedIdRef.current;if(!selectedId)return;let activeTab=activeTabIdFor(selectedId);if(!activeTab)return;resolveEpisodes(currentItems,{taskId:selectedId,tabId:activeTab})},[availableSignature,resolveEpisodes]),{availableItems:visibleItems,counts,openItem,show:show16,resolveVisited}}function buildIssueChatBackgroundSpawn(input){let base=interactiveEngineCommand(input.vendor),{sessionId}=withPinnedSessionId(base,input.vendor),fresh=initialTabs(),tab={...fresh.tabs[0],sessionId},state={...fresh,tabs:[tab]},spawn3=engineTabSpawnFor(state,tab,base,{live:!1,shell:input.shell??defaultShell(),prompt:input.prompt??issueWorktreePrompt(input.issue,input.api),task:{id:input.taskId,kind:input.kind??"task",vendor:input.vendor,repo:input.repoRoot},worktreePath:input.worktreePath,inlineImages:terminalDrawsKitty()});return{ptyKey:tabPtyKey(input.taskId,tab.id),command:spawn3.command,initialInput:spawn3.initialInput,firstMessage:spawn3.firstMessage,engineBin:spawn3.engineBin,tabsSnapshot:setTabSpawned(state,tab.id,!0)}}function useIssueChat(orch,hooks){let t3=useT();async function enter(taskId){hooks.closeKanban(),hooks.selectTask(taskId),await hooks.enterTask(taskId)}async function finish(request,enterTaskId){if(request.jump)await enter(enterTaskId);else hooks.notifyInfo(t3("kanban.detail.startedBackground",{title:issueChatTaskTitle(request.issue)}))}async function startProjectTab(request,api){let{repoRoot,issue,vendor}=request,main=await orch.ensureMainTask(repoRoot);await orch.mutateIssue(repoRoot,{type:"setStatus",id:issue.id,status:"doing"}).catch((err)=>{console.error("[rove kanban] issue setStatus failed:",err),hooks.notifyError(t3("kanban.statusFailed",{id:String(issue.id),error:userFacingErrorMessage(err)}))});let{task:child}=await orch.spawnChildTask({parentTaskId:main.id,worktree:!1,vendor}),spawn3=buildIssueChatBackgroundSpawn({issue,taskId:child.id,repoRoot,worktreePath:taskCwd(child),vendor,api,kind:child.kind,prompt:issueProjectPrompt(issue,api)});getDefaultPtyRegistry().acquire(spawn3.ptyKey,taskCwd(child),{command:spawn3.command,initialInput:spawn3.initialInput,firstMessage:spawn3.firstMessage,engineBin:spawn3.engineBin}),setTaskTabs2(child.id,spawn3.tabsSnapshot),await finish(request,child.id)}async function startWorktreeTask(request,api){let{repoRoot,issue,vendor}=request;setRepoLastActiveVendor(repoRoot,vendor),addSavedRepo(repoRoot);let task=await orch.createTask({repo:repoRoot,title:issueChatTaskTitle(issue),vendor});await orch.mutateIssue(repoRoot,{type:"link",id:issue.id,taskId:task.id}).catch((err)=>{console.error("[rove kanban] issue link failed:",err),hooks.notifyError(t3("kanban.linkFailed",{id:String(issue.id),error:userFacingErrorMessage(err)}))});let worktreePath=await orch.ensureWorktree(task.id),spawn3=buildIssueChatBackgroundSpawn({issue,taskId:task.id,repoRoot,worktreePath,vendor,api});return getDefaultPtyRegistry().acquire(spawn3.ptyKey,worktreePath,{command:spawn3.command,initialInput:spawn3.initialInput,firstMessage:spawn3.firstMessage,engineBin:spawn3.engineBin}),setTaskTabs2(task.id,spawn3.tabsSnapshot),{task,worktreePath,tab:spawn3.tabsSnapshot.tabs[0]}}async function start(request){try{let api=roveApiInvocation();if(request.placement==="project"){await startProjectTab(request,api);return}let{task,worktreePath,tab}=await startWorktreeTask(request,api);if(request.placement==="projectWorktree"){let main=await orch.ensureMainTask(request.repoRoot);await appendBackgroundEngineTab(main.id,{vendor:request.vendor,sessionId:tab.sessionId??null,ptyTask:{id:task.id,worktree:worktreePath}}),await finish(request,main.id);return}await finish(request,task.id)}catch(err){hooks.notifyError(t3("tasks.toast.issueChatFailed",{error:userFacingErrorMessage(err)}))}}return{start}}var import_react130=__toESM(require_react_production(),1);function usePrCheckNotifier(args){let notif=useLatest(args.notif),t3=useLatest(useT()),prev=import_react130.useRef(new Map);import_react130.useEffect(()=>{let next=new Map;for(let task of args.tasks){let pr=rollupPr(task),state=pr?.checkState;if(state===void 0)continue;next.set(task.id,state);let landed2=checkResolutionNotify(prev.current.get(task.id),state);if(!landed2)continue;notif.current.notify({kind:landed2==="passing"?"done":"error",taskId:task.id,tabId:"",title:t3.current(landed2==="passing"?"tasks.toast.checksPassingTitle":"tasks.toast.checksFailingTitle",{title:task.title}),body:t3.current("tasks.toast.checksResolvedBody",{pr:pr?.number===void 0?"\u2014":`#${pr.number}`,branch:task.branch||"\u2014"})})}prev.current=next},[args.tasks])}import{homedir}from"os";var import_react131=__toESM(require_react_production(),1);function decideScratchAdopt(input){if(!input.repoRoot||!input.harnessLive)return{kind:"stay"};let owners=input.ownerTasks.filter((task)=>task.dir!==""&&!task.sharesWorkspaceOf);if(input.cwd){let cwd=input.cwd,managed=owners.find((task)=>task.kind==="task"&&pathWithin(task.dir,cwd)!==null);if(managed)return{kind:"fold",taskId:managed.id}}for(let kind of["main","dir"]){let owned=owners.find((task)=>task.kind===kind&&(samePath(task.dir,input.cwd)||samePath(task.dir,input.repoRoot)));if(owned)return{kind:"fold",taskId:owned.id}}return{kind:"adopt",repo:input.repoRoot,known:[...input.knownRepos].some((repo)=>samePath(repo,input.repoRoot))}}async function renameHostedSession(from,to){if((process.env.ROVE_TERMINAL_BACKEND??"hosted")!=="hosted")return!1;try{return(await(await getSharedPtyClient()).request("pty.rename",{from,to})).renamed===!0}catch{return!1}}var tabNumber=(id)=>Number(/^tab-(\d+)$/.exec(id)?.[1]??0);async function foldScratchShell(io,scratchTaskId,targetTaskId){let rename=io.rename??renameHostedSession,scratchTabIds=(knownTaskTabs(io.kv,scratchTaskId)?.tabs??[{id:"tab-1"}]).map((tab)=>tab.id),reserved=await(io.reserve??reserveTabOrdinals)(targetTaskId,scratchTabIds.length*2).catch(()=>null),fallback=1+(knownTaskTabs(io.kv,targetTaskId)?.tabs??[]).reduce((max,tab)=>Math.max(max,tabNumber(tab.id)),0),nextId=()=>`tab-${reserved?.shift()??fallback++}`,folded=[];for(let tabId of scratchTabIds){let from=tabPtyKey(scratchTaskId,tabId),to=nextId(),ok=await rename(from,tabPtyKey(targetTaskId,to));if(!ok)to=nextId(),ok=await rename(from,tabPtyKey(targetTaskId,to));if(!ok)continue;folded.push(to)}if(folded.length===0)return null;return adoptTaskTabs(io.kv,targetTaskId,folded),{activeTabId:folded[0]}}var POLL_MS5=5000;function scratchOwnerTasks(tasks2){return tasks2.filter((task)=>!task.deletion&&task.scratch!==!0&&task.worktreePath!=="").map((task)=>({id:task.id,kind:task.kind??"task",dir:canonPath(task.worktreePath),...task.sharesWorkspaceOf?{sharesWorkspaceOf:task.sharesWorkspaceOf}:{}}))}function useScratchAdopt(deps){let{tasks:tasks2,orchestrator,kv,notifyInfo}=deps,onFoldRef=useLatest(deps.onFold),enabled=deps.enabled??!0,scratchIds=tasks2.filter((t3)=>t3.kind==="dir"&&t3.scratch===!0).map((t3)=>t3.id).join(",");import_react131.useEffect(()=>{if(!enabled||scratchIds==="")return;let cancelled=!1,inFlight=new Set,tick3=async()=>{let scratch=tasks2.filter((t3)=>t3.kind==="dir"&&t3.scratch===!0);if(scratch.length===0)return;let known=new Set([...getSavedRepos(),...tasks2.map((t3)=>t3.repo)]),owners=scratchOwnerTasks(tasks2),registry=getDefaultPtyRegistry(),liveEngines=getDefaultLiveEngines();for(let task of scratch){if(inFlight.has(task.id))continue;let key=tabPtyKey(task.id,"tab-1"),pid=registry.get(key)?.shellPid??null;if(pid===null||pid===void 0)continue;if(!liveEngines.get(key))continue;let rawCwd=await processCwd(pid);if(cancelled||!rawCwd)continue;let cwd=canonPath(rawCwd),repoRoot=canonPath(resolveMainRepoRoot(cwd)),decision=decideScratchAdopt({cwd,repoRoot:isGitRepo(repoRoot)?repoRoot:null,harnessLive:!0,knownRepos:known,ownerTasks:owners});if(cancelled||decision.kind==="stay")continue;inFlight.add(task.id);try{if(decision.kind==="fold"){let folded=await foldScratchShell({kv},task.id,decision.taskId);if(!folded)throw Error("fold did not move any session");await onFoldRef.current(task.id,decision.taskId,folded.activeTabId);continue}if(await orchestrator.adoptScratchRepo(task.id,decision.repo),!decision.known)notifyInfo(t("tasks.toast.scratchAdopted",{repo:repoBasename(decision.repo)}))}catch{inFlight.delete(task.id)}}};tick3();let timer3=setInterval(()=>void tick3(),POLL_MS5);return()=>{cancelled=!0,clearInterval(timer3)}},[enabled,scratchIds,orchestrator,kv,notifyInfo,tasks2])}var scratchTeardowns=new Set;function useScratchShell(deps){let{orchestrator,enterTask,forgetTaskTabs:forgetTaskTabs2,notifyError}=deps;useScratchAdopt({tasks:deps.tasks,orchestrator,kv:deps.kv,notifyInfo:deps.notifyInfo,onFold:async(scratchTaskId,targetTaskId,tabId)=>{if(deps.selectedId()===scratchTaskId)deps.selectTask(targetTaskId),requestTabActivation(targetTaskId,tabId);await orchestrator.deleteTask(scratchTaskId),forgetTaskTabs2(scratchTaskId)}});let openScratchShell=(vendor,prompt)=>{orchestrator.openDirectoryTask({dir:homedir(),scratch:!0,...vendor?{vendor}:{}}).then((task)=>{if(vendor)engineScratchTasks.add(task.id);if(vendor&&prompt)deps.seedPrompt(task.id,prompt);enterTask(task.id)}).catch((err)=>notifyError(t("tasks.toast.scratchOpenFailed",{message:userFacingErrorMessage(err)})))};return{openScratchShell,onScratchExit:(taskId)=>{if(scratchTeardowns.has(taskId))return;scratchTeardowns.add(taskId),(async()=>{try{await orchestrator.deleteTask(taskId),forgetTaskTabs2(taskId),await finishDeletedTaskFlow({orch:orchestrator,tasks:deps.tasks,taskId,logger:console,logPrefix:"[rove scratch]",updateActiveTask:!0})}catch(err){notifyError(t("tasks.toast.scratchCloseFailed",{message:userFacingErrorMessage(err)}))}})()},reportProblem:()=>openScratchShell(getGlobalDefaultVendor()??DEFAULT_TASK_VENDOR,t("help.reportPrompt",{logPath:defaultDaemonLogPath()}))}}var import_react132=__toESM(require_react_production(),1);function activationErrorMessage(error,translate){let message=errorMessage(error);if(message.includes(TASK_DELETING_CODE))return translate("tasks.toast.worktreeErrorDeleting");if(/not a git repository|does not appear to be a git repo/i.test(message))return translate("tasks.toast.worktreeErrorNotGit");return translate("tasks.toast.worktreeErrorGeneric",{message:userFacingErrorMessage(error)})}async function activateWorkspaceTask(opts,id){let task=opts.getTask(id);if(task?.deletion)return opts.reportError(new TaskDeletingError(id)),!1;if(task?.origin&&task.origin.machineId!=="local")return opts.selectTask(id),opts.focusWorkspace(),!0;if(!task?.worktreePath)try{await opts.ensureWorktree(id)}catch(error){return opts.reportError(error),!1}if(opts.isCurrent?.()===!1)return!1;return opts.selectTask(id),opts.focusWorkspace(),!0}function firstSelectableTask(tasks2,activeId,lastActiveId){let alive=(id)=>id?tasks2.find((task)=>task.id===id&&!task.deletion):void 0,active=alive(activeId)??alive(lastActiveId);if(active)return active;let live=tasks2.filter((task)=>!task.deletion),newest=(pool)=>pool.length>0?pool.reduce((best,task)=>task.updatedAt>best.updatedAt?task:best):void 0;return newest(live.filter((task)=>task.routine===void 0))??newest(live)??tasks2.find((task)=>!task.deletion)}function useWorkspaceSelection(args){let{orch,tasks:tasks2,activeTaskId,kv}=args,t3=useT(),[selectedId,setSelectedId]=import_react132.useState(()=>orch.activeTaskSignal()()??readLastActiveTaskId()),focusRestoredRef=import_react132.useRef(!1),userPickedRef=import_react132.useRef(!1),bootFocusRef=import_react132.useRef(!1),liveSelectedRef=import_react132.useRef(null);import_react132.useEffect(()=>{if(!focusRestoredRef.current&&activeTaskId&&tasks2.some((task)=>task.id===activeTaskId)){if(focusRestoredRef.current=!0,!userPickedRef.current&&selectedId!==activeTaskId){setSelectedId(activeTaskId);return}}if(!bootFocusRef.current&&!userPickedRef.current&&selectedId&&tasks2.some((task)=>task.id===selectedId))bootFocusRef.current=!0,args.focusWorkspace();let selected=selectedId?tasks2.find((task)=>task.id===selectedId):void 0,wasLive=selectedId!==null&&liveSelectedRef.current===selectedId;if(liveSelectedRef.current=selected&&selected.archived!==!0&&!selected.deletion?selectedId:null,wasLive&&selected?.archived===!0){setSelectedId(firstSelectableTask(tasks2.filter((task)=>task.archived!==!0),null)?.id??null);return}if(selectedId&&tasks2.some((task)=>task.id===selectedId&&!task.deletion))return;setSelectedId(firstSelectableTask(tasks2,activeTaskId,readLastActiveTaskId())?.id??null)},[tasks2,activeTaskId,selectedId,args.focusWorkspace]);let notifyWorktreeGoneRef=useLatest(args.notifyWorktreeGone),liveTaskIdsRef=import_react132.useRef(new Set),worktreePathsRef=import_react132.useRef(new Map);import_react132.useEffect(()=>{let next=new Set(tasks2.filter((task)=>!task.deletion).map((task)=>task.id)),registry=getDefaultPtyRegistry(),aliased=aliasedKeys(tasks2.filter((task)=>!task.deletion));for(let id of liveTaskIdsRef.current){if(next.has(id))continue;registry.releaseWhere((key)=>(key===id||key.startsWith(`${id}::`))&&!aliased.some((base)=>isUnderKey(key,base)))}liveTaskIdsRef.current=next;let paths=new Map;for(let task of tasks2)paths.set(task.id,task.worktreePath);for(let[id,prevPath]of worktreePathsRef.current)if(paths.get(id)===""&&prevPath!==""){let closed=knownTaskTabs(kv,id)?.tabs.length??0;registry.releaseWhere((key)=>key===id||key.startsWith(`${id}::`)),forgetTaskTabs(kv,id);let task=tasks2.find((candidate)=>candidate.id===id);notifyWorktreeGoneRef.current?.({taskId:id,title:task?.title??id,branch:task?.branch??"",closed})}worktreePathsRef.current=paths},[tasks2,kv]);function selectTask(id){if(userPickedRef.current=!0,selectedId===id){if(orch.activeTaskSignal()()!==id)orch.setActiveTask(id).catch((error)=>console.error("[rove workspace] setActiveTask failed:",error));return}setSelectedId(id),orch.setActiveTask(id).catch((error)=>console.error("[rove workspace] setActiveTask failed:",error));let kind=tasks2.find((task)=>task.id===id)?.kind==="main"?"project.opened":"task.opened";orch.reportUiEvent(kind,id)}let activationGenerationRef=import_react132.useRef(0);async function activateTask(id){let generation=++activationGenerationRef.current;reviveEmptiedTabs(kv,id,defaultShell()),await activateWorkspaceTask({getTask:(taskId)=>tasks2.find((task)=>task.id===taskId),ensureWorktree:(taskId)=>orch.ensureWorktree(taskId),selectTask,focusWorkspace:args.focusWorkspace,reportError:(error)=>{console.error("[rove workspace] task.ensureWorktree failed:",error),args.notifyError?.(activationErrorMessage(error,t3))},isCurrent:()=>activationGenerationRef.current===generation},id)}let selectedTask=selectedId?tasks2.find((task)=>task.id===selectedId):void 0;return{selectedId,setSelectedId,selectedTask,selectTask,activateTask}}var import_react133=__toESM(require_react_production(),1);function useZenMode(deps){let{kv,focus}=deps,[zen,setZen]=import_react133.useState(()=>kv.get(ZEN_ACTIVE_KEY,ZEN_DEFAULT)===!0);function toggleZen(){let next=!zen;if(setZen(next),kv.set(ZEN_ACTIVE_KEY,next),next)focus.setFocused("workspace")}return import_react133.useEffect(()=>{if(focus.focused==="files")setZen(!1)},[focus.focused]),{zen,toggleZen}}function WorkspaceRoot(props){let{theme}=useTheme(),inactiveBorder=theme.borderActive,dialog=useDialog(),kv=useKV(),focus=useFocus(),dims=useTerminalSize(),sidebarWidth=useSidebarWidth(),[sidebarCollapsed]=useSidebarCollapsed(),sidebarResize=useSidebarResizeGesture({width:sidebarWidth.width,onResize:sidebarWidth.pin,onReset:sidebarWidth.reset}),renderer=useRenderer(),notif=useNotifications(),orch=props.orchestrator;useDaemonNotices(orch,notif.notify,dialog);let{tasks:tasks2,activeTaskId,engineState,engineLifecycle,engineTabState,inboxItems,taskJobs,rowTokens,worktreeChanges:worktreeChanges2}=useDaemonState(orch),[searchActive,setSearchActive]=import_react135.useState(!1),t3=useT(),{notifyError,notifyInfo,notifyNeedsInput,notifyWorktreeGone}=useHostNotifiers({notif,t:t3,selectedId:()=>selectedId}),{selectedId,setSelectedId,selectedTask,selectTask,activateTask}=useWorkspaceSelection({orch,tasks:tasks2,activeTaskId,focusWorkspace:()=>focus.setFocused("workspace"),kv,notifyWorktreeGone,notifyError}),worktree=selectedTask?.worktreePath||null,workingFlow=selectedId!==null&&engineState?.get(selectedId)?.state==="running"&&normalizeWorkingBorder(kv.get(WORKING_BORDER_KEY,DEFAULT_WORKING_BORDER))==="flow",breath=useSpinnerFrame(workingFlow),taskInk=useTaskColor(selectedId),{sortMode,toggleSortMode,moveMode,setMoveMode,onLocalMergeRequest}=useSidebarHostState({kv,tasks:tasks2,focusSidebar:()=>focus.setFocused("sidebar"),notify:notifyInfo}),inbox=useInboxHost({orchestrator:orch,items:inboxItems,tasks:tasks2,kv,dialog,selectedId,selectTask,openAutomations:()=>pages.openPage("automations"),focusWorkspace:()=>focus.setFocused("workspace"),notifyError}),{jumpToNextAttention}=useAttention({tasks:tasks2,engineState,engineTabState,inboxItems:inbox.availableItems,selectedId,kv,notif,openAttention:inbox.openItem,noTasksMessage:t3("workspace.attention.none")});usePrCheckNotifier({tasks:tasks2,notif});let taskActions=useWorkspaceTaskActions({orchestrator:orch,tasks:()=>tasks2,dialog,notifyError,notifyInfo,notifyNeedsInput,t:t3,selectedId:()=>selectedId,setSelectedId,selectedTask:()=>selectedTask,activateTask,forgetTaskTabs:(id)=>forgetTaskTabs(kv,id),closeTaskTabs:(id)=>closeAllTaskTabs(kv,id),startWithPrompt:(repo,start)=>quickFork.onQuickFork(repo,{...start,attachments:[],attempts:1})}),editor=useEditorHandles({orchestrator:orch,worktree,selectedId,focus,notifyError,activateTask}),quickFork=useQuickFork(orch,{selectTask:setSelectedId,enterTask:activateTask,notifyError,notify:notifyInfo,t:t3}),scratch=useScratchShell({orchestrator:orch,tasks:tasks2,kv,selectedId:()=>selectedId,selectTask:setSelectedId,enterTask:(id)=>void activateTask(id),forgetTaskTabs:(id)=>forgetTaskTabs(kv,id),notifyError,notifyInfo,seedPrompt:quickFork.seedPrompt}),{zen,toggleZen}=useZenMode({kv,focus}),filesActions=useFilesPaneActions({onOpenFile:(relPath)=>void editor.onOpenFile(relPath),onOpenDiff:editor.onOpenDiff,onMention:editor.onMention,onZenToggle:toggleZen,onCreatePR:()=>void editor.onCreatePR()});import_react135.useEffect(()=>{return setUiEventReporter((kind,taskId,detail)=>orch.reportUiEvent(kind,taskId,detail)),()=>setUiEventReporter(null)},[orch]),useTabsSync(orch.tabs,orch.connectionStateSignal()),useRowStatusSync(orch.rowStatus,orch.connectionStateSignal());let pages=useHostPagesState(focus,props);useWhatsNewDialog(pages.whatsNewFrom,pages.closeWhatsNew),useWelcomeDialog(pages.welcome,pages.closeWelcome);let selectedTabId=selectedId===null?null:activeTabIdFor(selectedId),issueChat=useIssueChat(orch,{selectTask:setSelectedId,enterTask:activateTask,closeKanban:pages.closePage,notifyError,notifyInfo}),pageRender=useHostPagesRender({orchestrator:orch,pages,focus,dialog,kv,dims,selectedTask,activeTaskId,tasks:tasks2,engineState,activateTask}),openTaskWorktree=(id)=>openTaskWorktreeFor(id,{tasks:tasks2,ensureWorktree:orch.ensureWorktree.bind(orch),notifyError}),cursorTaskIdRef=import_react135.useRef(()=>null),banner=useHostBanner(orch,dims.width),refreshRove=()=>{selfRefreshAction({orchestrator:orch,renderer,confirm:()=>DialogConfirm.show(dialog,t3("update.refresh.confirmTitle"),t3("update.refresh.confirmBody"),t3("common.cancel"),t3("update.refresh.confirmLabel")).then((ok)=>ok===!0),notifyError,t:t3},banner.refresh.inputs)};useWorkspaceKeybindings({focus,dialog,pages,filesPaneVisible:!zen&&pages.nav==="terminal"&&pageRender.showSidebar&&pageRender.showContent,searchActive,selectedId,cursorTaskId:()=>cursorTaskIdRef.current(),openTaskWorktree,createTask:()=>void taskActions.createTask(),renameBranch:(id)=>void taskActions.renameBranch(id),cycleVendor:(id)=>void taskActions.cycleVendor(id),toggleZen,jumpToNextAttention,openInbox:inbox.show,reportProblem:scratch.reportProblem,paletteSearch:{orchestrator:orch,tasks:tasks2,openTask:openTaskOnTab(pages.closePage,activateTask)},createPR:()=>void editor.onCreatePR(),createPRFor:(id)=>{requestCreatePR(id),activateTask(id)},fixChecksFor:editor.onFixChecks,syncBaseFor:(id)=>void taskActions.syncBase(id),enterMoveMode:()=>{let target=selectedId??tasks2[0]?.id;if(!target)return;focus.setFocused("sidebar"),setSelectedId(String(target)),setMoveMode(!0)},toggleSortMode,refresh:{available:banner.refresh.available,run:refreshRove}});let activePane=dialog.stack.length>0?null:focus.focused,fullWindow=pageRender.settingsPage??pageRender.fullWindowPage,contentPageType=import_react135.isValidElement(pageRender.contentPage)?pageRender.contentPage.type:null;if(fullWindow)return $jsx(FullWindowPage,{banner:banner.element,background:theme.background,children:$jsx(PaneErrorBoundary,{region:"page",children:fullWindow})});return $jsxs(WorkspaceFrame,{orchestrator:orch,onOpenSettings:()=>pages.openSettings(),banner:banner.element,activeTaskId:selectedId,activeTabId:selectedTabId,onPaneDrag:sidebarResize.onPaneDrag,onPaneRelease:sidebarResize.onPaneRelease,children:[pageRender.showSidebar?$jsx(RenderProfiler,{id:"sidebar",children:$jsx(PaneErrorBoundary,{region:"sidebar",width:pageRender.showContent?sidebarWidth.width:dims.width,children:$jsx(HostSidebarMount,{terminalWidth:dims.width,showContent:pageRender.showContent,recentTask:pageRender.recentTask,tasks:tasks2,selectedId,selectTask,activateTask,daemon:{engineState,engineTabState,engineLifecycle,taskJobs,rowTokens,worktreeChanges:worktreeChanges2},actions:taskActions,pages,focus,inbox,update:banner.update,onFixChecks:editor.onFixChecks,onResolveConflicts:editor.onResolveConflicts,runAgain:quickFork.runAgain,openScratch:scratch.openScratchShell,activePane,zen,toggleZen,sortMode,moveMode,exitMoveMode:()=>setMoveMode(!1),onLocalMergeRequest,onSearchActiveChange:setSearchActive,cursorTaskIdRef,openTaskWorktree,t:t3})})}):null,pageRender.showContent?$jsxs("box",{flexGrow:1,flexShrink:1,borderStyle:"rounded",borderColor:focus.focused==="workspace"?theme.focusAccent:inactiveBorder,renderAfter:workingFlow?runningPaneFlow(taskInk??theme.focusAccent,inactiveBorder,focus.focused==="workspace",breath,taskInk?TASK_PARTNER_HUE_DEG:void 0):void 0,title:workingFlow&&selectedTask?runningPaneTitle(selectedTask.title,t3("workspace.inbox.state.running")):void 0,onMouseUp:()=>focus.setFocused("workspace"),children:[isNarrowWidth(dims.width)?$jsx(NarrowBackBar,{onBack:()=>focus.setFocused("sidebar")}):null,$jsx(PaneErrorBoundary,{region:"workspace",resetKeys:[selectedId,contentPageType],children:pageRender.contentPage?$jsx(PageServicesProvider,{value:{startIssueChat:issueChat.start},children:pageRender.contentPage}):$jsx(RenderProfiler,{id:"workspace",children:$jsx(ShowWorkspace,{task:selectedTask,worktree,orchestrator:orch,focused:activePane==="workspace",onRequestFocus:()=>focus.setFocused("workspace"),onEditorTabReady:editor.onEditorTabReady,onEngineSendReady:editor.onEngineSendReady,onEnginePasteReady:editor.onEnginePasteReady,onDiffTabReady:editor.onDiffTabReady,onSpawnChild:quickFork.onSpawnChild,onQuickFork:quickFork.onQuickFork,initialPrompt:quickFork.initialPromptFor(selectedTask?.id),onTabVisited:inbox.resolveVisited,onScratchExit:scratch.onScratchExit,onOpenScratch:scratch.openScratchShell,onEngineChosen:taskActions.setVendor,onOpenSettings:pages.openSettings})})})]}):null,!zen&&pageRender.contentPage==null&&pageRender.showSidebar&&pageRender.showContent?$jsx(HostFilesPane,{sidebarWidth:sidebarWidth.width,worktree,prBaseRef:selectedTask?.prStatus?.baseRef,focused:activePane==="files",actions:filesActions,taskKind:selectedTask?.kind,remoteHost:selectedTask?.origin&&selectedTask.origin.machineId!=="local"?selectedTask.origin.hostLabel:void 0,remote:selectedTask?.origin&&selectedTask.origin.machineId!=="local"&&!selectedTask.origin.stale?{machine:selectedTask.origin.machineId,taskId:String(selectedTask.id)}:void 0}):null,$jsx(ToastOverlay,{}),$jsx(PrefixHud,{left:1,width:sidebarWidth.width-2}),pageRender.showSidebar&&pageRender.showContent&&!sidebarCollapsed?$jsx(SidebarResizeGrip,{width:sidebarWidth.width,onGripDown:sidebarResize.onGripDown}):null]})}async function startWorkspaceHost(opts={}){await bootPaneHost({logContext:"workspace",providers:{kv:!0,focus:!0,notifications:!0},setup:async()=>{let cellPixelSize=await queryCellPixelSize({stdin:process.stdin,stdout:process.stdout}),client=await connectOrStartDaemon(),channels=CHANNEL_NAMES.filter((name)=>name!=="state"),orchestrator=new RemoteOrchestrator(client,{role:"gui",cellPixelSize,channels});await orchestrator.init(),process.env.ROVE_DAEMON_SOCKET_PATH=client.socketPath,installTerminalGraphics(createTerminalGraphics({env:process.env,stdoutIsTTY:process.stdout.isTTY===!0,cellPixelSize,write:(data)=>orchestrator.writeGraphics(data)}));let{MachineFeed}=await import("./chunk-55e3pt18.js"),{setMachineHub}=await import("./chunk-wv6d96t6.js"),machines=new MachineFeed(orchestrator);setMachineHub(machines);let stopRemoteStatus=followRemoteActivity(machines.liveSignal());registerCorePages();let stopModsPage=registerModsPage(orchestrator);registerBundledPlugins();let stopBundledPlugins=followBundledPlugins();return loadPluginPages(),{root:()=>$jsx(WorkspaceRoot,{orchestrator,whatsNewFrom:opts.whatsNewFrom??null,welcome:opts.welcome??null}),onDestroy:()=>{stopBundledPlugins(),stopModsPage(),stopRemoteStatus(),setMachineHub(null),machines.dispose(),orchestrator.dispose(),installTerminalGraphics(null),getDefaultPtyRegistry().detachAll()}}}})}export{startWorkspaceHost};