@sma1lboy/rove 0.9.193 → 0.9.195

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 (33) hide show
  1. package/dist/cli/{chunk-nk7gcg4y.js → chunk-0fe2k0jx.js} +1 -1
  2. package/dist/cli/{chunk-vrbn3nxt.js → chunk-0pch42yn.js} +1 -1
  3. package/dist/cli/{chunk-4zrw082j.js → chunk-1c45wn05.js} +1 -1
  4. package/dist/cli/{chunk-3brfcnpk.js → chunk-1z51dyjr.js} +1 -1
  5. package/dist/cli/{chunk-6pgztztk.js → chunk-2sgkw3yw.js} +1 -1
  6. package/dist/cli/{chunk-2fcxwa4k.js → chunk-4c0v2r51.js} +2 -2
  7. package/dist/cli/{chunk-k18qb13b.js → chunk-5rxf13e9.js} +1 -1
  8. package/dist/cli/{chunk-ak7117gm.js → chunk-7yb0xh67.js} +2 -2
  9. package/dist/cli/{chunk-0yfmy0rm.js → chunk-832nzvm5.js} +1 -1
  10. package/dist/cli/{chunk-nsks6346.js → chunk-8m10tjsv.js} +1 -1
  11. package/dist/cli/{chunk-bm4e237e.js → chunk-8zwxh0n4.js} +1 -1
  12. package/dist/cli/{chunk-hw4429zr.js → chunk-925e0rd1.js} +1 -1
  13. package/dist/cli/{chunk-b34g4xzj.js → chunk-b1esazj4.js} +2 -2
  14. package/dist/cli/{chunk-e15fwx61.js → chunk-c7hjesva.js} +1 -1
  15. package/dist/cli/{chunk-ejzb5q7e.js → chunk-dsarke4k.js} +5 -5
  16. package/dist/cli/{chunk-4wq5v9a3.js → chunk-f3fk95gv.js} +2 -2
  17. package/dist/cli/{chunk-52tjqcxt.js → chunk-fenh1bkh.js} +1 -1
  18. package/dist/cli/{chunk-xqhcpdj4.js → chunk-gchf8f4p.js} +1 -1
  19. package/dist/cli/{chunk-jmw7vvbc.js → chunk-hk8xx4k0.js} +1 -1
  20. package/dist/cli/{chunk-944pedh5.js → chunk-jfjcz976.js} +1 -1
  21. package/dist/cli/{chunk-0g0kj2fw.js → chunk-mcd4f2jr.js} +1 -1
  22. package/dist/cli/{chunk-sc0xyg6n.js → chunk-nt6smaf4.js} +1 -1
  23. package/dist/cli/{chunk-gsr2dnqc.js → chunk-pq4263qt.js} +1 -1
  24. package/dist/cli/{chunk-8sw5skks.js → chunk-qeypyf57.js} +1 -1
  25. package/dist/cli/{chunk-00zwq5t0.js → chunk-s5qy4qxf.js} +1 -1
  26. package/dist/cli/{chunk-rwf7xfvh.js → chunk-t7py1sa4.js} +1 -1
  27. package/dist/cli/{chunk-xw5y8gw3.js → chunk-taxanedr.js} +1 -1
  28. package/dist/cli/{chunk-mtt5b8t3.js → chunk-whep4jqb.js} +1 -1
  29. package/dist/cli/{chunk-8vbae93m.js → chunk-wvj68g1e.js} +1 -1
  30. package/dist/cli/index.js +3 -3
  31. package/dist/cli/kobe.js +1 -1
  32. package/dist/cli/rove.js +1 -1
  33. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{useMachineRows,useMergedTasks}from"./chunk-68jcangn.js";import{readOutdatedCache}from"./chunk-fgn4qk9p.js";import{listPaneLaunches}from"./chunk-cckrwr2v.js";import{formatBytes}from"./chunk-my20q579.js";import{DEFAULT_EDITOR_KIND,EDITOR_CUSTOM_KEY,EDITOR_KINDS,EDITOR_KIND_KEY,normalizeEditorKind,resolveEditorLaunch}from"./chunk-g8ap5366.js";import{embeddedTerminalEnv}from"./chunk-ef39ym8f.js";import{UpdatePage,openWithSystemViewer,resolveRowSelectionChrome,spawnDetached}from"./chunk-8sw5skks.js";import"./chunk-e15fwx61.js";import{deriveTitleFromSessionId,startTaskSessionWithPromptAdapter}from"./chunk-kmsnrf9m.js";import{canonPath,checkResolutionNotify}from"./chunk-grdk12w7.js";import{readLastActiveTaskId}from"./chunk-2kb4z64z.js";import{ISSUE_STATUSES,isValidCron,nextCronAfter,tightenPluginPermissions}from"./chunk-9fc0j6ng.js";import"./chunk-xd9kw4hh.js";import"./chunk-xsrcwcjc.js";import{reloadPluginEngines}from"./chunk-c8xm2s8h.js";import{submitFeedback}from"./chunk-nsks6346.js";import"./chunk-xb9b93ts.js";import{DIRTY_WORKTREE_CODE,PROJECT_SIBLING_BASE,TASK_DELETING_CODE,TaskDeletingError,WORKTREE_BASE_CUSTOM_KEY,worktreeBaseKindOf}from"./chunk-ztwz2465.js";import{currentPluginPlatform,loadPluginRegistry,parsePluginManifest,pluginConfigDir,pluginLogPath,pluginManifestPath,qualifiedActionId,readPluginManifest,savePluginRegistry,supportsPlatform}from"./chunk-bq9shn2d.js";import{PROJECT_DIR_TOKEN,WORKTREE_BASE_KEY,hasProjectDirToken,normalizeWorktreeBase}from"./chunk-63wmhbqs.js";import{ulid}from"./chunk-qkehg2c1.js";import{approxCellWidth,approxCharCells,charWidth,displayWidth,padEndCells}from"./chunk-dvcb6mk4.js";import{addTab,closeActiveTab,closeTab,collapseSplit,cycleLeaf,cycleTab,engineTabSpawnFor,expandHome,filterSubdirs,findEditorTab,forgetTaskTabsSnapshot,hasEngineLeaf,initialShellTabs,initialSplit,initialTabs,isTabSplit,joinDrill,joinPicked,leaves,listSubdirs,moveTab,openCommandTab,openContentTab,openEditorTab,pathLeaf,recycleTabs,rehydrateTabs,removeLeaf,renameActiveTab,renameLeaf,reopenTabs,selectTab,setTabAutoTitle,setTabEngineCommand,setTabForkFrom,setTabInitialPrompt,setTabLastTitle,setTabLiveVendor,setTabSessionId,setTabSpawned,setTabSplit,setTabTitle,shellIdentityInput,splitActive,splitLeafNames,splitLeafPtyKey,splitPathForDirSuggest,stripTrailingSlash,sweepOrphanTabsSnapshots,tabCwdFor,tabExitAction,tabPtyKey,tabPtyKeyFor,tabTitle,tabTitleStable,terminalTabsKey,visibleNativeStatus}from"./chunk-6dgyb7sq.js";import{AUTO_STATUS_KEY,DISPATCHER_KEY,hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp}from"./chunk-3dv9vdpj.js";import{execHostForWorktreePath,remoteKeyForRepo}from"./chunk-dg8bsyb9.js";import"./chunk-2apszxn2.js";import"./chunk-g2advs8t.js";import{ensurePtyHostReachable}from"./chunk-gsy8xfh6.js";import"./chunk-rcyasw34.js";import{DEFAULT_TERMINAL_COLORS,formatDefaultColorReply,parseTerminalDefaultColors}from"./chunk-7q67dz4c.js";import{readFirstNonEmptyRepoFile}from"./chunk-v3fqkype.js";import"./chunk-hape5vwj.js";import{resolveLoginShell}from"./chunk-b99tf0jr.js";import"./chunk-w25b7xxz.js";import{getGlobalDefaultVendor,resolvePreferredVendor,setGlobalDefaultVendor,setRepoLastActiveVendor}from"./chunk-j5przd8x.js";import{matchPathGlob}from"./chunk-kg11c1py.js";import{KEY_HINTS_ENABLED_KEY,PANE_HINT_USED_KEYS,grammarHelpSections,guideCategory,keyHintsEnabled,keyHintsToggleOn,legendCap,paneHintTokens,paneHintVisible,scopeCategory,statusHintTokens,toggleKeyHints}from"./chunk-jmw7vvbc.js";import{$Fragment,$jsx,$jsxs,DEFAULT_PREFIX_CONFIGURATION,DEFAULT_SOUND_VOLUME,DIRECT_GUIDE_PREFIX_ACTION_ID,FIXED_BINDING_IDS,KobeKeymap,PREFIX_GUIDE_DELAY_MS,PREFIX_HUD_TTL_MS,SOUND_VOLUME_KEY,armPrefixFromCurrentStack,attentionEdges,attentionKindFor,bindByIds,bootPaneHost,chipAttentionKind,currentBindingReachability,currentPrefixConfiguration,defaultChordsOf,findBinding,formatChord,hostTargetFps,imeAnchorController,invokeArmedPrefixActionFromCurrentStack,isKittyModifierKeyEvent,isNarrowWidth,keymapVersion,modalActive,narrowSurface,nextSoundVolume,normalizeSoundVolume,pageCloseBindings,pluginKeybindings,prefixAction,prefixHudClock,prefixHudState,redrawScreen,reloadUserKeybindings,shortcutCaption,showDialog,subscribeKeymapVersion,taskJumpDigit,useAccessor,useBindingStackVersion,useBindings,useDialog,useDialogPaddingX,useFocus,useKV,useLatest,useNotifications,useOptionalDialog,useOptionalFocus,useOptionalKV,useOptionalNotifications,usePaste,useRenderer,useT,useTerminalDimensions,useTheme,userKeybindingsReport}from"./chunk-0g0kj2fw.js";import{RemoteOrchestrator}from"./chunk-6pgztztk.js";import{require_react_production}from"./chunk-a82ec09z.js";import{parseNumstatRows,parsePorcelain,pickPushedChanges,sameWorktreeChanges}from"./chunk-k6nxyxyh.js";import{parsePorcelainRows,unquoteGitPath}from"./chunk-h4n8ffqy.js";import{READ_ONLY_GIT_ENV,readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{FOCUS_ACCENT_SLOTS,LOCALE_KEY}from"./chunk-072m1jjt.js";import"./chunk-z7c6nap0.js";import{tildify}from"./chunk-fczqwtmq.js";import{connectOrStartDaemon}from"./chunk-te8g5azg.js";import"./chunk-y13681dw.js";import{KobeDaemonClient}from"./chunk-b5mbpv97.js";import{attentionInboxItemKey,automationRunNeedsAttention}from"./chunk-re5ke4fz.js";import"./chunk-mnqxgvyb.js";import"./chunk-764bsyb0.js";import{detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-5mbv38x2.js";import{ENGINE_PROTOCOLS,engineCanFork,engineLaunchArgv,engineProtocolKey,getEngineProtocol,pickUnclaimedSessionId,protocolEntry,withPinnedSessionId}from"./chunk-00t0rc5r.js";import{defaultEngineCommand,engineCommandKey,engineDisplayName,engineNameKey,humanizeSlug,interactiveEngineCommand,kobeApiInvocation}from"./chunk-yfkr1fem.js";import{currentLang,intlLocale,setLocaleLang,t,tKeys}from"./chunk-x2c7ehve.js";import{LOCALES}from"./chunk-22jgttzv.js";import{createStateCell}from"./chunk-sdyzxayr.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-qnj7vk5g.js";import{engineEntry,engineSessionIdFromTitle,engineTitleTurnHint,getCapabilities,stripEngineStatusPrefix}from"./chunk-kav5p2qb.js";import{availableEngineIds,installedEngineIds}from"./chunk-kx3kydwv.js";import"./chunk-w7zv47mp.js";import{maybeStartScheduledRun,spawnCapture}from"./chunk-khj0apc7.js";import{CURRENT_VERSION}from"./chunk-nk7gcg4y.js";import"./chunk-jvxh93nz.js";import{errorMessage,userFacingErrorMessage}from"./chunk-2brn8e1y.js";import{roveCliInvocation}from"./chunk-r92b9j14.js";import"./chunk-aep7gvh4.js";import"./chunk-7kysxgbq.js";import"./chunk-krpsfcda.js";import{DEFAULT_TASK_VENDOR,TASK_STATUSES}from"./chunk-xy8be792.js";import{addSavedRepo,getSavedRepos,isGitRepo,isRemoteRepoKey,resolveMainRepoRoot}from"./chunk-9ydhv2zb.js";import{recordSpawn}from"./chunk-40dgv828.js";import{loadStateFile}from"./chunk-3jh78dmc.js";import"./chunk-ddcxvbme.js";import{logClientError}from"./chunk-0q6h4vt4.js";import"./chunk-pw6yfj10.js";import{ALL_VENDORS,isBuiltinVendor,nextVendorWithin,prevVendorWithin}from"./chunk-05jej26n.js";import"./chunk-81p6mm0p.js";import{isDev,promptAttachmentsDir,roveStateDir}from"./chunk-q5jhy3t8.js";import"./chunk-t915by6w.js";import{pathIdentity,pathSyntax,pathWithin,samePath}from"./chunk-f10n6063.js";import{OWNER_ONLY_DIR_MODE,OWNER_ONLY_FILE_MODE}from"./chunk-9prawccj.js";import{defaultDaemonSocketPath}from"./chunk-8cjr5ypt.js";import{activeCliName}from"./chunk-00ehck55.js";import"./chunk-fxs82dsx.js";import{ROVE_PRODUCT_NAME}from"./chunk-sb0ns0c7.js";import{readRoveEnv}from"./chunk-hq4b3fca.js";import"./chunk-pxk2c2vj.js";import{__commonJS,__require,__toESM}from"./chunk-wqfp8d9w.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{useMachineRows,useMergedTasks}from"./chunk-68jcangn.js";import{readOutdatedCache}from"./chunk-fgn4qk9p.js";import{listPaneLaunches}from"./chunk-cckrwr2v.js";import{formatBytes}from"./chunk-my20q579.js";import{DEFAULT_EDITOR_KIND,EDITOR_CUSTOM_KEY,EDITOR_KINDS,EDITOR_KIND_KEY,normalizeEditorKind,resolveEditorLaunch}from"./chunk-g8ap5366.js";import{embeddedTerminalEnv}from"./chunk-ef39ym8f.js";import{UpdatePage,openWithSystemViewer,resolveRowSelectionChrome,spawnDetached}from"./chunk-qeypyf57.js";import"./chunk-c7hjesva.js";import{deriveTitleFromSessionId,startTaskSessionWithPromptAdapter}from"./chunk-kmsnrf9m.js";import{canonPath,checkResolutionNotify}from"./chunk-grdk12w7.js";import{readLastActiveTaskId}from"./chunk-2kb4z64z.js";import{ISSUE_STATUSES,isValidCron,nextCronAfter,tightenPluginPermissions}from"./chunk-9fc0j6ng.js";import"./chunk-xd9kw4hh.js";import"./chunk-xsrcwcjc.js";import{reloadPluginEngines}from"./chunk-c8xm2s8h.js";import{submitFeedback}from"./chunk-8m10tjsv.js";import"./chunk-xb9b93ts.js";import{DIRTY_WORKTREE_CODE,PROJECT_SIBLING_BASE,TASK_DELETING_CODE,TaskDeletingError,WORKTREE_BASE_CUSTOM_KEY,worktreeBaseKindOf}from"./chunk-ztwz2465.js";import{currentPluginPlatform,loadPluginRegistry,parsePluginManifest,pluginConfigDir,pluginLogPath,pluginManifestPath,qualifiedActionId,readPluginManifest,savePluginRegistry,supportsPlatform}from"./chunk-bq9shn2d.js";import{PROJECT_DIR_TOKEN,WORKTREE_BASE_KEY,hasProjectDirToken,normalizeWorktreeBase}from"./chunk-63wmhbqs.js";import{ulid}from"./chunk-qkehg2c1.js";import{approxCellWidth,approxCharCells,charWidth,displayWidth,padEndCells}from"./chunk-dvcb6mk4.js";import{addTab,closeActiveTab,closeTab,collapseSplit,cycleLeaf,cycleTab,engineTabSpawnFor,expandHome,filterSubdirs,findEditorTab,forgetTaskTabsSnapshot,hasEngineLeaf,initialShellTabs,initialSplit,initialTabs,isTabSplit,joinDrill,joinPicked,leaves,listSubdirs,moveTab,openCommandTab,openContentTab,openEditorTab,pathLeaf,recycleTabs,rehydrateTabs,removeLeaf,renameActiveTab,renameLeaf,reopenTabs,selectTab,setTabAutoTitle,setTabEngineCommand,setTabForkFrom,setTabInitialPrompt,setTabLastTitle,setTabLiveVendor,setTabSessionId,setTabSpawned,setTabSplit,setTabTitle,shellIdentityInput,splitActive,splitLeafNames,splitLeafPtyKey,splitPathForDirSuggest,stripTrailingSlash,sweepOrphanTabsSnapshots,tabCwdFor,tabExitAction,tabPtyKey,tabPtyKeyFor,tabTitle,tabTitleStable,terminalTabsKey,visibleNativeStatus}from"./chunk-6dgyb7sq.js";import{AUTO_STATUS_KEY,DISPATCHER_KEY,hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp}from"./chunk-3dv9vdpj.js";import{execHostForWorktreePath,remoteKeyForRepo}from"./chunk-dg8bsyb9.js";import"./chunk-2apszxn2.js";import"./chunk-g2advs8t.js";import{ensurePtyHostReachable}from"./chunk-gsy8xfh6.js";import"./chunk-rcyasw34.js";import{DEFAULT_TERMINAL_COLORS,formatDefaultColorReply,parseTerminalDefaultColors}from"./chunk-7q67dz4c.js";import{readFirstNonEmptyRepoFile}from"./chunk-v3fqkype.js";import"./chunk-hape5vwj.js";import{resolveLoginShell}from"./chunk-b99tf0jr.js";import"./chunk-w25b7xxz.js";import{getGlobalDefaultVendor,resolvePreferredVendor,setGlobalDefaultVendor,setRepoLastActiveVendor}from"./chunk-j5przd8x.js";import{matchPathGlob}from"./chunk-kg11c1py.js";import{KEY_HINTS_ENABLED_KEY,PANE_HINT_USED_KEYS,grammarHelpSections,guideCategory,keyHintsEnabled,keyHintsToggleOn,legendCap,paneHintTokens,paneHintVisible,scopeCategory,statusHintTokens,toggleKeyHints}from"./chunk-hk8xx4k0.js";import{$Fragment,$jsx,$jsxs,DEFAULT_PREFIX_CONFIGURATION,DEFAULT_SOUND_VOLUME,DIRECT_GUIDE_PREFIX_ACTION_ID,FIXED_BINDING_IDS,KobeKeymap,PREFIX_GUIDE_DELAY_MS,PREFIX_HUD_TTL_MS,SOUND_VOLUME_KEY,armPrefixFromCurrentStack,attentionEdges,attentionKindFor,bindByIds,bootPaneHost,chipAttentionKind,currentBindingReachability,currentPrefixConfiguration,defaultChordsOf,findBinding,formatChord,hostTargetFps,imeAnchorController,invokeArmedPrefixActionFromCurrentStack,isKittyModifierKeyEvent,isNarrowWidth,keymapVersion,modalActive,narrowSurface,nextSoundVolume,normalizeSoundVolume,pageCloseBindings,pluginKeybindings,prefixAction,prefixHudClock,prefixHudState,redrawScreen,reloadUserKeybindings,shortcutCaption,showDialog,subscribeKeymapVersion,taskJumpDigit,useAccessor,useBindingStackVersion,useBindings,useDialog,useDialogPaddingX,useFocus,useKV,useLatest,useNotifications,useOptionalDialog,useOptionalFocus,useOptionalKV,useOptionalNotifications,usePaste,useRenderer,useT,useTerminalDimensions,useTheme,userKeybindingsReport}from"./chunk-mcd4f2jr.js";import{RemoteOrchestrator}from"./chunk-2sgkw3yw.js";import{require_react_production}from"./chunk-a82ec09z.js";import{parseNumstatRows,parsePorcelain,pickPushedChanges,sameWorktreeChanges}from"./chunk-k6nxyxyh.js";import{parsePorcelainRows,unquoteGitPath}from"./chunk-h4n8ffqy.js";import{READ_ONLY_GIT_ENV,readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{FOCUS_ACCENT_SLOTS,LOCALE_KEY}from"./chunk-072m1jjt.js";import"./chunk-z7c6nap0.js";import{tildify}from"./chunk-fczqwtmq.js";import{connectOrStartDaemon}from"./chunk-te8g5azg.js";import"./chunk-y13681dw.js";import{KobeDaemonClient}from"./chunk-b5mbpv97.js";import{attentionInboxItemKey,automationRunNeedsAttention}from"./chunk-re5ke4fz.js";import"./chunk-mnqxgvyb.js";import"./chunk-764bsyb0.js";import{detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-5mbv38x2.js";import{ENGINE_PROTOCOLS,engineCanFork,engineLaunchArgv,engineProtocolKey,getEngineProtocol,pickUnclaimedSessionId,protocolEntry,withPinnedSessionId}from"./chunk-00t0rc5r.js";import{defaultEngineCommand,engineCommandKey,engineDisplayName,engineNameKey,humanizeSlug,interactiveEngineCommand,kobeApiInvocation}from"./chunk-yfkr1fem.js";import{currentLang,intlLocale,setLocaleLang,t,tKeys}from"./chunk-x2c7ehve.js";import{LOCALES}from"./chunk-22jgttzv.js";import{createStateCell}from"./chunk-sdyzxayr.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-qnj7vk5g.js";import{engineEntry,engineSessionIdFromTitle,engineTitleTurnHint,getCapabilities,stripEngineStatusPrefix}from"./chunk-kav5p2qb.js";import{availableEngineIds,installedEngineIds}from"./chunk-kx3kydwv.js";import"./chunk-w7zv47mp.js";import{maybeStartScheduledRun,spawnCapture}from"./chunk-khj0apc7.js";import{CURRENT_VERSION}from"./chunk-0fe2k0jx.js";import"./chunk-jvxh93nz.js";import{errorMessage,userFacingErrorMessage}from"./chunk-2brn8e1y.js";import{roveCliInvocation}from"./chunk-r92b9j14.js";import"./chunk-aep7gvh4.js";import"./chunk-7kysxgbq.js";import"./chunk-krpsfcda.js";import{DEFAULT_TASK_VENDOR,TASK_STATUSES}from"./chunk-xy8be792.js";import{addSavedRepo,getSavedRepos,isGitRepo,isRemoteRepoKey,resolveMainRepoRoot}from"./chunk-9ydhv2zb.js";import{recordSpawn}from"./chunk-40dgv828.js";import{loadStateFile}from"./chunk-3jh78dmc.js";import"./chunk-ddcxvbme.js";import{logClientError}from"./chunk-0q6h4vt4.js";import"./chunk-pw6yfj10.js";import{ALL_VENDORS,isBuiltinVendor,nextVendorWithin,prevVendorWithin}from"./chunk-05jej26n.js";import"./chunk-81p6mm0p.js";import{isDev,promptAttachmentsDir,roveStateDir}from"./chunk-q5jhy3t8.js";import"./chunk-t915by6w.js";import{pathIdentity,pathSyntax,pathWithin,samePath}from"./chunk-f10n6063.js";import{OWNER_ONLY_DIR_MODE,OWNER_ONLY_FILE_MODE}from"./chunk-9prawccj.js";import{defaultDaemonSocketPath}from"./chunk-8cjr5ypt.js";import{activeCliName}from"./chunk-00ehck55.js";import"./chunk-fxs82dsx.js";import{ROVE_PRODUCT_NAME}from"./chunk-sb0ns0c7.js";import{readRoveEnv}from"./chunk-hq4b3fca.js";import"./chunk-pxk2c2vj.js";import{__commonJS,__require,__toESM}from"./chunk-wqfp8d9w.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
 
@@ -53,8 +53,8 @@ ${D3.join(`
53
53
  `)),r5.length=0)},3000),re2=new FinalizationRegistry((e2)=>{typeof e2=="string"&&r5.push(e2)})}var C2=class{constructor(e2){this._size=0,this._options=e2,this._leakageMon=We>0||this._options?.leakWarningThreshold?new Ee(e2?.onListenerError??Y2,this._options?.leakWarningThreshold??We):void 0,this._perfMon=this._options?._profName?new be(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(Ve){let e2=this._listeners;queueMicrotask(()=>{at(e2,(t3)=>t3.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??=(e2,t3,n2)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let p3=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(p3);let b3=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],D3=new Ae(`${p3}. HINT: Stack shows most frequent listener (${b3[1]}-times)`,b3[0]);return(this._options?.onListenerError||Y2)(D3),_3.None}if(this._disposed)return _3.None;t3&&(e2=e2.bind(t3));let o2=new N2(e2),d2,v3;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*0.2)&&(o2.stack=K2.create(),d2=this._leakageMon.check(o2.stack,this._size+1)),Ve&&(o2.stack=v3??K2.create()),this._listeners?this._listeners instanceof N2?(this._deliveryQueue??=new Fe,this._listeners=[this._listeners,o2]):this._listeners.push(o2):(this._options?.onWillAddFirstListener?.(this),this._listeners=o2,this._options?.onDidAddFirstListener?.(this)),this._size++;let E3=me(()=>{re2?.unregister(E3),d2?.(),this._removeListener(o2)});if(n2 instanceof U2?n2.add(E3):Array.isArray(n2)&&n2.push(E3),re2){let p3=Error().stack.split(`
54
54
  `).slice(2,3).join(`
55
55
  `).trim(),b3=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(p3);re2.register(E3,b3?.[2]??p3,E3)}return E3},this._event}_removeListener(e2){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t3=this._listeners,n2=t3.indexOf(e2);if(n2===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),Error("Attempted to dispose unknown listener");this._size--,t3[n2]=void 0;let o2=this._deliveryQueue.current===this;if(this._size*ot<=t3.length){let d2=0;for(let v3=0;v3<t3.length;v3++)t3[v3]?t3[d2++]=t3[v3]:o2&&(this._deliveryQueue.end--,d2<this._deliveryQueue.i&&this._deliveryQueue.i--);t3.length=d2}}_deliver(e2,t3){if(!e2)return;let n2=this._options?.onListenerError||Y2;if(!n2){e2.value(t3);return}try{e2.value(t3)}catch(o2){n2(o2)}}_deliverQueue(e2){let t3=e2.current._listeners;for(;e2.i<e2.end;)this._deliver(t3[e2.i++],e2.value);e2.reset()}fire(e2){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof N2)this._deliver(this._listeners,e2);else{let t3=this._deliveryQueue;t3.enqueue(this,e2,this._listeners.length),this._deliverQueue(t3)}this._perfMon?.stop()}hasListeners(){return this._size>0}},Fe=class{constructor(){this.i=-1,this.end=0}enqueue(e2,t3,n2){this.i=0,this.end=n2,this.current=e2,this.value=t3}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},w3=class r5{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new C2,this.onChange=this._onChange.event;let e2=new H2;this.register(e2),this._active=e2.version,this._activeProvider=e2}static extractShouldJoin(e2){return(e2&1)!==0}static extractWidth(e2){return e2>>1&3}static extractCharKind(e2){return e2>>3}static createPropertyValue(e2,t3,n2=!1){return(e2&16777215)<<3|(t3&3)<<1|(n2?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e2){if(!this._providers[e2])throw Error(`unknown Unicode version "${e2}"`);this._active=e2,this._activeProvider=this._providers[e2],this._onChange.fire(e2)}register(e2){this._providers[e2.version]=e2}wcwidth(e2){return this._activeProvider.wcwidth(e2)}getStringCellWidth(e2){let t3=0,n2=0,o2=e2.length;for(let d2=0;d2<o2;++d2){let v3=e2.charCodeAt(d2);if(55296<=v3&&v3<=56319){if(++d2>=o2)return t3+this.wcwidth(v3);let b3=e2.charCodeAt(d2);56320<=b3&&b3<=57343?v3=(v3-55296)*1024+b3-56320+65536:t3+=this.wcwidth(b3)}let E3=this.charProperties(v3,n2),p3=r5.extractWidth(E3);r5.extractShouldJoin(E3)&&(p3-=r5.extractWidth(n2)),t3+=p3,n2=E3}return t3}charProperties(e2,t3){return this._activeProvider.charProperties(e2,t3)}},ye=[[768,879],[1155,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1541],[1552,1562],[1564,1564],[1611,1631],[1648,1648],[1750,1757],[1759,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2045,2045],[2070,2073],[2075,2083],[2085,2087],[2089,2093],[2137,2139],[2259,2306],[2362,2362],[2364,2364],[2369,2376],[2381,2381],[2385,2391],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2558,2558],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2641,2641],[2672,2673],[2677,2677],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2810,2815],[2817,2817],[2876,2876],[2879,2879],[2881,2884],[2893,2893],[2902,2902],[2914,2915],[2946,2946],[3008,3008],[3021,3021],[3072,3072],[3076,3076],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3170,3171],[3201,3201],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3328,3329],[3387,3388],[3393,3396],[3405,3405],[3426,3427],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3981,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4151],[4153,4154],[4157,4158],[4184,4185],[4190,4192],[4209,4212],[4226,4226],[4229,4230],[4237,4237],[4253,4253],[4448,4607],[4957,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6158],[6277,6278],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6683,6683],[6742,6742],[6744,6750],[6752,6752],[6754,6754],[6757,6764],[6771,6780],[6783,6783],[6832,6846],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7040,7041],[7074,7077],[7080,7081],[7083,7085],[7142,7142],[7144,7145],[7149,7149],[7151,7153],[7212,7219],[7222,7223],[7376,7378],[7380,7392],[7394,7400],[7405,7405],[7412,7412],[7416,7417],[7616,7673],[7675,7679],[8203,8207],[8234,8238],[8288,8292],[8294,8303],[8400,8432],[11503,11505],[11647,11647],[11744,11775],[12330,12333],[12441,12442],[42607,42610],[42612,42621],[42654,42655],[42736,42737],[43010,43010],[43014,43014],[43019,43019],[43045,43046],[43204,43205],[43232,43249],[43263,43263],[43302,43309],[43335,43345],[43392,43394],[43443,43443],[43446,43449],[43452,43453],[43493,43493],[43561,43566],[43569,43570],[43573,43574],[43587,43587],[43596,43596],[43644,43644],[43696,43696],[43698,43700],[43703,43704],[43710,43711],[43713,43713],[43756,43757],[43766,43766],[44005,44005],[44008,44008],[44013,44013],[64286,64286],[65024,65039],[65056,65071],[65279,65279],[65529,65531]],lt=[[66045,66045],[66272,66272],[66422,66426],[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[68325,68326],[68900,68903],[69446,69456],[69633,69633],[69688,69702],[69759,69761],[69811,69814],[69817,69818],[69821,69821],[69837,69837],[69888,69890],[69927,69931],[69933,69940],[70003,70003],[70016,70017],[70070,70078],[70089,70092],[70191,70193],[70196,70196],[70198,70199],[70206,70206],[70367,70367],[70371,70378],[70400,70401],[70459,70460],[70464,70464],[70502,70508],[70512,70516],[70712,70719],[70722,70724],[70726,70726],[70750,70750],[70835,70840],[70842,70842],[70847,70848],[70850,70851],[71090,71093],[71100,71101],[71103,71104],[71132,71133],[71219,71226],[71229,71229],[71231,71232],[71339,71339],[71341,71341],[71344,71349],[71351,71351],[71453,71455],[71458,71461],[71463,71467],[71727,71735],[71737,71738],[72148,72151],[72154,72155],[72160,72160],[72193,72202],[72243,72248],[72251,72254],[72263,72263],[72273,72278],[72281,72283],[72330,72342],[72344,72345],[72752,72758],[72760,72765],[72767,72767],[72850,72871],[72874,72880],[72882,72883],[72885,72886],[73009,73014],[73018,73018],[73020,73021],[73023,73029],[73031,73031],[73104,73105],[73109,73109],[73111,73111],[73459,73460],[78896,78904],[92912,92916],[92976,92982],[94031,94031],[94095,94098],[113821,113822],[113824,113827],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[121344,121398],[121403,121452],[121461,121461],[121476,121476],[121499,121503],[121505,121519],[122880,122886],[122888,122904],[122907,122913],[122915,122916],[122918,122922],[123184,123190],[123628,123631],[125136,125142],[125252,125258],[917505,917505],[917536,917631],[917760,917999]],ge=[[4352,4447],[8986,8987],[9001,9002],[9193,9196],[9200,9200],[9203,9203],[9725,9726],[9748,9749],[9800,9811],[9855,9855],[9875,9875],[9889,9889],[9898,9899],[9917,9918],[9924,9925],[9934,9934],[9940,9940],[9962,9962],[9970,9971],[9973,9973],[9978,9978],[9981,9981],[9989,9989],[9994,9995],[10024,10024],[10060,10060],[10062,10062],[10067,10069],[10071,10071],[10133,10135],[10160,10160],[10175,10175],[11035,11036],[11088,11088],[11093,11093],[11904,11929],[11931,12019],[12032,12245],[12272,12283],[12288,12329],[12334,12350],[12353,12438],[12443,12543],[12549,12591],[12593,12686],[12688,12730],[12736,12771],[12784,12830],[12832,12871],[12880,19903],[19968,42124],[42128,42182],[43360,43388],[44032,55203],[63744,64255],[65040,65049],[65072,65106],[65108,65126],[65128,65131],[65281,65376],[65504,65510]],xt=[[94176,94179],[94208,100343],[100352,101106],[110592,110878],[110928,110930],[110948,110951],[110960,111355],[126980,126980],[127183,127183],[127374,127374],[127377,127386],[127488,127490],[127504,127547],[127552,127560],[127568,127569],[127584,127589],[127744,127776],[127789,127797],[127799,127868],[127870,127891],[127904,127946],[127951,127955],[127968,127984],[127988,127988],[127992,128062],[128064,128064],[128066,128252],[128255,128317],[128331,128334],[128336,128359],[128378,128378],[128405,128406],[128420,128420],[128507,128591],[128640,128709],[128716,128716],[128720,128722],[128725,128725],[128747,128748],[128756,128762],[128992,129003],[129293,129393],[129395,129398],[129402,129442],[129445,129450],[129454,129482],[129485,129535],[129648,129651],[129656,129658],[129664,129666],[129680,129685],[131072,196605],[196608,262141]],I3;function je(r6,e2){let t3=0,n2=e2.length-1,o2;if(r6<e2[0][0]||r6>e2[n2][1])return!1;for(;n2>=t3;)if(o2=t3+n2>>1,r6>e2[o2][1])t3=o2+1;else if(r6<e2[o2][0])n2=o2-1;else return!0;return!1}var se=class{constructor(){if(this.version="11",!I3){I3=new Uint8Array(65536),I3.fill(1),I3[0]=0,I3.fill(0,1,32),I3.fill(0,127,160);for(let e2=0;e2<ye.length;++e2)I3.fill(0,ye[e2][0],ye[e2][1]+1);for(let e2=0;e2<ge.length;++e2)I3.fill(2,ge[e2][0],ge[e2][1]+1)}}wcwidth(e2){return e2<32?0:e2<127?1:e2<65536?I3[e2]:je(e2,lt)?0:je(e2,xt)?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)}},Ke=class{activate(e2){e2.unicode.register(new se)}dispose(){}};var import_headless=__toESM(require_xterm_headless(),1);var SCROLLBACK_ROWS_KEY="terminal.scrollbackRows",DEFAULT_SCROLLBACK_ROWS=1000,SCROLLBACK_ROWS_MIN=100,SCROLLBACK_ROWS_MAX=1e5;function normalizeScrollbackRows(value){let n2=typeof value==="number"?Math.floor(value):typeof value==="string"?Number.parseInt(value.trim(),10):Number.NaN;if(!Number.isFinite(n2))return DEFAULT_SCROLLBACK_ROWS;return Math.min(SCROLLBACK_ROWS_MAX,Math.max(SCROLLBACK_ROWS_MIN,n2))}function persistedScrollbackRows(){return normalizeScrollbackRows(loadStateFile()[SCROLLBACK_ROWS_KEY])}var target=process.env.ROVE_RENDER_PROFILE,renderProfileOn=Boolean(target),counts=new Map,totals=new Map,started=0;function flush(){if(counts.size===0)return;let row={sec:Math.round((Date.now()-started)/1000)};for(let[k3,n2]of counts){row[`${k3}_n`]=n2;let ms=totals.get(k3);if(ms!==void 0)row[`${k3}_ms`]=+ms.toFixed(3)}counts.clear(),totals.clear();try{__require("fs").appendFileSync(target,`${JSON.stringify(row)}
56
- `)}catch{}}if(renderProfileOn)started=Date.now(),setInterval(flush,1000).unref?.();function profileTick(stage){if(!renderProfileOn)return;counts.set(stage,(counts.get(stage)??0)+1)}function profileSpan(stage,fn){if(!renderProfileOn)return fn();let t0=performance.now();try{return fn()}finally{counts.set(stage,(counts.get(stage)??0)+1),totals.set(stage,(totals.get(stage)??0)+(performance.now()-t0))}}class PtyListeners{data=new Set;exits=new Set;titles=new Set;get dataCount(){return this.data.size}addData(listener){return this.data.add(listener),()=>this.data.delete(listener)}addExit(listener){return this.exits.add(listener),()=>this.exits.delete(listener)}addTitle(listener){return this.titles.add(listener),()=>this.titles.delete(listener)}publishData(snapshot,cursor,window2,wrapped){for(let listener of this.data)try{listener(snapshot,cursor,window2,wrapped)}catch{}}publishTitle(title){for(let listener of this.titles)try{listener(title)}catch{}}drainExits(){let listeners=[...this.exits];return this.exits.clear(),listeners}clearData(){this.data.clear()}clearAll(){this.data.clear(),this.exits.clear(),this.titles.clear()}}function sameRgb(a2,b3){if(a2===b3)return!0;return a2!==void 0&&b3!==void 0&&a2[0]===b3[0]&&a2[1]===b3[1]&&a2[2]===b3[2]}function sameChunk(a2,b3){return a2.text===b3.text&&(a2.attributes??0)===(b3.attributes??0)&&sameRgb(a2.fg,b3.fg)&&sameRgb(a2.bg,b3.bg)}function sameRow(a2,b3){if(a2===b3)return!0;if(a2.length!==b3.length)return!1;for(let i2=0;i2<a2.length;i2++)if(!sameChunk(a2[i2],b3[i2]))return!1;return!0}function reconcileTerminalRow(previous,next){return previous&&sameRow(previous,next)?previous:next}function reconcileTerminalRows(previous,next){if(previous.length!==next.length)return next;let changed=!1;for(let i2=0;i2<next.length;i2++){let stable=reconcileTerminalRow(previous[i2],next[i2]);if(next[i2]=stable,stable!==previous[i2])changed=!0}return changed?next:previous}function reconcileTerminalCursor(previous,next){if(previous===next)return previous;if(previous&&next&&previous.x===next.x&&previous.y===next.y)return previous;return next}var ATTR=Object.freeze({BOLD:1,DIM:2,ITALIC:4,UNDERLINE:8,BLINK:16,INVERSE:32,HIDDEN:64,STRIKETHROUGH:128}),EMPTY_STYLE=Object.freeze({fg:void 0,bg:void 0,attributes:0});function ansi256ToRgb(index){if(index<0)return[0,0,0];if(index<16)return SYSTEM_PALETTE[index]??[0,0,0];if(index<232){let i2=index-16,r6=Math.floor(i2/36),g3=Math.floor(i2/6%6),b3=i2%6,step=(n2)=>n2===0?0:55+40*n2;return[step(r6),step(g3),step(b3)]}if(index<256){let gray=8+10*(index-232);return[gray,gray,gray]}return[0,0,0]}var SYSTEM_PALETTE=[[21,22,30],[247,118,142],[158,206,106],[224,175,104],[122,162,247],[187,154,247],[125,207,255],[169,177,214],[65,72,104],[255,137,157],[158,224,68],[250,186,74],[141,176,255],[199,169,255],[164,218,255],[192,202,245]];function applySgr(prev,rawParams){let params=rawParams.length===0?[0]:rawParams.map((p3)=>p3===""?0:Number.parseInt(p3,10)||0),fg=prev.fg,bg=prev.bg,attr=prev.attributes,i2=0;while(i2<params.length){let p3=params[i2];if(p3===void 0)break;if(p3===0){fg=void 0,bg=void 0,attr=0,i2+=1;continue}if(p3===1){attr|=ATTR.BOLD,i2+=1;continue}if(p3===2){attr|=ATTR.DIM,i2+=1;continue}if(p3===3){attr|=ATTR.ITALIC,i2+=1;continue}if(p3===4){attr|=ATTR.UNDERLINE,i2+=1;continue}if(p3===5||p3===6){attr|=ATTR.BLINK,i2+=1;continue}if(p3===7){attr|=ATTR.INVERSE,i2+=1;continue}if(p3===8){attr|=ATTR.HIDDEN,i2+=1;continue}if(p3===9){attr|=ATTR.STRIKETHROUGH,i2+=1;continue}if(p3===22){attr&=~(ATTR.BOLD|ATTR.DIM),i2+=1;continue}if(p3===23){attr&=~ATTR.ITALIC,i2+=1;continue}if(p3===24){attr&=~ATTR.UNDERLINE,i2+=1;continue}if(p3===25){attr&=~ATTR.BLINK,i2+=1;continue}if(p3===27){attr&=~ATTR.INVERSE,i2+=1;continue}if(p3===28){attr&=~ATTR.HIDDEN,i2+=1;continue}if(p3===29){attr&=~ATTR.STRIKETHROUGH,i2+=1;continue}if(p3>=30&&p3<=37){fg=ansi256ToRgb(p3-30),i2+=1;continue}if(p3>=90&&p3<=97){fg=ansi256ToRgb(p3-90+8),i2+=1;continue}if(p3===39){fg=void 0,i2+=1;continue}if(p3>=40&&p3<=47){bg=ansi256ToRgb(p3-40),i2+=1;continue}if(p3>=100&&p3<=107){bg=ansi256ToRgb(p3-100+8),i2+=1;continue}if(p3===49){bg=void 0,i2+=1;continue}if(p3===38){let sub=params[i2+1];if(sub===5){let idx=params[i2+2]??0;fg=ansi256ToRgb(idx),i2+=3;continue}if(sub===2){let r6=params[i2+2]??0,g3=params[i2+3]??0,b3=params[i2+4]??0;fg=[r6,g3,b3],i2+=5;continue}i2+=1;continue}if(p3===48){let sub=params[i2+1];if(sub===5){let idx=params[i2+2]??0;bg=ansi256ToRgb(idx),i2+=3;continue}if(sub===2){let r6=params[i2+2]??0,g3=params[i2+3]??0,b3=params[i2+4]??0;bg=[r6,g3,b3],i2+=5;continue}i2+=1;continue}i2+=1}return{fg,bg,attributes:attr}}function sgrParamsFromRaw(raw){let body=raw;if(body.charCodeAt(0)===27)body=body.slice(2);else if(body.charCodeAt(0)===155)body=body.slice(1);if(body.endsWith("m"))body=body.slice(0,-1);return body.split(";")}function parseAnsiLine(input,initial=EMPTY_STYLE){if(input.length===0)return{chunks:[],endStyle:initial};let out=[],style={...initial},buf="",flush2=()=>{if(buf.length===0)return;let c2={text:buf,...style.fg?{fg:style.fg}:{},...style.bg?{bg:style.bg}:{},...style.attributes!==0?{attributes:style.attributes}:{}};out.push(c2),buf=""},codes=ie(input);for(let code of codes){if(code.type==="TEXT"){buf+=code.raw;continue}if(code.type==="CSI"&&code.command==="m"){flush2(),style=applySgr(style,sgrParamsFromRaw(code.raw));continue}if(code.type==="OSC"&&code.command==="8"){flush2();let url=code.params[code.params.length-1]??"";style={...style,attributes:url?style.attributes|ATTR.UNDERLINE:style.attributes&~ATTR.UNDERLINE}}}return flush2(),{chunks:out,endStyle:style}}function parseAnsiSnapshot(input){let lines=input.split(`
57
- `),rows=[],carry=EMPTY_STYLE;for(let line of lines){let{chunks,endStyle}=parseAnsiLine(line,carry);rows.push(chunks),carry=endStyle}return rows}var XTERM_COLOR_MODE_DEFAULT=0,XTERM_COLOR_MODE_PALETTE=16777216,XTERM_COLOR_MODE_RGB=50331648,DEFAULT_RENDER_STYLE=Object.freeze({fg:"",bg:"",attrs:0});function colorKeyToRGB(key){if(key==="")return;let sep=key.indexOf(":"),value=Number(key.slice(sep+1));if(key.startsWith("rgb:"))return[value>>16&255,value>>8&255,value&255];if(key.startsWith("pal:"))return ansi256ToRgb(value);return}function colorKey(cell,kind){if(kind==="fg"?cell.isFgDefault():cell.isBgDefault())return"";let mode=kind==="fg"?cell.getFgColorMode():cell.getBgColorMode(),color=kind==="fg"?cell.getFgColor():cell.getBgColor();if(mode===XTERM_COLOR_MODE_RGB||(kind==="fg"?cell.isFgRGB():cell.isBgRGB()))return`rgb:${color}`;if(mode===XTERM_COLOR_MODE_PALETTE||(kind==="fg"?cell.isFgPalette():cell.isBgPalette()))return`pal:${color}`;if(mode===XTERM_COLOR_MODE_DEFAULT)return"";return""}function cellAttributes(cell){let attrs=0;if(cell.isBold())attrs|=ATTR.BOLD;if(cell.isDim())attrs|=ATTR.DIM;if(cell.isItalic())attrs|=ATTR.ITALIC;if(cell.isUnderline())attrs|=ATTR.UNDERLINE;if(cell.isBlink())attrs|=ATTR.BLINK;if(cell.isInverse())attrs|=ATTR.INVERSE;if(cell.isInvisible())attrs|=ATTR.HIDDEN;if(cell.isStrikethrough())attrs|=ATTR.STRIKETHROUGH;return attrs}function matchingStyleRewrite(cell,styleRewrites){if(!styleRewrites||styleRewrites.length===0||!cell.isFgDefault()||cell.isBgDefault())return;let background=colorKeyToRGB(colorKey(cell,"bg"));return styleRewrites.find((rewrite)=>sameRgb2(background,rewrite.matchBackground))}function rgbKey([red,green,blue]){return`rgb:${red<<16|green<<8|blue}`}function cellStyle(cell,styleRewrites){let style={fg:colorKey(cell,"fg"),bg:colorKey(cell,"bg"),attrs:cellAttributes(cell)},rewrite=matchingStyleRewrite(cell,styleRewrites);return rewrite?{...style,fg:rgbKey(rewrite.foreground),bg:rgbKey(rewrite.background)}:style}function styleEquals(a2,b3){return a2.fg===b3.fg&&a2.bg===b3.bg&&a2.attrs===b3.attrs}function renderStyleToChunkFields(style){let fg=colorKeyToRGB(style.fg),bg=colorKeyToRGB(style.bg);return{...fg?{fg}:{},...bg?{bg}:{},...style.attrs!==0?{attributes:style.attrs}:{}}}function isSolidBlock(chars){return chars==="\u2580"||chars==="\u2584"||chars==="\u2588"}function paintsSamePixel(fg,bg){if(fg===void 0||bg===void 0)return!1;return fg[0]===bg[0]&&fg[1]===bg[1]&&fg[2]===bg[2]}function isVisibleCell(cell){let chars=cell.getChars();if(chars!==""&&chars!==" ")return!0;return!cell.isAttributeDefault()||!cell.isFgDefault()||!cell.isBgDefault()}var scratchCell;function getCellReusing(line,x2){if(scratchCell===void 0){let seeded=line.getCell(x2);if(seeded)scratchCell=seeded;return seeded}return line.getCell(x2,scratchCell)}function xtermLineToChunks(line,minLast=-1,styleRewrites){let last=Math.min(line.length-1,minLast);for(let x2=0;x2<line.length;x2++){let cell=getCellReusing(line,x2);if(!cell||cell.getWidth()===0)continue;if(isVisibleCell(cell))last=Math.max(last,x2)}if(last===-1)return[];let out=[],active=DEFAULT_RENDER_STYLE,activeIsFill=!1,buf="",flush2=()=>{if(buf==="")return;out.push({text:buf,...renderStyleToChunkFields(active)}),buf=""};for(let x2=0;x2<=last;x2++){let cell=getCellReusing(line,x2);if(!cell||cell.getWidth()===0)continue;let next=cellStyle(cell,styleRewrites);if(!styleEquals(active,next))flush2(),active=next,activeIsFill=paintsSamePixel(colorKeyToRGB(next.fg),colorKeyToRGB(next.bg));let chars=cell.getChars()||" ";buf+=isSolidBlock(chars)&&activeIsFill?" ":chars}return flush2(),out}function chunkColorMatchesCell(rgb,cell,kind){if(kind==="fg"?cell.isFgDefault():cell.isBgDefault())return rgb===void 0;if(!rgb)return!1;let mode=kind==="fg"?cell.getFgColorMode():cell.getBgColorMode(),color=kind==="fg"?cell.getFgColor():cell.getBgColor();if(mode===XTERM_COLOR_MODE_RGB||(kind==="fg"?cell.isFgRGB():cell.isBgRGB()))return rgb[0]===(color>>16&255)&&rgb[1]===(color>>8&255)&&rgb[2]===(color&255);if(mode===XTERM_COLOR_MODE_PALETTE||(kind==="fg"?cell.isFgPalette():cell.isBgPalette())){let palette=ansi256ToRgb(color);return rgb[0]===palette[0]&&rgb[1]===palette[1]&&rgb[2]===palette[2]}return!1}function sameRgb2(a2,b3){return Boolean(a2&&b3&&a2[0]===b3[0]&&a2[1]===b3[1]&&a2[2]===b3[2])}function chunkStyleMatchesCell(chunk,cell,styleRewrites){let rewrite=matchingStyleRewrite(cell,styleRewrites);if(rewrite)return(chunk.attributes??0)===cellAttributes(cell)&&sameRgb2(chunk.fg,rewrite.foreground)&&sameRgb2(chunk.bg,rewrite.background);return(chunk.attributes??0)===cellAttributes(cell)&&chunkColorMatchesCell(chunk.fg,cell,"fg")&&chunkColorMatchesCell(chunk.bg,cell,"bg")}function xtermLineMatchesChunks(line,row,minLast=-1,styleRewrites){if(!line)return row.length===0;let last=Math.min(line.length-1,minLast);for(let x2=0;x2<line.length;x2++){let cell=getCellReusing(line,x2);if(!cell||cell.getWidth()===0)continue;if(isVisibleCell(cell))last=Math.max(last,x2)}if(last===-1)return row.length===0;let chunkIndex=0,textOffset=0;for(let x2=0;x2<=last;x2++){let cell=getCellReusing(line,x2);if(!cell||cell.getWidth()===0)continue;let chunk=row[chunkIndex];if(!chunk||!chunkStyleMatchesCell(chunk,cell,styleRewrites))return!1;let raw=cell.getChars()||" ",text=isSolidBlock(raw)&&paintsSamePixel(chunk.fg,chunk.bg)?" ":raw;if(!chunk.text.startsWith(text,textOffset))return!1;if(textOffset+=text.length,textOffset===chunk.text.length)chunkIndex++,textOffset=0;else if(textOffset>chunk.text.length)return!1}return chunkIndex===row.length&&textOffset===0}function wireXtermChannels(term,hooks){term.onData(hooks.onReply),term.onTitleChange(hooks.onTitle)}function wireXtermDefaultColorQueries(term,colors,reply){let resolved=parseTerminalDefaultColors(colors)??DEFAULT_TERMINAL_COLORS;for(let slot of[10,11])term.parser.registerOscHandler(slot,(payload)=>{if(payload!=="?")return!1;return reply(formatDefaultColorReply(slot,resolved)),!0})}class XtermRefreshTracker{dirty=null;subscription;supported;constructor(term){let event=term._core?._inputHandler?.onRequestRefreshRows;if(!event){this.supported=!1,this.subscription=null;return}this.supported=!0,this.subscription=event((range)=>{if(!range){this.dirty={kind:"all"};return}if(!this.dirty)this.dirty={kind:"range",start:range.start,end:range.end};else if(this.dirty.kind==="range")this.dirty.start=Math.min(this.dirty.start,range.start),this.dirty.end=Math.max(this.dirty.end,range.end)})}markAll(){this.dirty={kind:"all"}}peek(){return this.dirty}clear(){this.dirty=null}dispose(){this.subscription?.dispose()}}function snapshotMeta(active,viewportRows,scrollbackRows){return{type:active.type,baseY:active.baseY,length:active.length,start:Math.max(0,active.length-(viewportRows+scrollbackRows))}}function sameMeta(a2,b3){return a2.type===b3.type&&a2.baseY===b3.baseY&&a2.length===b3.length&&a2.start===b3.start}function dirtyRowsMatchSnapshot(active,snapshot,previousMeta,currentMeta,dirty,cursorHidden,frozen=null,styleRewrites){if(!previousMeta||!sameMeta(previousMeta,currentMeta)||!dirty)return!1;let first=currentMeta.start,last=currentMeta.length-1;if(dirty.kind==="range")first=Math.max(first,active.baseY+dirty.start),last=Math.min(last,active.baseY+dirty.end);let cursorY=active.baseY+active.cursorY;for(let y3=first;y3<=last;y3++){let row=snapshot[y3-currentMeta.start];if(!row)return!1;if(frozen&&y3<frozen.baseY&&frozen.cache.get(frozen.absBase+y3)===row)continue;let minLast=!cursorHidden&&y3===cursorY?active.cursorX-1:-1;if(!xtermLineMatchesChunks(active.getLine(y3),row,minLast,styleRewrites))return!1}return!0}function xtermSynchronizedOutput(term){try{return term.modes.synchronizedOutputMode===!0}catch{return!1}}function xtermCursorHidden(term){try{return term._core?.coreService?.isCursorHidden===!0}catch{return!1}}function sameFlags(previous,next){if(previous.length!==next.length)return!1;for(let i2=0;i2<next.length;i2++)if(previous[i2]!==next[i2])return!1;return!0}class XtermSnapshotEngine{alternateScreenStyleRewrites;scrollbackCache=new Map;wrappedCache=new Map;wrapped=[];anchor;anchorId=0;snapshotEpoch=0;publishedMeta=null;constructor(alternateScreenStyleRewrites){this.alternateScreenStyleRewrites=alternateScreenStyleRewrites}invalidate(){this.scrollbackCache.clear(),this.wrappedCache.clear(),this.wrapped=[],this.anchor?.dispose(),this.anchor=void 0,this.anchorId=0,this.publishedMeta=null}refresh(term,rows,scrollbackRows,refreshTracker,previousSnapshot,previousCursor,previousWindow){if(xtermSynchronizedOutput(term))return null;let active=term.buffer.active,styleRewrites=active.type==="alternate"?this.alternateScreenStyleRewrites:void 0,cursorHidden=xtermCursorHidden(term),currentMeta=snapshotMeta(active,rows,scrollbackRows),nextCursor=reconcileTerminalCursor(previousCursor,cursorHidden?null:{x:active.cursorX,y:active.baseY+active.cursorY-currentMeta.start}),verifyAnchor=this.anchor,verifyFrozen=active.type!=="alternate"&&verifyAnchor!==void 0&&!verifyAnchor.isDisposed?{baseY:active.baseY,absBase:this.anchorId-verifyAnchor.line,cache:this.scrollbackCache}:null;if(dirtyRowsMatchSnapshot(active,previousSnapshot,this.publishedMeta,currentMeta,refreshTracker.peek(),cursorHidden,verifyFrozen,styleRewrites))return refreshTracker.clear(),this.publishedMeta=currentMeta,{snapshot:previousSnapshot,cursor:nextCursor,snapshotWindow:previousWindow,wrapped:this.wrapped,changed:nextCursor!==previousCursor};let canAnchor=active.type!=="alternate"&&active.baseY>0;if(canAnchor&&(this.anchor===void 0||this.anchor.isDisposed)){this.scrollbackCache.clear(),this.wrappedCache.clear();let fresh=term.registerMarker(-active.cursorY-1);if(fresh)this.snapshotEpoch+=1,this.anchor=fresh,this.anchorId=fresh.line}let anchorAlive=canAnchor&&this.anchor!==void 0&&!this.anchor.isDisposed,absBase=anchorAlive?this.anchorId-this.anchor.line:0,cache=this.scrollbackCache,wrappedCache=this.wrappedCache,rowsOut=[],wrappedOut=[],cursorY=active.baseY+active.cursorY,start=currentMeta.start;for(let y3=start;y3<active.length;y3++){let frozen=anchorAlive&&y3<active.baseY;if(frozen){let cached=cache.get(absBase+y3);if(cached){rowsOut.push(cached),wrappedOut.push(wrappedCache.get(absBase+y3)??!1);continue}}let line=active.getLine(y3),minLast=!cursorHidden&&y3===cursorY?active.cursorX-1:-1,row=line?xtermLineToChunks(line,minLast,styleRewrites):[],wraps=y3>start&&line?.isWrapped===!0,stableRow=frozen?reconcileTerminalRow(previousSnapshot[rowsOut.length],row):row;if(rowsOut.push(stableRow),wrappedOut.push(wraps),frozen)cache.set(absBase+y3,stableRow),wrappedCache.set(absBase+y3,wraps)}if(anchorAlive){let min=absBase+start;for(let id of cache.keys())if(id<min)cache.delete(id);for(let id of wrappedCache.keys())if(id<min)wrappedCache.delete(id)}if(canAnchor){let next=term.registerMarker(-active.cursorY-1);if(next)this.anchorId=anchorAlive?absBase+next.line:0,this.anchor?.dispose(),this.anchor=next}let snapshot=reconcileTerminalRows(previousSnapshot,rowsOut),nextStartLine=absBase+start,snapshotWindow=anchorAlive?previousWindow?.epoch===this.snapshotEpoch&&previousWindow.startLine===nextStartLine?previousWindow:{epoch:this.snapshotEpoch,startLine:nextStartLine}:null;refreshTracker.clear(),this.publishedMeta=currentMeta;let wrapLayoutMoved=!sameFlags(this.wrapped,wrappedOut);if(wrapLayoutMoved)this.wrapped=wrappedOut;let changed=snapshot!==previousSnapshot||nextCursor!==previousCursor||snapshotWindow!==previousWindow||wrapLayoutMoved;return{snapshot,cursor:nextCursor,snapshotWindow,wrapped:this.wrapped,changed}}}var KITTY_CSI_U_RE=/^\x1b\[[\d:;]*u$/;function containsControlCharacter(value){for(let character of value){let codePoint=character.codePointAt(0);if(codePoint===void 0||codePoint<=31||codePoint>=127&&codePoint<=159)return!0}return!1}var CTRL_PUNCT_C0={"@":"\x00","[":"\x1B","\\":"\x1C","]":"\x1D","^":"\x1E",_:"\x1F","?":"\x7F"},LEGACY_FUNCTION_KEYS={f1:{kind:"ss3",final:"P"},f2:{kind:"ss3",final:"Q"},f3:{kind:"ss3",final:"R"},f4:{kind:"ss3",final:"S"},f5:{kind:"tilde",number:15},f6:{kind:"tilde",number:17},f7:{kind:"tilde",number:18},f8:{kind:"tilde",number:19},f9:{kind:"tilde",number:20},f10:{kind:"tilde",number:21},f11:{kind:"tilde",number:23},f12:{kind:"tilde",number:24}},XTERM_MODIFIER_NAMED_KEYS=new Set(["delete","kpdelete","insert","kpinsert","up","kpup","down","kpdown","right","kpright","left","kpleft","home","kphome","end","kpend","pageup","kppageup","pagedown","kppagedown"]);function legacyModifier(evt){return 1+(evt.shift?1:0)+(evt.option||evt.meta?2:0)+(evt.ctrl?4:0)+(evt.super?8:0)+(evt.hyper?16:0)}function legacyCursorSequence(evt,final,applicationCursorKeys){let modifier=legacyModifier(evt);if(modifier!==1)return`\x1B[1;${modifier}${final}`;return applicationCursorKeys?`\x1BO${final}`:`\x1B[${final}`}function legacyTildeSequence(evt,number){let modifier=legacyModifier(evt);return modifier===1?`\x1B[${number}~`:`\x1B[${number};${modifier}~`}function legacyFunctionSequence(evt,key){if(key.kind==="tilde")return legacyTildeSequence(evt,key.number);let modifier=legacyModifier(evt);return modifier===1?`\x1BO${key.final}`:`\x1B[1;${modifier}${key.final}`}var NORMAL_TERMINAL_INPUT_MODES={applicationCursorKeys:!1,applicationKeypad:!1};function keyEventToShellBytes(evt,modes=NORMAL_TERMINAL_INPUT_MODES){if(isKittyModifierKeyEvent(evt))return null;let e2=evt,seq=typeof e2.sequence==="string"&&e2.sequence.length>0?e2.sequence:null,kittyInput=e2.source==="kitty"||typeof e2.raw==="string"&&KITTY_CSI_U_RE.test(e2.raw)||seq!=null&&KITTY_CSI_U_RE.test(seq);if(seq!=null&&!kittyInput)return seq;if(seq!=null&&!containsControlCharacter(seq)&&!evt.ctrl&&!e2.option&&!e2.meta)return seq;return synthesizeShellBytes(evt,modes)}function synthesizeShellBytes(evt,modes){let name=evt.name;if(!name)return null;if(evt.shift&&name==="tab")return"\x1B[Z";let functionKey=LEGACY_FUNCTION_KEYS[name],xtermModifiedNamedKey=functionKey!==void 0||XTERM_MODIFIER_NAMED_KEYS.has(name);if((evt.option||evt.meta)&&!xtermModifiedNamedKey){let inner=synthesizeShellBytes({...evt,option:!1,meta:!1},modes);return inner==null?null:`\x1B${inner}`}if(functionKey)return legacyFunctionSequence(evt,functionKey);switch(name){case"return":case"enter":return"\r";case"kpenter":return modes.applicationKeypad&&legacyModifier(evt)===1?"\x1BOM":"\r";case"tab":return"\t";case"backspace":return"\x7F";case"delete":case"kpdelete":return legacyTildeSequence(evt,3);case"insert":case"kpinsert":return legacyTildeSequence(evt,2);case"up":case"kpup":return legacyCursorSequence(evt,"A",modes.applicationCursorKeys);case"down":case"kpdown":return legacyCursorSequence(evt,"B",modes.applicationCursorKeys);case"right":case"kpright":return legacyCursorSequence(evt,"C",modes.applicationCursorKeys);case"left":case"kpleft":return legacyCursorSequence(evt,"D",modes.applicationCursorKeys);case"home":case"kphome":return legacyCursorSequence(evt,"H",modes.applicationCursorKeys);case"end":case"kpend":return legacyCursorSequence(evt,"F",modes.applicationCursorKeys);case"pageup":case"kppageup":return legacyTildeSequence(evt,5);case"pagedown":case"kppagedown":return legacyTildeSequence(evt,6);case"clear":return"\x1B[E";case"escape":return"\x1B";case"space":return evt.ctrl?"\x00":" ";default:if(name.length===1){if(evt.ctrl){let code=name.toLowerCase().charCodeAt(0);if(code>=97&&code<=122)return String.fromCharCode(code-96);let c0=CTRL_PUNCT_C0[name];if(c0!=null)return c0;return null}if(evt.shift&&name>="a"&&name<="z")return name.toUpperCase();return name}return null}}var DEFAULT_PAGE_SIZE=10;var RESERVED_SPEC=[{id:"help.open"},{id:"focus.sidebar"},{id:"chat.tab.new"},{id:"chat.tab.close"},{id:"chat.tab.cycle-next"},{id:"chat.tab.cycle-prev"},{id:"chat.tab.rename"},"ctrl+e","ctrl+f",{id:"workspace.split.right"},{id:"workspace.split.down"},{id:"workspace.split.focus-next"},{id:"focus.next"},{id:"terminal.reset"},{id:"attention.next"},{id:"tasks.jump"}],RESERVED_GLOBAL_CHORDS=[...new Set(RESERVED_SPEC.flatMap((entry)=>typeof entry==="string"?[entry]:defaultChordsOf(entry.id)))],PASSTHROUGH_NAMES=[..."abcdefghijklmnopqrstuvwxyz".split(""),..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),..."0123456789".split(""),..." `~!@#$%^&*()-_=+[]{}\\|;:'\",.<>/?".split(""),"return","enter","space","tab","backspace","delete","up","down","left","right","home","end","pageup","pagedown","escape","insert","f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","f11","f12"],PASSTHROUGH_MODIFIER_PREFIXES=["","ctrl+","alt+","shift+","ctrl+shift+","alt+shift+","ctrl+alt+"],PASSTHROUGH_CHORDS=PASSTHROUGH_NAMES.flatMap((name)=>PASSTHROUGH_MODIFIER_PREFIXES.map((prefix)=>`${prefix}${name}`)).filter((chord)=>!RESERVED_GLOBAL_CHORDS.includes(chord));function encodeWheel(modes,direction,col,row){if(modes.mouseTracking)return`\x1B[<${direction==="up"?64:65};${Math.max(1,col)};${Math.max(1,row)}M`;if(modes.alternateScreen)return(modes.applicationCursorKeys?direction==="up"?"\x1BOA":"\x1BOB":direction==="up"?"\x1B[A":"\x1B[B").repeat(3);return null}function encodeMouseButton(modes,kind,button,col,row,modifiers){if(modes.mouseTracking==="none")return null;if(kind==="drag"&&modes.mouseTracking!=="drag"&&modes.mouseTracking!=="any")return null;let code=button;if(kind==="drag")code+=32;if(modifiers?.shift)code+=4;if(modifiers?.alt)code+=8;if(modifiers?.ctrl)code+=16;return`\x1B[<${code};${Math.max(1,col)};${Math.max(1,row)}${kind==="up"?"m":"M"}`}function readInputModes(term){try{return{applicationCursorKeys:term.modes.applicationCursorKeysMode===!0,applicationKeypad:term.modes.applicationKeypadMode===!0}}catch{return{applicationCursorKeys:!1,applicationKeypad:!1}}}function appOwnsMouse(term){try{return term.modes.mouseTrackingMode!=="none"}catch{return!1}}function onAlternateScreen(term){try{return term.buffer.active.type==="alternate"}catch{return!1}}function wheelSequence(term,direction,col,row){try{return encodeWheel({mouseTracking:term.modes.mouseTrackingMode!=="none",applicationCursorKeys:term.modes.applicationCursorKeysMode===!0,alternateScreen:term.buffer.active.type==="alternate"},direction,col,row)}catch{return null}}function mouseButtonSequence(term,kind,button,col,row,modifiers){try{return encodeMouseButton({mouseTracking:term.modes.mouseTrackingMode},kind,button,col,row,modifiers)}catch{return null}}var SNAPSHOT_COALESCE_MS=Math.round(1000/hostTargetFps());class XtermTaskPty{taskId;cwd;term;listeners=new PtyListeners;snapshot=[];cursor=null;snapshotWindow=null;snapshotWrapped=[];snapshotDirty=!1;snapshotEngine;_title=null;_unwatchedSince=Date.now();_killed=!1;muteReplies=!1;cols;rows;refreshQueued=!1;lastRefreshAt=0;refreshTracker;scrollbackRows;constructor(opts,options={}){if(this.taskId=opts.taskId,this.cwd=opts.cwd,this.cols=opts.cols??DEFAULT_COLS,this.rows=opts.rows??DEFAULT_ROWS,opts.restore?.title)this._title=opts.restore.title;this.scrollbackRows=opts.scrollback??persistedScrollbackRows(),this.term=new import_headless.Terminal({allowProposedApi:!0,cols:this.cols,rows:this.rows,scrollback:this.scrollbackRows}),this.snapshotEngine=new XtermSnapshotEngine(opts.alternateScreenStyleRewrites),this.term.loadAddon(new Ke),this.term.unicode.activeVersion="11",this.refreshTracker=new XtermRefreshTracker(this.term);let reply=(data)=>{if(this._killed||this.muteReplies)return;try{this.transportWrite(data)}catch{}};if(wireXtermChannels(this.term,{onReply:reply,onTitle:(title)=>{if(!title||title===this._title)return;this._title=title,this.listeners.publishTitle(title)}}),options.respondToDefaultColorQueries!==!1)wireXtermDefaultColorQueries(this.term,opts.defaultColors,reply)}get killed(){return this._killed}write(data){if(this._killed||data.length===0)return;try{this.transportWrite(data)}catch{this.markDead(!1)}}inputModes(){return readInputModes(this.term)}onExit(cb){if(this._killed)return cb(),()=>{};return this.listeners.addExit(cb)}onTitleChange(cb){let off=this.listeners.addTitle(cb);if(this._title)try{cb(this._title)}catch{}return off}paste(text){if(this._killed||text.length===0)return;let bracketed=!1;try{bracketed=this.term.modes.bracketedPasteMode===!0}catch{}this.write(bracketed?`\x1B[200~${text}\x1B[201~`:text)}wheel(direction,col,row){return this.emit(this._killed?null:wheelSequence(this.term,direction,col,row))}click(kind,button,col,row,modifiers){return this.emit(this._killed?null:mouseButtonSequence(this.term,kind,button,col,row,modifiers))}emit(seq){if(seq===null)return!1;return this.write(seq),!0}get appOwnsMouse(){return this._killed?!1:appOwnsMouse(this.term)}get onAlternateScreen(){return this._killed?!1:onAlternateScreen(this.term)}onData(cb){this.ensureFreshSnapshot();let off=this.listeners.addData(cb);if(this._unwatchedSince=null,this.snapshot.length>0)try{cb(this.snapshot,this.cursor,this.snapshotWindow,this.snapshotWrapped)}catch{}return()=>{if(off(),this.listeners.dataCount===0&&this._unwatchedSince===null)this._unwatchedSince=Date.now()}}unwatchedSinceMs(){return this._unwatchedSince}get windowTitle(){return this._title}get scrollback(){return this.scrollbackRows}resizeEmulator(cols,rows){this.cols=cols,this.rows=rows,this.term.resize(cols,rows),this.invalidateScrollbackCache(),this.refreshTracker.markAll()}get size(){return{cols:this.cols,rows:this.rows}}resize(cols,rows){if(this._killed)return;this.cols=cols,this.rows=rows;try{this.term.resize(cols,rows),this.invalidateScrollbackCache(),this.transportResize(cols,rows),this.refreshTracker.markAll(),this.refreshSnapshot()}catch{this.markDead(!1)}}invalidateScrollbackCache(){this.snapshotEngine.invalidate(),this.snapshotWindow=null}capture(){return this.ensureFreshSnapshot(),this.snapshot}captureCursor(){return this.ensureFreshSnapshot(),this.cursor}captureWindow(){return this.ensureFreshSnapshot(),this.snapshotWindow}captureWrapped(){return this.ensureFreshSnapshot(),this.snapshotWrapped}ensureFreshSnapshot(){if(!this.snapshotDirty||this._killed)return;this.refreshSnapshot()}kill(){if(this._killed)return;this.markDead(!0)}feed(data){this.feedInternal(data,!1)}feedReplay(data){this.feedInternal(data,!0)}feedInternal(data,muteReplies){if(this._killed)return;if(muteReplies)this.muteReplies=!0;profileTick("feed"),this.term.write(data,()=>{if(muteReplies)this.muteReplies=!1;if(!this.refreshTracker.supported)this.refreshTracker.markAll();this.queueRefresh()})}queueRefresh(){if(this.listeners.dataCount===0){this.snapshotDirty=!0;return}if(this.refreshQueued)return;let since=Date.now()-this.lastRefreshAt;if(since>=SNAPSHOT_COALESCE_MS){this.refreshSnapshot();return}this.refreshQueued=!0,setTimeout(()=>{this.refreshQueued=!1,this.refreshSnapshot()},SNAPSHOT_COALESCE_MS-since)}refreshSnapshot(){if(this._killed)return;this.lastRefreshAt=Date.now();let result=profileSpan("refresh",()=>this.snapshotEngine.refresh(this.term,this.rows,this.scrollbackRows,this.refreshTracker,this.snapshot,this.cursor,this.snapshotWindow));if(result===null){this.queueRefresh();return}if(this.snapshot=result.snapshot,this.cursor=result.cursor,this.snapshotWindow=result.snapshotWindow,this.snapshotWrapped=result.wrapped,this.snapshotDirty=!1,result.changed)this.publishSnapshot()}publishSnapshot(){profileTick("publish"),this.listeners.publishData(this.snapshot,this.cursor,this.snapshotWindow,this.snapshotWrapped)}disposeEmulator(){try{this.term.dispose()}catch{}}markDead(killProcess){if(this._killed)return;if(this._killed=!0,this.refreshTracker.dispose(),this.disposeEmulator(),killProcess)try{this.transportKill()}catch{}let exitCbs=this.listeners.drainExits();this.listeners.clearData();for(let cb of exitCbs)try{cb()}catch{}}silentDispose(){this._killed=!0,this.refreshTracker.dispose(),this.disposeEmulator(),this.listeners.clearAll()}}var WIGGLE_MIN_GAP_MS=150;class HostedTaskPty extends XtermTaskPty{client=null;opened=!1;pendingInput=[];pendingResize=null;unsubs=[];deadOnAttach=!1;sessionPid=void 0;pendingExitPid=null;get shellPid(){return this.sessionPid??null}serializer=new D;hostOffset=null;constructor(opts){super(opts,{respondToDefaultColorQueries:!1});this.term.loadAddon(this.serializer),this.openRemote(opts)}static createdFresh(res){return res.alive&&(res.created??res.replay.length===0)}async openRemote(opts){try{let client=await getSharedPtyClient();if(this.killed)return;this.client=client,routeAdd(this),this.unsubs.push(client.onLifecycle("close",()=>this.remoteGone()));let res=await client.request("pty.open",{key:this.taskId,cwd:this.cwd,command:opts.command,shell:opts.shell,cols:this.cols,rows:this.rows,defaultColors:opts.defaultColors,sinceOffset:opts.restore?.byteOffset,sincePid:opts.restore?.pid??void 0});if(this.killed)return;this.sessionPid=res.pid??null,this.hostOffset=res.offset??null;let restored=opts.restore!==void 0&&res.sinceValid===!0&&res.created!==!0&&(res.pid??null)===opts.restore.pid;if(restored&&opts.restore){if(await this.restoreParked(opts.restore,Buffer.from(res.replay,"base64")),this.killed)return}else if(res.replay.length>0)this.feedReplay(Buffer.from(res.replay,"base64"));if(this.opened=!0,this.pendingResize){let{cols,rows}=this.pendingResize;this.pendingResize=null,this.sendResize(cols,rows)}let fresh=HostedTaskPty.createdFresh(res);if(opts.initialInput&&fresh)this.sendInput(opts.initialInput);if(opts.firstMessage&&fresh)pastePromptWhenEngineUp(client,this.taskId,opts.engineBin,opts.firstMessage).catch((err)=>logClientError("pty-hosted",err));for(let data of this.pendingInput.splice(0))this.sendInput(data);let parkedExitPid=this.pendingExitPid;if(this.pendingExitPid=null,!res.alive)this.deadOnAttach=res.replay.length>0||restored,this.remoteGone();else if(parkedExitPid!==null&&parkedExitPid===this.sessionPid)this.remoteGone();else if(res.replay.length>0&&!restored){if(this.sendResize(this.cols,Math.max(1,this.rows-1)),await Promise.all([this.nextDataOrTimeout(500),new Promise((r6)=>setTimeout(r6,WIGGLE_MIN_GAP_MS))]),!this.killed)this.sendResize(this.cols,this.rows)}}catch(err){logClientError("pty-hosted",err),this.remoteGone()}}transportWrite(data){if(!this.opened){this.pendingInput.push(data);return}this.sendInput(data)}transportResize(cols,rows){if(!this.opened){this.pendingResize={cols,rows};return}this.sendResize(cols,rows)}transportKill(){let client=this.client;if(client)client.request("pty.kill",{key:this.taskId}).catch(()=>{});this.cleanup()}kill(){if(this.killed){this.client?.request("pty.kill",{key:this.taskId}).catch(()=>{});return}super.kill()}capturePark(){if(this.killed||!this.opened||this.hostOffset===null||this.sessionPid===void 0)return null;try{return{serialized:Buffer.from(this.serializer.serialize({scrollback:this.scrollback}),"utf8").toString(),title:this.windowTitle,cursorHidden:xtermCursorHidden(this.term),cols:this.cols,rows:this.rows,byteOffset:this.hostOffset,pid:this.sessionPid}}catch{return null}}async restoreParked(state,delta){let targetCols=this.cols,targetRows=this.rows;if(state.cols!==targetCols||state.rows!==targetRows)this.resizeEmulator(state.cols,state.rows);if(this.feedReplay(state.serialized+(state.cursorHidden?"\x1B[?25l":"")),delta.byteLength>0)this.feedReplay(delta);if(await new Promise((resolve)=>{let off=this.onExit(resolve);this.term.write("",()=>{off(),resolve()})}),!this.killed&&(this.cols!==targetCols||this.rows!==targetRows))this.resizeEmulator(targetCols,targetRows)}detach(opts={}){let client=this.client;this.cleanup();let siblings=routeCount(this.taskId);if(client&&siblings===0)client.request("pty.detach",{key:this.taskId,parked:opts.parked===!0,parkedScreenBytes:opts.parkedScreenBytes}).catch(()=>{});this.silentDispose()}sendInput(data){this.client?.request("pty.write",{key:this.taskId,data}).catch(()=>this.remoteGone())}sendResize(cols,rows){this.client?.request("pty.resize",{key:this.taskId,cols,rows}).catch(()=>{})}dataWaiter=null;_lastOutputAt=null;lastOutputAtMs(){return this._lastOutputAt}nextDataOrTimeout(ms){return new Promise((resolve)=>{let timer=setTimeout(()=>{this.dataWaiter=null,resolve()},ms);this.dataWaiter=()=>{this.dataWaiter=null,clearTimeout(timer),resolve()}})}feedFrame(dataB64){this.dataWaiter?.(),this._lastOutputAt=Date.now();let buf=Buffer.from(dataB64,"base64");if(this.hostOffset!==null)this.hostOffset+=buf.byteLength;this.feed(buf)}remoteExited(pid){if(this.killed)return;if(pid===void 0){this.remoteGone();return}if(this.sessionPid===void 0){this.pendingExitPid=pid;return}if(pid!==null&&pid===this.sessionPid)this.remoteGone()}remoteGone(){this.cleanup(),this.markDead(!1)}cleanup(){routeRemove(this);for(let unsub of this.unsubs.splice(0))try{unsub()}catch{}}}class MockTaskPty{taskId;cwd;listeners=new Set;buffer="";writes=[];_killed=!1;_title=null;exitListeners=new Set;titleListeners=new Set;pastes=[];deadOnAttach=!1;wheels=[];clicks=[];appOwnsMouse=!1;onAlternateScreen=!1;_cols;_rows;_cursor=null;modes={applicationCursorKeys:!1,applicationKeypad:!1};constructor(opts){if(this.taskId=opts.taskId,this.cwd=opts.cwd,this._cols=opts.cols??DEFAULT_COLS,this._rows=opts.rows??DEFAULT_ROWS,opts.initialInput)this.writes.push(opts.initialInput)}get killed(){return this._killed}get writeLog(){return this.writes}get geometry(){return{cols:this._cols,rows:this._rows}}feed(data){if(this._killed)return;this.buffer+=data;let title=extractOscTitle(data);if(title&&title!==this._title){this._title=title;for(let cb of this.titleListeners)try{cb(title)}catch{}}let rows=this.capture();for(let cb of this.listeners)try{cb(rows,this._cursor,null)}catch{}}write(data){if(this._killed)return;this.writes.push(data)}inputModes(){return this.modes}replaceScreen(data){if(this._killed)return;this.buffer="",this.feed(data)}onData(cb){if(this.listeners.add(cb),this.buffer!=="")try{cb(this.capture(),this._cursor,null)}catch{}return()=>{this.listeners.delete(cb)}}resize(cols,rows){if(this._killed)return;this._cols=cols,this._rows=rows}capture(){return parseAnsiSnapshot(this.buffer)}setCursor(pos){this._cursor=pos}captureCursor(){if(this._killed)return null;return this._cursor}captureWindow(){return null}kill(){if(this._killed)return;this._killed=!0,this.listeners.clear();let exitCbs=[...this.exitListeners];this.exitListeners.clear();for(let cb of exitCbs)cb()}paste(text){if(this._killed)return;this.pastes.push(text)}wheel(direction,col,row){if(this._killed)return!1;return this.wheels.push({direction,col,row}),!1}click(kind,button,col,row){if(this._killed)return!1;return this.clicks.push({kind,button,col,row}),this.appOwnsMouse}onExit(cb){if(this._killed)return cb(),()=>{};return this.exitListeners.add(cb),()=>{this.exitListeners.delete(cb)}}onTitleChange(cb){if(this.titleListeners.add(cb),this._title)try{cb(this._title)}catch{}return()=>{this.titleListeners.delete(cb)}}}import{spawn}from"child_process";class PipeTaskPty{taskId;cwd;proc;listeners=new Set;buffer="";_killed=!1;_title=null;exitListeners=new Set;titleListeners=new Set;cols;rows;constructor(opts){this.taskId=opts.taskId,this.cwd=opts.cwd,this.cols=opts.cols??DEFAULT_COLS,this.rows=opts.rows??DEFAULT_ROWS;let argv=resolveArgv(opts),exe=argv[0]??defaultShell(),args=argv.slice(1);if(this.proc=spawn(exe,args,{cwd:opts.cwd,env:embeddedTerminalEnv(process.env,{TERM:process.env.TERM??"xterm-256color",COLUMNS:String(this.cols),LINES:String(this.rows),KOBE_TERMINAL_PIPE:"1"}),stdio:["pipe","pipe","pipe"]}),this.proc.stdout?.setEncoding("utf8"),this.proc.stderr?.setEncoding("utf8"),this.proc.stdout?.on("data",(chunk)=>this.append(chunk)),this.proc.stderr?.on("data",(chunk)=>this.append(chunk)),this.proc.stdin?.on("error",()=>this.markDead(!1)),this.proc.on("error",(err)=>{this.append(`
56
+ `)}catch{}}if(renderProfileOn)started=Date.now(),setInterval(flush,1000).unref?.();function profileTick(stage){if(!renderProfileOn)return;counts.set(stage,(counts.get(stage)??0)+1)}function profileSpan(stage,fn){if(!renderProfileOn)return fn();let t0=performance.now();try{return fn()}finally{counts.set(stage,(counts.get(stage)??0)+1),totals.set(stage,(totals.get(stage)??0)+(performance.now()-t0))}}class PtyListeners{data=new Set;exits=new Set;titles=new Set;get dataCount(){return this.data.size}addData(listener){return this.data.add(listener),()=>this.data.delete(listener)}addExit(listener){return this.exits.add(listener),()=>this.exits.delete(listener)}addTitle(listener){return this.titles.add(listener),()=>this.titles.delete(listener)}publishData(snapshot,cursor,window2,wrapped){for(let listener of this.data)try{listener(snapshot,cursor,window2,wrapped)}catch{}}publishTitle(title){for(let listener of this.titles)try{listener(title)}catch{}}drainExits(){let listeners=[...this.exits];return this.exits.clear(),listeners}clearData(){this.data.clear()}clearAll(){this.data.clear(),this.exits.clear(),this.titles.clear()}}class TerminalCursorSettlement{platform;settled=null;settledRow;candidate=null;constructor(platform){this.platform=platform}get pending(){return this.candidate!==null}reset(){this.settled=null,this.settledRow=void 0,this.candidate=null}update(cursor,rows,atSynchronizedFrameEnd,now){if(!cursor)return this.candidate=null,null;if(this.platform==="win32"&&atSynchronizedFrameEnd&&cursor.y!==this.settled?.y){if(this.candidate?.row!==cursor.y)this.candidate={row:cursor.y,since:now};if(now-this.candidate.since<80)return this.settled&&rows[this.settled.y]===this.settledRow?this.settled:null}return this.candidate=null,this.settled=cursor,this.settledRow=rows[cursor.y],cursor}}function sameRgb(a2,b3){if(a2===b3)return!0;return a2!==void 0&&b3!==void 0&&a2[0]===b3[0]&&a2[1]===b3[1]&&a2[2]===b3[2]}function sameChunk(a2,b3){return a2.text===b3.text&&(a2.attributes??0)===(b3.attributes??0)&&sameRgb(a2.fg,b3.fg)&&sameRgb(a2.bg,b3.bg)}function sameRow(a2,b3){if(a2===b3)return!0;if(a2.length!==b3.length)return!1;for(let i2=0;i2<a2.length;i2++)if(!sameChunk(a2[i2],b3[i2]))return!1;return!0}function reconcileTerminalRow(previous,next){return previous&&sameRow(previous,next)?previous:next}function reconcileTerminalRows(previous,next){if(previous.length!==next.length)return next;let changed=!1;for(let i2=0;i2<next.length;i2++){let stable=reconcileTerminalRow(previous[i2],next[i2]);if(next[i2]=stable,stable!==previous[i2])changed=!0}return changed?next:previous}function reconcileTerminalCursor(previous,next){if(previous===next)return previous;if(previous&&next&&previous.x===next.x&&previous.y===next.y)return previous;return next}var ATTR=Object.freeze({BOLD:1,DIM:2,ITALIC:4,UNDERLINE:8,BLINK:16,INVERSE:32,HIDDEN:64,STRIKETHROUGH:128}),EMPTY_STYLE=Object.freeze({fg:void 0,bg:void 0,attributes:0});function ansi256ToRgb(index){if(index<0)return[0,0,0];if(index<16)return SYSTEM_PALETTE[index]??[0,0,0];if(index<232){let i2=index-16,r6=Math.floor(i2/36),g3=Math.floor(i2/6%6),b3=i2%6,step=(n2)=>n2===0?0:55+40*n2;return[step(r6),step(g3),step(b3)]}if(index<256){let gray=8+10*(index-232);return[gray,gray,gray]}return[0,0,0]}var SYSTEM_PALETTE=[[21,22,30],[247,118,142],[158,206,106],[224,175,104],[122,162,247],[187,154,247],[125,207,255],[169,177,214],[65,72,104],[255,137,157],[158,224,68],[250,186,74],[141,176,255],[199,169,255],[164,218,255],[192,202,245]];function applySgr(prev,rawParams){let params=rawParams.length===0?[0]:rawParams.map((p3)=>p3===""?0:Number.parseInt(p3,10)||0),fg=prev.fg,bg=prev.bg,attr=prev.attributes,i2=0;while(i2<params.length){let p3=params[i2];if(p3===void 0)break;if(p3===0){fg=void 0,bg=void 0,attr=0,i2+=1;continue}if(p3===1){attr|=ATTR.BOLD,i2+=1;continue}if(p3===2){attr|=ATTR.DIM,i2+=1;continue}if(p3===3){attr|=ATTR.ITALIC,i2+=1;continue}if(p3===4){attr|=ATTR.UNDERLINE,i2+=1;continue}if(p3===5||p3===6){attr|=ATTR.BLINK,i2+=1;continue}if(p3===7){attr|=ATTR.INVERSE,i2+=1;continue}if(p3===8){attr|=ATTR.HIDDEN,i2+=1;continue}if(p3===9){attr|=ATTR.STRIKETHROUGH,i2+=1;continue}if(p3===22){attr&=~(ATTR.BOLD|ATTR.DIM),i2+=1;continue}if(p3===23){attr&=~ATTR.ITALIC,i2+=1;continue}if(p3===24){attr&=~ATTR.UNDERLINE,i2+=1;continue}if(p3===25){attr&=~ATTR.BLINK,i2+=1;continue}if(p3===27){attr&=~ATTR.INVERSE,i2+=1;continue}if(p3===28){attr&=~ATTR.HIDDEN,i2+=1;continue}if(p3===29){attr&=~ATTR.STRIKETHROUGH,i2+=1;continue}if(p3>=30&&p3<=37){fg=ansi256ToRgb(p3-30),i2+=1;continue}if(p3>=90&&p3<=97){fg=ansi256ToRgb(p3-90+8),i2+=1;continue}if(p3===39){fg=void 0,i2+=1;continue}if(p3>=40&&p3<=47){bg=ansi256ToRgb(p3-40),i2+=1;continue}if(p3>=100&&p3<=107){bg=ansi256ToRgb(p3-100+8),i2+=1;continue}if(p3===49){bg=void 0,i2+=1;continue}if(p3===38){let sub=params[i2+1];if(sub===5){let idx=params[i2+2]??0;fg=ansi256ToRgb(idx),i2+=3;continue}if(sub===2){let r6=params[i2+2]??0,g3=params[i2+3]??0,b3=params[i2+4]??0;fg=[r6,g3,b3],i2+=5;continue}i2+=1;continue}if(p3===48){let sub=params[i2+1];if(sub===5){let idx=params[i2+2]??0;bg=ansi256ToRgb(idx),i2+=3;continue}if(sub===2){let r6=params[i2+2]??0,g3=params[i2+3]??0,b3=params[i2+4]??0;bg=[r6,g3,b3],i2+=5;continue}i2+=1;continue}i2+=1}return{fg,bg,attributes:attr}}function sgrParamsFromRaw(raw){let body=raw;if(body.charCodeAt(0)===27)body=body.slice(2);else if(body.charCodeAt(0)===155)body=body.slice(1);if(body.endsWith("m"))body=body.slice(0,-1);return body.split(";")}function parseAnsiLine(input,initial=EMPTY_STYLE){if(input.length===0)return{chunks:[],endStyle:initial};let out=[],style={...initial},buf="",flush2=()=>{if(buf.length===0)return;let c2={text:buf,...style.fg?{fg:style.fg}:{},...style.bg?{bg:style.bg}:{},...style.attributes!==0?{attributes:style.attributes}:{}};out.push(c2),buf=""},codes=ie(input);for(let code of codes){if(code.type==="TEXT"){buf+=code.raw;continue}if(code.type==="CSI"&&code.command==="m"){flush2(),style=applySgr(style,sgrParamsFromRaw(code.raw));continue}if(code.type==="OSC"&&code.command==="8"){flush2();let url=code.params[code.params.length-1]??"";style={...style,attributes:url?style.attributes|ATTR.UNDERLINE:style.attributes&~ATTR.UNDERLINE}}}return flush2(),{chunks:out,endStyle:style}}function parseAnsiSnapshot(input){let lines=input.split(`
57
+ `),rows=[],carry=EMPTY_STYLE;for(let line of lines){let{chunks,endStyle}=parseAnsiLine(line,carry);rows.push(chunks),carry=endStyle}return rows}var XTERM_COLOR_MODE_DEFAULT=0,XTERM_COLOR_MODE_PALETTE=16777216,XTERM_COLOR_MODE_RGB=50331648,DEFAULT_RENDER_STYLE=Object.freeze({fg:"",bg:"",attrs:0});function colorKeyToRGB(key){if(key==="")return;let sep=key.indexOf(":"),value=Number(key.slice(sep+1));if(key.startsWith("rgb:"))return[value>>16&255,value>>8&255,value&255];if(key.startsWith("pal:"))return ansi256ToRgb(value);return}function colorKey(cell,kind){if(kind==="fg"?cell.isFgDefault():cell.isBgDefault())return"";let mode=kind==="fg"?cell.getFgColorMode():cell.getBgColorMode(),color=kind==="fg"?cell.getFgColor():cell.getBgColor();if(mode===XTERM_COLOR_MODE_RGB||(kind==="fg"?cell.isFgRGB():cell.isBgRGB()))return`rgb:${color}`;if(mode===XTERM_COLOR_MODE_PALETTE||(kind==="fg"?cell.isFgPalette():cell.isBgPalette()))return`pal:${color}`;if(mode===XTERM_COLOR_MODE_DEFAULT)return"";return""}function cellAttributes(cell){let attrs=0;if(cell.isBold())attrs|=ATTR.BOLD;if(cell.isDim())attrs|=ATTR.DIM;if(cell.isItalic())attrs|=ATTR.ITALIC;if(cell.isUnderline())attrs|=ATTR.UNDERLINE;if(cell.isBlink())attrs|=ATTR.BLINK;if(cell.isInverse())attrs|=ATTR.INVERSE;if(cell.isInvisible())attrs|=ATTR.HIDDEN;if(cell.isStrikethrough())attrs|=ATTR.STRIKETHROUGH;return attrs}function matchingStyleRewrite(cell,styleRewrites){if(!styleRewrites||styleRewrites.length===0||!cell.isFgDefault()||cell.isBgDefault())return;let background=colorKeyToRGB(colorKey(cell,"bg"));return styleRewrites.find((rewrite)=>sameRgb2(background,rewrite.matchBackground))}function rgbKey([red,green,blue]){return`rgb:${red<<16|green<<8|blue}`}function cellStyle(cell,styleRewrites){let style={fg:colorKey(cell,"fg"),bg:colorKey(cell,"bg"),attrs:cellAttributes(cell)},rewrite=matchingStyleRewrite(cell,styleRewrites);return rewrite?{...style,fg:rgbKey(rewrite.foreground),bg:rgbKey(rewrite.background)}:style}function styleEquals(a2,b3){return a2.fg===b3.fg&&a2.bg===b3.bg&&a2.attrs===b3.attrs}function renderStyleToChunkFields(style){let fg=colorKeyToRGB(style.fg),bg=colorKeyToRGB(style.bg);return{...fg?{fg}:{},...bg?{bg}:{},...style.attrs!==0?{attributes:style.attrs}:{}}}function isSolidBlock(chars){return chars==="\u2580"||chars==="\u2584"||chars==="\u2588"}function paintsSamePixel(fg,bg){if(fg===void 0||bg===void 0)return!1;return fg[0]===bg[0]&&fg[1]===bg[1]&&fg[2]===bg[2]}function isVisibleCell(cell){let chars=cell.getChars();if(chars!==""&&chars!==" ")return!0;return!cell.isAttributeDefault()||!cell.isFgDefault()||!cell.isBgDefault()}var scratchCell;function getCellReusing(line,x2){if(scratchCell===void 0){let seeded=line.getCell(x2);if(seeded)scratchCell=seeded;return seeded}return line.getCell(x2,scratchCell)}function xtermLineToChunks(line,minLast=-1,styleRewrites){let last=Math.min(line.length-1,minLast);for(let x2=0;x2<line.length;x2++){let cell=getCellReusing(line,x2);if(!cell||cell.getWidth()===0)continue;if(isVisibleCell(cell))last=Math.max(last,x2)}if(last===-1)return[];let out=[],active=DEFAULT_RENDER_STYLE,activeIsFill=!1,buf="",flush2=()=>{if(buf==="")return;out.push({text:buf,...renderStyleToChunkFields(active)}),buf=""};for(let x2=0;x2<=last;x2++){let cell=getCellReusing(line,x2);if(!cell||cell.getWidth()===0)continue;let next=cellStyle(cell,styleRewrites);if(!styleEquals(active,next))flush2(),active=next,activeIsFill=paintsSamePixel(colorKeyToRGB(next.fg),colorKeyToRGB(next.bg));let chars=cell.getChars()||" ";buf+=isSolidBlock(chars)&&activeIsFill?" ":chars}return flush2(),out}function chunkColorMatchesCell(rgb,cell,kind){if(kind==="fg"?cell.isFgDefault():cell.isBgDefault())return rgb===void 0;if(!rgb)return!1;let mode=kind==="fg"?cell.getFgColorMode():cell.getBgColorMode(),color=kind==="fg"?cell.getFgColor():cell.getBgColor();if(mode===XTERM_COLOR_MODE_RGB||(kind==="fg"?cell.isFgRGB():cell.isBgRGB()))return rgb[0]===(color>>16&255)&&rgb[1]===(color>>8&255)&&rgb[2]===(color&255);if(mode===XTERM_COLOR_MODE_PALETTE||(kind==="fg"?cell.isFgPalette():cell.isBgPalette())){let palette=ansi256ToRgb(color);return rgb[0]===palette[0]&&rgb[1]===palette[1]&&rgb[2]===palette[2]}return!1}function sameRgb2(a2,b3){return Boolean(a2&&b3&&a2[0]===b3[0]&&a2[1]===b3[1]&&a2[2]===b3[2])}function chunkStyleMatchesCell(chunk,cell,styleRewrites){let rewrite=matchingStyleRewrite(cell,styleRewrites);if(rewrite)return(chunk.attributes??0)===cellAttributes(cell)&&sameRgb2(chunk.fg,rewrite.foreground)&&sameRgb2(chunk.bg,rewrite.background);return(chunk.attributes??0)===cellAttributes(cell)&&chunkColorMatchesCell(chunk.fg,cell,"fg")&&chunkColorMatchesCell(chunk.bg,cell,"bg")}function xtermLineMatchesChunks(line,row,minLast=-1,styleRewrites){if(!line)return row.length===0;let last=Math.min(line.length-1,minLast);for(let x2=0;x2<line.length;x2++){let cell=getCellReusing(line,x2);if(!cell||cell.getWidth()===0)continue;if(isVisibleCell(cell))last=Math.max(last,x2)}if(last===-1)return row.length===0;let chunkIndex=0,textOffset=0;for(let x2=0;x2<=last;x2++){let cell=getCellReusing(line,x2);if(!cell||cell.getWidth()===0)continue;let chunk=row[chunkIndex];if(!chunk||!chunkStyleMatchesCell(chunk,cell,styleRewrites))return!1;let raw=cell.getChars()||" ",text=isSolidBlock(raw)&&paintsSamePixel(chunk.fg,chunk.bg)?" ":raw;if(!chunk.text.startsWith(text,textOffset))return!1;if(textOffset+=text.length,textOffset===chunk.text.length)chunkIndex++,textOffset=0;else if(textOffset>chunk.text.length)return!1}return chunkIndex===row.length&&textOffset===0}function wireXtermChannels(term,hooks){term.onData(hooks.onReply),term.onTitleChange(hooks.onTitle)}function wireXtermDefaultColorQueries(term,colors,reply){let resolved=parseTerminalDefaultColors(colors)??DEFAULT_TERMINAL_COLORS;for(let slot of[10,11])term.parser.registerOscHandler(slot,(payload)=>{if(payload!=="?")return!1;return reply(formatDefaultColorReply(slot,resolved)),!0})}class XtermRefreshTracker{dirty=null;subscription;synchronizedCursorSubscription;lastSynchronizedCursor=null;supported;constructor(term){this.synchronizedCursorSubscription=term.parser.registerCsiHandler({prefix:"?",final:"l"},(params)=>{if(params.includes(2026)){let active=term.buffer.active;this.lastSynchronizedCursor={x:active.cursorX,y:active.baseY+active.cursorY}}return!1});let event=term._core?._inputHandler?.onRequestRefreshRows;if(!event){this.supported=!1,this.subscription=null;return}this.supported=!0,this.subscription=event((range)=>{if(!range){this.dirty={kind:"all"};return}if(!this.dirty)this.dirty={kind:"range",start:range.start,end:range.end};else if(this.dirty.kind==="range")this.dirty.start=Math.min(this.dirty.start,range.start),this.dirty.end=Math.max(this.dirty.end,range.end)})}markAll(){this.dirty={kind:"all"}}get synchronizedCursor(){return this.lastSynchronizedCursor}peek(){return this.dirty}clear(){this.dirty=null}dispose(){this.subscription?.dispose(),this.synchronizedCursorSubscription.dispose()}}function snapshotMeta(active,viewportRows,scrollbackRows){return{type:active.type,baseY:active.baseY,length:active.length,start:Math.max(0,active.length-(viewportRows+scrollbackRows))}}function sameMeta(a2,b3){return a2.type===b3.type&&a2.baseY===b3.baseY&&a2.length===b3.length&&a2.start===b3.start}function dirtyRowsMatchSnapshot(active,snapshot,previousMeta,currentMeta,dirty,cursorHidden,frozen=null,styleRewrites){if(!previousMeta||!sameMeta(previousMeta,currentMeta)||!dirty)return!1;let first=currentMeta.start,last=currentMeta.length-1;if(dirty.kind==="range")first=Math.max(first,active.baseY+dirty.start),last=Math.min(last,active.baseY+dirty.end);let cursorY=active.baseY+active.cursorY;for(let y3=first;y3<=last;y3++){let row=snapshot[y3-currentMeta.start];if(!row)return!1;if(frozen&&y3<frozen.baseY&&frozen.cache.get(frozen.absBase+y3)===row)continue;let minLast=!cursorHidden&&y3===cursorY?active.cursorX-1:-1;if(!xtermLineMatchesChunks(active.getLine(y3),row,minLast,styleRewrites))return!1}return!0}function xtermSynchronizedOutput(term){try{return term.modes.synchronizedOutputMode===!0}catch{return!1}}function xtermCursorHidden(term){try{return term._core?.coreService?.isCursorHidden===!0}catch{return!1}}function sameFlags(previous,next){if(previous.length!==next.length)return!1;for(let i2=0;i2<next.length;i2++)if(previous[i2]!==next[i2])return!1;return!0}class XtermSnapshotEngine{alternateScreenStyleRewrites;scrollbackCache=new Map;wrappedCache=new Map;wrapped=[];anchor;anchorId=0;snapshotEpoch=0;publishedMeta=null;cursorSettlement;constructor(alternateScreenStyleRewrites,platform=process.platform){this.alternateScreenStyleRewrites=alternateScreenStyleRewrites;this.cursorSettlement=new TerminalCursorSettlement(platform)}invalidate(){this.scrollbackCache.clear(),this.wrappedCache.clear(),this.wrapped=[],this.anchor?.dispose(),this.anchor=void 0,this.anchorId=0,this.publishedMeta=null,this.cursorSettlement.reset()}refresh(term,rows,scrollbackRows,refreshTracker,previousSnapshot,previousCursor,previousWindow){if(xtermSynchronizedOutput(term))return null;let active=term.buffer.active,styleRewrites=active.type==="alternate"?this.alternateScreenStyleRewrites:void 0,cursorHidden=xtermCursorHidden(term),currentMeta=snapshotMeta(active,rows,scrollbackRows),nextCursor=reconcileTerminalCursor(previousCursor,cursorHidden?null:{x:active.cursorX,y:active.baseY+active.cursorY-currentMeta.start}),frameCursor=refreshTracker.synchronizedCursor,atFrameEnd=nextCursor!==null&&frameCursor?.x===nextCursor.x&&frameCursor.y===nextCursor.y+currentMeta.start,verifyAnchor=this.anchor,verifyFrozen=active.type!=="alternate"&&verifyAnchor!==void 0&&!verifyAnchor.isDisposed?{baseY:active.baseY,absBase:this.anchorId-verifyAnchor.line,cache:this.scrollbackCache}:null;if(dirtyRowsMatchSnapshot(active,previousSnapshot,this.publishedMeta,currentMeta,refreshTracker.peek(),cursorHidden,verifyFrozen,styleRewrites)){refreshTracker.clear(),this.publishedMeta=currentMeta;let cursor2=this.cursorSettlement.update(nextCursor,previousSnapshot,atFrameEnd,Date.now());return{snapshot:previousSnapshot,cursor:cursor2,snapshotWindow:previousWindow,wrapped:this.wrapped,changed:cursor2!==previousCursor,cursorPending:this.cursorSettlement.pending}}let canAnchor=active.type!=="alternate"&&active.baseY>0;if(canAnchor&&(this.anchor===void 0||this.anchor.isDisposed)){this.scrollbackCache.clear(),this.wrappedCache.clear();let fresh=term.registerMarker(-active.cursorY-1);if(fresh)this.snapshotEpoch+=1,this.anchor=fresh,this.anchorId=fresh.line}let anchorAlive=canAnchor&&this.anchor!==void 0&&!this.anchor.isDisposed,absBase=anchorAlive?this.anchorId-this.anchor.line:0,cache=this.scrollbackCache,wrappedCache=this.wrappedCache,rowsOut=[],wrappedOut=[],cursorY=active.baseY+active.cursorY,start=currentMeta.start;for(let y3=start;y3<active.length;y3++){let frozen=anchorAlive&&y3<active.baseY;if(frozen){let cached=cache.get(absBase+y3);if(cached){rowsOut.push(cached),wrappedOut.push(wrappedCache.get(absBase+y3)??!1);continue}}let line=active.getLine(y3),minLast=!cursorHidden&&y3===cursorY?active.cursorX-1:-1,row=line?xtermLineToChunks(line,minLast,styleRewrites):[],wraps=y3>start&&line?.isWrapped===!0,stableRow=frozen?reconcileTerminalRow(previousSnapshot[rowsOut.length],row):row;if(rowsOut.push(stableRow),wrappedOut.push(wraps),frozen)cache.set(absBase+y3,stableRow),wrappedCache.set(absBase+y3,wraps)}if(anchorAlive){let min=absBase+start;for(let id of cache.keys())if(id<min)cache.delete(id);for(let id of wrappedCache.keys())if(id<min)wrappedCache.delete(id)}if(canAnchor){let next=term.registerMarker(-active.cursorY-1);if(next)this.anchorId=anchorAlive?absBase+next.line:0,this.anchor?.dispose(),this.anchor=next}let snapshot=reconcileTerminalRows(previousSnapshot,rowsOut),cursor=this.cursorSettlement.update(nextCursor,snapshot,atFrameEnd,Date.now()),nextStartLine=absBase+start,snapshotWindow=anchorAlive?previousWindow?.epoch===this.snapshotEpoch&&previousWindow.startLine===nextStartLine?previousWindow:{epoch:this.snapshotEpoch,startLine:nextStartLine}:null;refreshTracker.clear(),this.publishedMeta=currentMeta;let wrapLayoutMoved=!sameFlags(this.wrapped,wrappedOut);if(wrapLayoutMoved)this.wrapped=wrappedOut;let changed=snapshot!==previousSnapshot||cursor!==previousCursor||snapshotWindow!==previousWindow||wrapLayoutMoved;return{snapshot,cursor,snapshotWindow,wrapped:this.wrapped,changed,cursorPending:this.cursorSettlement.pending}}}var KITTY_CSI_U_RE=/^\x1b\[[\d:;]*u$/;function containsControlCharacter(value){for(let character of value){let codePoint=character.codePointAt(0);if(codePoint===void 0||codePoint<=31||codePoint>=127&&codePoint<=159)return!0}return!1}var CTRL_PUNCT_C0={"@":"\x00","[":"\x1B","\\":"\x1C","]":"\x1D","^":"\x1E",_:"\x1F","?":"\x7F"},LEGACY_FUNCTION_KEYS={f1:{kind:"ss3",final:"P"},f2:{kind:"ss3",final:"Q"},f3:{kind:"ss3",final:"R"},f4:{kind:"ss3",final:"S"},f5:{kind:"tilde",number:15},f6:{kind:"tilde",number:17},f7:{kind:"tilde",number:18},f8:{kind:"tilde",number:19},f9:{kind:"tilde",number:20},f10:{kind:"tilde",number:21},f11:{kind:"tilde",number:23},f12:{kind:"tilde",number:24}},XTERM_MODIFIER_NAMED_KEYS=new Set(["delete","kpdelete","insert","kpinsert","up","kpup","down","kpdown","right","kpright","left","kpleft","home","kphome","end","kpend","pageup","kppageup","pagedown","kppagedown"]);function legacyModifier(evt){return 1+(evt.shift?1:0)+(evt.option||evt.meta?2:0)+(evt.ctrl?4:0)+(evt.super?8:0)+(evt.hyper?16:0)}function legacyCursorSequence(evt,final,applicationCursorKeys){let modifier=legacyModifier(evt);if(modifier!==1)return`\x1B[1;${modifier}${final}`;return applicationCursorKeys?`\x1BO${final}`:`\x1B[${final}`}function legacyTildeSequence(evt,number){let modifier=legacyModifier(evt);return modifier===1?`\x1B[${number}~`:`\x1B[${number};${modifier}~`}function legacyFunctionSequence(evt,key){if(key.kind==="tilde")return legacyTildeSequence(evt,key.number);let modifier=legacyModifier(evt);return modifier===1?`\x1BO${key.final}`:`\x1B[1;${modifier}${key.final}`}var NORMAL_TERMINAL_INPUT_MODES={applicationCursorKeys:!1,applicationKeypad:!1};function keyEventToShellBytes(evt,modes=NORMAL_TERMINAL_INPUT_MODES){if(isKittyModifierKeyEvent(evt))return null;let e2=evt,seq=typeof e2.sequence==="string"&&e2.sequence.length>0?e2.sequence:null,kittyInput=e2.source==="kitty"||typeof e2.raw==="string"&&KITTY_CSI_U_RE.test(e2.raw)||seq!=null&&KITTY_CSI_U_RE.test(seq);if(seq!=null&&!kittyInput)return seq;if(seq!=null&&!containsControlCharacter(seq)&&!evt.ctrl&&!e2.option&&!e2.meta)return seq;return synthesizeShellBytes(evt,modes)}function synthesizeShellBytes(evt,modes){let name=evt.name;if(!name)return null;if(evt.shift&&name==="tab")return"\x1B[Z";let functionKey=LEGACY_FUNCTION_KEYS[name],xtermModifiedNamedKey=functionKey!==void 0||XTERM_MODIFIER_NAMED_KEYS.has(name);if((evt.option||evt.meta)&&!xtermModifiedNamedKey){let inner=synthesizeShellBytes({...evt,option:!1,meta:!1},modes);return inner==null?null:`\x1B${inner}`}if(functionKey)return legacyFunctionSequence(evt,functionKey);switch(name){case"return":case"enter":return"\r";case"kpenter":return modes.applicationKeypad&&legacyModifier(evt)===1?"\x1BOM":"\r";case"tab":return"\t";case"backspace":return"\x7F";case"delete":case"kpdelete":return legacyTildeSequence(evt,3);case"insert":case"kpinsert":return legacyTildeSequence(evt,2);case"up":case"kpup":return legacyCursorSequence(evt,"A",modes.applicationCursorKeys);case"down":case"kpdown":return legacyCursorSequence(evt,"B",modes.applicationCursorKeys);case"right":case"kpright":return legacyCursorSequence(evt,"C",modes.applicationCursorKeys);case"left":case"kpleft":return legacyCursorSequence(evt,"D",modes.applicationCursorKeys);case"home":case"kphome":return legacyCursorSequence(evt,"H",modes.applicationCursorKeys);case"end":case"kpend":return legacyCursorSequence(evt,"F",modes.applicationCursorKeys);case"pageup":case"kppageup":return legacyTildeSequence(evt,5);case"pagedown":case"kppagedown":return legacyTildeSequence(evt,6);case"clear":return"\x1B[E";case"escape":return"\x1B";case"space":return evt.ctrl?"\x00":" ";default:if(name.length===1){if(evt.ctrl){let code=name.toLowerCase().charCodeAt(0);if(code>=97&&code<=122)return String.fromCharCode(code-96);let c0=CTRL_PUNCT_C0[name];if(c0!=null)return c0;return null}if(evt.shift&&name>="a"&&name<="z")return name.toUpperCase();return name}return null}}var DEFAULT_PAGE_SIZE=10;var RESERVED_SPEC=[{id:"help.open"},{id:"focus.sidebar"},{id:"chat.tab.new"},{id:"chat.tab.close"},{id:"chat.tab.cycle-next"},{id:"chat.tab.cycle-prev"},{id:"chat.tab.rename"},"ctrl+e","ctrl+f",{id:"workspace.split.right"},{id:"workspace.split.down"},{id:"workspace.split.focus-next"},{id:"focus.next"},{id:"terminal.reset"},{id:"attention.next"},{id:"tasks.jump"}],RESERVED_GLOBAL_CHORDS=[...new Set(RESERVED_SPEC.flatMap((entry)=>typeof entry==="string"?[entry]:defaultChordsOf(entry.id)))],PASSTHROUGH_NAMES=[..."abcdefghijklmnopqrstuvwxyz".split(""),..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),..."0123456789".split(""),..." `~!@#$%^&*()-_=+[]{}\\|;:'\",.<>/?".split(""),"return","enter","space","tab","backspace","delete","up","down","left","right","home","end","pageup","pagedown","escape","insert","f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","f11","f12"],PASSTHROUGH_MODIFIER_PREFIXES=["","ctrl+","alt+","shift+","ctrl+shift+","alt+shift+","ctrl+alt+"],PASSTHROUGH_CHORDS=PASSTHROUGH_NAMES.flatMap((name)=>PASSTHROUGH_MODIFIER_PREFIXES.map((prefix)=>`${prefix}${name}`)).filter((chord)=>!RESERVED_GLOBAL_CHORDS.includes(chord));function encodeWheel(modes,direction,col,row){if(modes.mouseTracking)return`\x1B[<${direction==="up"?64:65};${Math.max(1,col)};${Math.max(1,row)}M`;if(modes.alternateScreen)return(modes.applicationCursorKeys?direction==="up"?"\x1BOA":"\x1BOB":direction==="up"?"\x1B[A":"\x1B[B").repeat(3);return null}function encodeMouseButton(modes,kind,button,col,row,modifiers){if(modes.mouseTracking==="none")return null;if(kind==="drag"&&modes.mouseTracking!=="drag"&&modes.mouseTracking!=="any")return null;let code=button;if(kind==="drag")code+=32;if(modifiers?.shift)code+=4;if(modifiers?.alt)code+=8;if(modifiers?.ctrl)code+=16;return`\x1B[<${code};${Math.max(1,col)};${Math.max(1,row)}${kind==="up"?"m":"M"}`}function readInputModes(term){try{return{applicationCursorKeys:term.modes.applicationCursorKeysMode===!0,applicationKeypad:term.modes.applicationKeypadMode===!0}}catch{return{applicationCursorKeys:!1,applicationKeypad:!1}}}function appOwnsMouse(term){try{return term.modes.mouseTrackingMode!=="none"}catch{return!1}}function onAlternateScreen(term){try{return term.buffer.active.type==="alternate"}catch{return!1}}function wheelSequence(term,direction,col,row){try{return encodeWheel({mouseTracking:term.modes.mouseTrackingMode!=="none",applicationCursorKeys:term.modes.applicationCursorKeysMode===!0,alternateScreen:term.buffer.active.type==="alternate"},direction,col,row)}catch{return null}}function mouseButtonSequence(term,kind,button,col,row,modifiers){try{return encodeMouseButton({mouseTracking:term.modes.mouseTrackingMode},kind,button,col,row,modifiers)}catch{return null}}var SNAPSHOT_COALESCE_MS=Math.round(1000/hostTargetFps());class XtermTaskPty{taskId;cwd;term;listeners=new PtyListeners;snapshot=[];cursor=null;snapshotWindow=null;snapshotWrapped=[];snapshotDirty=!1;snapshotEngine;_title=null;_unwatchedSince=Date.now();_killed=!1;muteReplies=!1;cols;rows;refreshQueued=!1;lastRefreshAt=0;refreshTracker;scrollbackRows;constructor(opts,options={}){if(this.taskId=opts.taskId,this.cwd=opts.cwd,this.cols=opts.cols??DEFAULT_COLS,this.rows=opts.rows??DEFAULT_ROWS,opts.restore?.title)this._title=opts.restore.title;this.scrollbackRows=opts.scrollback??persistedScrollbackRows(),this.term=new import_headless.Terminal({allowProposedApi:!0,cols:this.cols,rows:this.rows,scrollback:this.scrollbackRows}),this.snapshotEngine=new XtermSnapshotEngine(opts.alternateScreenStyleRewrites),this.term.loadAddon(new Ke),this.term.unicode.activeVersion="11",this.refreshTracker=new XtermRefreshTracker(this.term);let reply=(data)=>{if(this._killed||this.muteReplies)return;try{this.transportWrite(data)}catch{}};if(wireXtermChannels(this.term,{onReply:reply,onTitle:(title)=>{if(!title||title===this._title)return;this._title=title,this.listeners.publishTitle(title)}}),options.respondToDefaultColorQueries!==!1)wireXtermDefaultColorQueries(this.term,opts.defaultColors,reply)}get killed(){return this._killed}write(data){if(this._killed||data.length===0)return;try{this.transportWrite(data)}catch{this.markDead(!1)}}inputModes(){return readInputModes(this.term)}onExit(cb){if(this._killed)return cb(),()=>{};return this.listeners.addExit(cb)}onTitleChange(cb){let off=this.listeners.addTitle(cb);if(this._title)try{cb(this._title)}catch{}return off}paste(text){if(this._killed||text.length===0)return;let bracketed=!1;try{bracketed=this.term.modes.bracketedPasteMode===!0}catch{}this.write(bracketed?`\x1B[200~${text}\x1B[201~`:text)}wheel(direction,col,row){return this.emit(this._killed?null:wheelSequence(this.term,direction,col,row))}click(kind,button,col,row,modifiers){return this.emit(this._killed?null:mouseButtonSequence(this.term,kind,button,col,row,modifiers))}emit(seq){if(seq===null)return!1;return this.write(seq),!0}get appOwnsMouse(){return this._killed?!1:appOwnsMouse(this.term)}get onAlternateScreen(){return this._killed?!1:onAlternateScreen(this.term)}onData(cb){this.ensureFreshSnapshot();let off=this.listeners.addData(cb);if(this._unwatchedSince=null,this.snapshot.length>0)try{cb(this.snapshot,this.cursor,this.snapshotWindow,this.snapshotWrapped)}catch{}return()=>{if(off(),this.listeners.dataCount===0&&this._unwatchedSince===null)this._unwatchedSince=Date.now()}}unwatchedSinceMs(){return this._unwatchedSince}get windowTitle(){return this._title}get scrollback(){return this.scrollbackRows}resizeEmulator(cols,rows){this.cols=cols,this.rows=rows,this.term.resize(cols,rows),this.invalidateScrollbackCache(),this.refreshTracker.markAll()}get size(){return{cols:this.cols,rows:this.rows}}resize(cols,rows){if(this._killed)return;this.cols=cols,this.rows=rows;try{this.term.resize(cols,rows),this.invalidateScrollbackCache(),this.transportResize(cols,rows),this.refreshTracker.markAll(),this.refreshSnapshot()}catch{this.markDead(!1)}}invalidateScrollbackCache(){this.snapshotEngine.invalidate(),this.snapshotWindow=null}capture(){return this.ensureFreshSnapshot(),this.snapshot}captureCursor(){return this.ensureFreshSnapshot(),this.cursor}captureWindow(){return this.ensureFreshSnapshot(),this.snapshotWindow}captureWrapped(){return this.ensureFreshSnapshot(),this.snapshotWrapped}ensureFreshSnapshot(){if(!this.snapshotDirty||this._killed)return;this.refreshSnapshot()}kill(){if(this._killed)return;this.markDead(!0)}feed(data){this.feedInternal(data,!1)}feedReplay(data){this.feedInternal(data,!0)}feedInternal(data,muteReplies){if(this._killed)return;if(muteReplies)this.muteReplies=!0;profileTick("feed"),this.term.write(data,()=>{if(muteReplies)this.muteReplies=!1;if(!this.refreshTracker.supported)this.refreshTracker.markAll();this.queueRefresh()})}queueRefresh(){if(this.listeners.dataCount===0){this.snapshotDirty=!0;return}if(this.refreshQueued)return;let since=Date.now()-this.lastRefreshAt;if(since>=SNAPSHOT_COALESCE_MS){this.refreshSnapshot();return}this.refreshQueued=!0,setTimeout(()=>{this.refreshQueued=!1,this.refreshSnapshot()},SNAPSHOT_COALESCE_MS-since)}refreshSnapshot(){if(this._killed)return;this.lastRefreshAt=Date.now();let result=profileSpan("refresh",()=>this.snapshotEngine.refresh(this.term,this.rows,this.scrollbackRows,this.refreshTracker,this.snapshot,this.cursor,this.snapshotWindow));if(result===null){this.queueRefresh();return}if(this.snapshot=result.snapshot,this.cursor=result.cursor,this.snapshotWindow=result.snapshotWindow,this.snapshotWrapped=result.wrapped,this.snapshotDirty=!1,result.changed)this.publishSnapshot();if(result.cursorPending)this.queueRefresh()}publishSnapshot(){profileTick("publish"),this.listeners.publishData(this.snapshot,this.cursor,this.snapshotWindow,this.snapshotWrapped)}disposeEmulator(){try{this.term.dispose()}catch{}}markDead(killProcess){if(this._killed)return;if(this._killed=!0,this.refreshTracker.dispose(),this.disposeEmulator(),killProcess)try{this.transportKill()}catch{}let exitCbs=this.listeners.drainExits();this.listeners.clearData();for(let cb of exitCbs)try{cb()}catch{}}silentDispose(){this._killed=!0,this.refreshTracker.dispose(),this.disposeEmulator(),this.listeners.clearAll()}}var WIGGLE_MIN_GAP_MS=150;class HostedTaskPty extends XtermTaskPty{client=null;opened=!1;pendingInput=[];pendingResize=null;unsubs=[];deadOnAttach=!1;sessionPid=void 0;pendingExitPid=null;get shellPid(){return this.sessionPid??null}serializer=new D;hostOffset=null;constructor(opts){super(opts,{respondToDefaultColorQueries:!1});this.term.loadAddon(this.serializer),this.openRemote(opts)}static createdFresh(res){return res.alive&&(res.created??res.replay.length===0)}async openRemote(opts){try{let client=await getSharedPtyClient();if(this.killed)return;this.client=client,routeAdd(this),this.unsubs.push(client.onLifecycle("close",()=>this.remoteGone()));let res=await client.request("pty.open",{key:this.taskId,cwd:this.cwd,command:opts.command,shell:opts.shell,cols:this.cols,rows:this.rows,defaultColors:opts.defaultColors,sinceOffset:opts.restore?.byteOffset,sincePid:opts.restore?.pid??void 0});if(this.killed)return;this.sessionPid=res.pid??null,this.hostOffset=res.offset??null;let restored=opts.restore!==void 0&&res.sinceValid===!0&&res.created!==!0&&(res.pid??null)===opts.restore.pid;if(restored&&opts.restore){if(await this.restoreParked(opts.restore,Buffer.from(res.replay,"base64")),this.killed)return}else if(res.replay.length>0)this.feedReplay(Buffer.from(res.replay,"base64"));if(this.opened=!0,this.pendingResize){let{cols,rows}=this.pendingResize;this.pendingResize=null,this.sendResize(cols,rows)}let fresh=HostedTaskPty.createdFresh(res);if(opts.initialInput&&fresh)this.sendInput(opts.initialInput);if(opts.firstMessage&&fresh)pastePromptWhenEngineUp(client,this.taskId,opts.engineBin,opts.firstMessage).catch((err)=>logClientError("pty-hosted",err));for(let data of this.pendingInput.splice(0))this.sendInput(data);let parkedExitPid=this.pendingExitPid;if(this.pendingExitPid=null,!res.alive)this.deadOnAttach=res.replay.length>0||restored,this.remoteGone();else if(parkedExitPid!==null&&parkedExitPid===this.sessionPid)this.remoteGone();else if(res.replay.length>0&&!restored){if(this.sendResize(this.cols,Math.max(1,this.rows-1)),await Promise.all([this.nextDataOrTimeout(500),new Promise((r6)=>setTimeout(r6,WIGGLE_MIN_GAP_MS))]),!this.killed)this.sendResize(this.cols,this.rows)}}catch(err){logClientError("pty-hosted",err),this.remoteGone()}}transportWrite(data){if(!this.opened){this.pendingInput.push(data);return}this.sendInput(data)}transportResize(cols,rows){if(!this.opened){this.pendingResize={cols,rows};return}this.sendResize(cols,rows)}transportKill(){let client=this.client;if(client)client.request("pty.kill",{key:this.taskId}).catch(()=>{});this.cleanup()}kill(){if(this.killed){this.client?.request("pty.kill",{key:this.taskId}).catch(()=>{});return}super.kill()}capturePark(){if(this.killed||!this.opened||this.hostOffset===null||this.sessionPid===void 0)return null;try{return{serialized:Buffer.from(this.serializer.serialize({scrollback:this.scrollback}),"utf8").toString(),title:this.windowTitle,cursorHidden:xtermCursorHidden(this.term),cols:this.cols,rows:this.rows,byteOffset:this.hostOffset,pid:this.sessionPid}}catch{return null}}async restoreParked(state,delta){let targetCols=this.cols,targetRows=this.rows;if(state.cols!==targetCols||state.rows!==targetRows)this.resizeEmulator(state.cols,state.rows);if(this.feedReplay(state.serialized+(state.cursorHidden?"\x1B[?25l":"")),delta.byteLength>0)this.feedReplay(delta);if(await new Promise((resolve)=>{let off=this.onExit(resolve);this.term.write("",()=>{off(),resolve()})}),!this.killed&&(this.cols!==targetCols||this.rows!==targetRows))this.resizeEmulator(targetCols,targetRows)}detach(opts={}){let client=this.client;this.cleanup();let siblings=routeCount(this.taskId);if(client&&siblings===0)client.request("pty.detach",{key:this.taskId,parked:opts.parked===!0,parkedScreenBytes:opts.parkedScreenBytes}).catch(()=>{});this.silentDispose()}sendInput(data){this.client?.request("pty.write",{key:this.taskId,data}).catch(()=>this.remoteGone())}sendResize(cols,rows){this.client?.request("pty.resize",{key:this.taskId,cols,rows}).catch(()=>{})}dataWaiter=null;_lastOutputAt=null;lastOutputAtMs(){return this._lastOutputAt}nextDataOrTimeout(ms){return new Promise((resolve)=>{let timer=setTimeout(()=>{this.dataWaiter=null,resolve()},ms);this.dataWaiter=()=>{this.dataWaiter=null,clearTimeout(timer),resolve()}})}feedFrame(dataB64){this.dataWaiter?.(),this._lastOutputAt=Date.now();let buf=Buffer.from(dataB64,"base64");if(this.hostOffset!==null)this.hostOffset+=buf.byteLength;this.feed(buf)}remoteExited(pid){if(this.killed)return;if(pid===void 0){this.remoteGone();return}if(this.sessionPid===void 0){this.pendingExitPid=pid;return}if(pid!==null&&pid===this.sessionPid)this.remoteGone()}remoteGone(){this.cleanup(),this.markDead(!1)}cleanup(){routeRemove(this);for(let unsub of this.unsubs.splice(0))try{unsub()}catch{}}}class MockTaskPty{taskId;cwd;listeners=new Set;buffer="";writes=[];_killed=!1;_title=null;exitListeners=new Set;titleListeners=new Set;pastes=[];deadOnAttach=!1;wheels=[];clicks=[];appOwnsMouse=!1;onAlternateScreen=!1;_cols;_rows;_cursor=null;modes={applicationCursorKeys:!1,applicationKeypad:!1};constructor(opts){if(this.taskId=opts.taskId,this.cwd=opts.cwd,this._cols=opts.cols??DEFAULT_COLS,this._rows=opts.rows??DEFAULT_ROWS,opts.initialInput)this.writes.push(opts.initialInput)}get killed(){return this._killed}get writeLog(){return this.writes}get geometry(){return{cols:this._cols,rows:this._rows}}feed(data){if(this._killed)return;this.buffer+=data;let title=extractOscTitle(data);if(title&&title!==this._title){this._title=title;for(let cb of this.titleListeners)try{cb(title)}catch{}}let rows=this.capture();for(let cb of this.listeners)try{cb(rows,this._cursor,null)}catch{}}write(data){if(this._killed)return;this.writes.push(data)}inputModes(){return this.modes}replaceScreen(data){if(this._killed)return;this.buffer="",this.feed(data)}onData(cb){if(this.listeners.add(cb),this.buffer!=="")try{cb(this.capture(),this._cursor,null)}catch{}return()=>{this.listeners.delete(cb)}}resize(cols,rows){if(this._killed)return;this._cols=cols,this._rows=rows}capture(){return parseAnsiSnapshot(this.buffer)}setCursor(pos){this._cursor=pos}captureCursor(){if(this._killed)return null;return this._cursor}captureWindow(){return null}kill(){if(this._killed)return;this._killed=!0,this.listeners.clear();let exitCbs=[...this.exitListeners];this.exitListeners.clear();for(let cb of exitCbs)cb()}paste(text){if(this._killed)return;this.pastes.push(text)}wheel(direction,col,row){if(this._killed)return!1;return this.wheels.push({direction,col,row}),!1}click(kind,button,col,row){if(this._killed)return!1;return this.clicks.push({kind,button,col,row}),this.appOwnsMouse}onExit(cb){if(this._killed)return cb(),()=>{};return this.exitListeners.add(cb),()=>{this.exitListeners.delete(cb)}}onTitleChange(cb){if(this.titleListeners.add(cb),this._title)try{cb(this._title)}catch{}return()=>{this.titleListeners.delete(cb)}}}import{spawn}from"child_process";class PipeTaskPty{taskId;cwd;proc;listeners=new Set;buffer="";_killed=!1;_title=null;exitListeners=new Set;titleListeners=new Set;cols;rows;constructor(opts){this.taskId=opts.taskId,this.cwd=opts.cwd,this.cols=opts.cols??DEFAULT_COLS,this.rows=opts.rows??DEFAULT_ROWS;let argv=resolveArgv(opts),exe=argv[0]??defaultShell(),args=argv.slice(1);if(this.proc=spawn(exe,args,{cwd:opts.cwd,env:embeddedTerminalEnv(process.env,{TERM:process.env.TERM??"xterm-256color",COLUMNS:String(this.cols),LINES:String(this.rows),KOBE_TERMINAL_PIPE:"1"}),stdio:["pipe","pipe","pipe"]}),this.proc.stdout?.setEncoding("utf8"),this.proc.stderr?.setEncoding("utf8"),this.proc.stdout?.on("data",(chunk)=>this.append(chunk)),this.proc.stderr?.on("data",(chunk)=>this.append(chunk)),this.proc.stdin?.on("error",()=>this.markDead(!1)),this.proc.on("error",(err)=>{this.append(`
58
58
  [Rove terminal] failed to start shell: ${err.message}
59
59
  `),this.markDead(!1)}),this.proc.on("exit",()=>this.markDead(!1)),this.proc.unref?.(),opts.initialInput)this.write(opts.initialInput)}get killed(){return this._killed}write(data){if(this._killed||data.length===0)return;let stdin=this.proc.stdin;if(!stdin||stdin.destroyed)return;let bytes=data.replace(/\r/g,`
60
60
  `);try{stdin.write(bytes)}catch{this.markDead(!1)}}inputModes(){return{applicationCursorKeys:!1,applicationKeypad:!1}}onData(cb){if(this.listeners.add(cb),this.buffer!=="")try{cb(this.capture(),null,null)}catch{}return()=>{this.listeners.delete(cb)}}resize(cols,rows){if(this._killed)return;this.cols=cols,this.rows=rows}capture(){return parseAnsiSnapshot(this.buffer)}captureCursor(){return null}captureWindow(){return null}kill(){if(this._killed)return;this.markDead(!0)}append(chunk){if(this._killed)return;if(this.buffer+=chunk,this.buffer.length>PIPE_SCROLLBACK_LIMIT)this.buffer=this.buffer.slice(this.buffer.length-PIPE_SCROLLBACK_LIMIT);let title=extractOscTitle(chunk);if(title&&title!==this._title){this._title=title;for(let cb of this.titleListeners)try{cb(title)}catch{}}let rows=this.capture();for(let cb of this.listeners)try{cb(rows,null,null)}catch{}}markDead(killProcess){if(this._killed)return;if(this._killed=!0,killProcess)try{this.proc.kill("SIGTERM")}catch{}let exitCbs=[...this.exitListeners];this.listeners.clear(),this.exitListeners.clear();for(let cb of exitCbs)try{cb()}catch{}}paste(text){this.write(text)}wheel(){return!1}click(){return!1}onExit(cb){if(this._killed)return cb(),()=>{};return this.exitListeners.add(cb),()=>{this.exitListeners.delete(cb)}}onTitleChange(cb){if(this.titleListeners.add(cb),this._title)try{cb(this._title)}catch{}return()=>{this.titleListeners.delete(cb)}}}class BunTerminalTaskPty extends XtermTaskPty{proc;constructor(opts){super(opts);if(this.proc=Bun.spawn(resolveArgv(opts),{cwd:opts.cwd,env:embeddedTerminalEnv(process.env,{TERM:"xterm-256color",COLUMNS:String(this.cols),LINES:String(this.rows),BASH_SILENCE_DEPRECATION_WARNING:"1",KOBE_TERMINAL_PTY:"1"}),terminal:{cols:this.cols,rows:this.rows,name:"xterm-256color",data:(_terminal,data)=>this.feed(data),exit:()=>this.markDead(!1)}}),this.proc.exited.then(()=>this.markDead(!1),()=>this.markDead(!1)),this.proc.unref?.(),opts.initialInput)this.transportWrite(opts.initialInput)}get shellPid(){return this.proc.pid??null}transportWrite(data){this.proc.terminal?.write(data)}transportResize(cols,rows){this.proc.terminal?.resize(cols,rows)}transportKill(){try{this.proc.terminal?.close()}catch{}try{this.proc.kill("SIGTERM")}catch{}}}function createTaskPty(opts){let backend=process.env.KOBE_TERMINAL_BACKEND??"hosted";if(backend==="mock")return new MockTaskPty(opts);if(backend==="pipe")return new PipeTaskPty(opts);if(backend==="bun-pty")return new BunTerminalTaskPty(opts);if(backend==="hosted")return new HostedTaskPty(opts);throw Error(`unknown terminal backend: ${backend}`)}var PARK_AFTER_MS=120000,PARK_SWEEP_MS=30000,PARK_QUIET_MS=30000;class PtyRegistry{map=new Map;parked=new Map;factory;sweepTimer=null;constructor(factory=createTaskPty){this.factory=factory}ensureSweeper(){if(this.sweepTimer)return;let timer=setInterval(()=>this.parkIdle(PARK_AFTER_MS),PARK_SWEEP_MS);timer.unref?.(),this.sweepTimer=timer}stopSweeper(){if(this.sweepTimer)clearInterval(this.sweepTimer);this.sweepTimer=null}parkIdle(idleMs,now=Date.now()){let parked=[];for(let[id,pty]of this.map){if(pty.killed)continue;if(!pty.detach||!pty.unwatchedSinceMs)continue;let since=pty.unwatchedSinceMs();if(since===null||now-since<idleMs)continue;let lastOut=pty.lastOutputAtMs?.()??null;if(lastOut!==null&&now-lastOut<PARK_QUIET_MS)continue;let screen=pty.capturePark?.()??null;try{pty.detach({parked:screen!==null,parkedScreenBytes:screen?Buffer.byteLength(screen.serialized):void 0})}catch{}if(this.map.delete(id),screen)this.parked.set(id,screen);parked.push(id)}if(parked.length>0&&isDev()){let rss=Math.round(process.memoryUsage().rss/1048576);console.error(`[rove pty] parked ${parked.length} idle terminal(s); ${this.map.size} live; rss=${rss}MB`)}return parked}acquire(taskId,cwd,opts={}){let existing=this.map.get(taskId);if(existing&&!existing.killed)return existing;if(existing)this.map.delete(taskId);let restore=this.parked.get(taskId);if(restore)this.parked.delete(taskId);let pty=this.factory({taskId,cwd,...opts,...restore?{restore}:{}});return this.map.set(taskId,pty),this.ensureSweeper(),pty}get(taskId){let pty=this.map.get(taskId);if(!pty)return null;if(pty.killed)return this.map.delete(taskId),null;return pty}has(taskId){return this.get(taskId)!==null}release(taskId){let pty=this.map.get(taskId);if(this.map.delete(taskId),this.parked.delete(taskId),!pty)return;try{pty.kill()}catch{}}releaseWhere(predicate){let ids=Array.from(this.map.keys()).filter(predicate);for(let id of ids)this.release(id);for(let id of Array.from(this.parked.keys()).filter(predicate))this.parked.delete(id)}releaseAll(){let ids=Array.from(this.map.keys());for(let id of ids)this.release(id);this.parked.clear(),this.stopSweeper()}detachAll(){let ptys=Array.from(this.map.values());this.map.clear(),this.parked.clear(),this.stopSweeper();for(let pty of ptys)try{if(pty.detach)pty.detach();else pty.kill()}catch{}}reset(taskId,cwd,opts={}){return this.release(taskId),this.acquire(taskId,cwd,opts)}resetIfCurrent(taskId,expected,cwd,opts={}){if(expected.killed||this.map.get(taskId)!==expected)return null;return this.reset(taskId,cwd,opts)}get size(){return this.map.size}entries(){return[...this.map]}}var defaultRegistry=null;function getDefaultPtyRegistry(){if(!defaultRegistry)defaultRegistry=new PtyRegistry;return defaultRegistry}var import_react118=__toESM(require_react_production(),1);function truncateEnd(s2,max){if(max<=0)return"";let points=[...s2];if(points.length<=max)return s2;return`${points.slice(0,Math.max(0,max-1)).join("")}\u2026`}function truncateEndCells(s2,maxCells,cellsOf){if(maxCells<=0)return"";let total=0;for(let ch of s2)total+=cellsOf(ch.codePointAt(0)??0);if(total<=maxCells)return s2;let used=0,out="";for(let ch of s2){let w4=cellsOf(ch.codePointAt(0)??0);if(used+w4>maxCells-1)break;used+=w4,out+=ch}return`${out}\u2026`}function truncateStart(s2,max){if(max<=0)return"";let points=[...s2];if(points.length<=max)return s2;return`\u2026${points.slice(points.length-Math.max(0,max-1)).join("")}`}function truncateStartCells(s2,maxCells,cellsOf){if(maxCells<=0)return"";let points=[...s2],total=0;for(let ch of points)total+=cellsOf(ch.codePointAt(0)??0);if(total<=maxCells)return s2;let used=0,out="";for(let i2=points.length-1;i2>=0;i2--){let ch=points[i2],w4=cellsOf(ch.codePointAt(0)??0);if(used+w4>maxCells-1)break;used+=w4,out=ch+out}return`\u2026${out}`}var SIDEBAR_WIDTH=24;function sidebarWidthFor(terminalWidth){return Math.max(SIDEBAR_WIDTH,Math.min(40,Math.floor(terminalWidth/6)))}var MAIN_BRANCH_POLL_MS=2000;function sidebarEmptyStateKey(opts){if(opts.searching)return"tasks.empty.noMatchSearch";if(opts.projectFilter)return"tasks.empty.noActiveProject";return"tasks.empty.noActive"}var BRANCH_LABEL_MAX=16;function truncateBranchLabel(branch,max=BRANCH_LABEL_MAX){return truncateEnd(branch,max)}function toneColor(theme,tone){switch(tone){case"success":return theme.success;case"warning":return theme.warning;case"primary":return theme.primary;case"error":return theme.error;default:return theme.textMuted}}function searchQueryKeystroke(query,evt){if(evt.defaultPrevented)return null;if(evt.ctrl||evt.meta||evt.option)return null;if(evt.name==="backspace")return query.slice(0,-1);let seq=evt.sequence;if(!seq||seq.length!==1)return null;let code=seq.charCodeAt(0);if(code<32||code===127)return null;return query+seq}var import_react4=__toESM(require_react_production(),1);var FRAME={border:!0,borderStyle:"rounded"};var import_react2=__toESM(require_react_production(),1);var PREFIX_TAP_PRESENTATION_KEY="hints.keyboard.prefixTapPresentation",PREFIX_TAP_PRESENTATIONS=["local","guide"];function normalizePrefixTapPresentation(raw){return raw==="guide"?"guide":"local"}var import_react=__toESM(require_react_production(),1);function useKeymapVersion(){return import_react.useSyncExternalStore(subscribeKeymapVersion,keymapVersion,keymapVersion)}var DEFAULT_PRESENTATION={mode:"local",activeSurface:null},ShortcutRevealContext=import_react2.createContext(DEFAULT_PRESENTATION);function useShortcutRevealPresentation(){return import_react2.useContext(ShortcutRevealContext)}function ShortcutRevealProvider(props){let kv=useOptionalKV(),hud=useAccessor(prefixHudState),mode=normalizePrefixTapPresentation(kv?.get(PREFIX_TAP_PRESENTATION_KEY)),value=import_react2.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(KobeKeymap.map((binding,index)=>[binding.id,index])),byAction=new Map;for(let option of options){let current=byAction.get(option.action);if(current)current.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=useTerminalDimensions(),hud=useAccessor(prefixHudState),guide=hud.guide,{activeSurface}=useShortcutRevealPresentation(),showPrefixGuide=guide?.kind==="prefix"&&activeSurface!==null,showCommandGuide=guide?.kind==="direct"||showPrefixGuide,[,setFlushTick]=import_react4.useState(0),clock=prefixHudClock(),now=clock.now(),fresh=hud.entries.filter((entry)=>now-entry.at<PREFIX_HUD_TTL_MS),oldestAt=fresh[0]?.at;import_react4.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_react4.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 bound of bounds){if(bound>chunkStart)columnChunks.push(groups.slice(chunkStart,bound));chunkStart=bound}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((entry)=>$jsx("box",{paddingLeft:1,paddingRight:1,backgroundColor:theme.backgroundDialog,children:$jsx("text",{fg:theme.textMuted,wrapMode:"none",children:truncateEndCells(`${entry.prefixKey?`${entry.prefixKey} + `:""}${entry.stroke} ${entry.action?`\u2192 ${actionLabel(entry.action,t3)}`:"\u2205"}`,width-2,charWidth)})},entry.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}from"@opentui/core";var MAX_VISIBLE=3,CARD_WIDTH=44,RIGHT_MARGIN=2,BOTTOM_MARGIN2=2;function cardRows(toast){return(toast.body?2:1)+1}function ToastOverlay(){let{theme}=useTheme(),dims=useTerminalDimensions(),notif=useNotifications();if(notif.toasts.length===0)return null;let visibleToasts=notif.toasts.slice(-MAX_VISIBLE),stackRows=visibleToasts.reduce((rows,toast)=>rows+cardRows(toast),0),cardWidth=Math.min(CARD_WIDTH,Math.max(12,dims.width-RIGHT_MARGIN*2)),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:TextAttributes.BOLD,wrapMode:"none",flexShrink:0,children:`${glyph} `}),$jsx("text",{fg:theme.text,attributes:TextAttributes.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.id)})})}var import_react28=__toESM(require_react_production(),1);var import_react9=__toESM(require_react_production(),1);import{spawnSync}from"child_process";import*as fs from"fs";var DEFAULT_BASE_REF="main";function notAGitRepoReason(path){return`This folder isn't a git repository yet, and a task needs a git branch to work in. To fix it, turn ${path} into a repo: git init && git add -A && git commit -m "init" \u2014 then create the task again. (Working in non-git folders is coming soon.)`}function gitMissingReason(){return t("workspace.welcome.gitMissing")}function isBinaryMissing(out){return out.error!==void 0&&out.error.code==="ENOENT"}function git(repo,args){try{recordSpawn("tui.gitSnapshot",["git",...args],repo);let out=spawnSync("git",args,{cwd:repo,encoding:"utf-8",timeout:2000,stdio:["ignore","pipe","ignore"]});return{status:out.status??1,stdout:out.stdout??"",missing:isBinaryMissing(out),spawned:!0}}catch{return{status:1,stdout:"",missing:!1,spawned:!1}}}function noCommitsReason(path){return`This repository has no commits yet, and a task branches off an existing commit. To fix it, make one in ${path}: git add -A && git commit -m "init" \u2014 then create the task again.`}function hasNoCommits(repo){let out=git(repo,["rev-parse","--verify","HEAD"]);return out.spawned&&!out.missing&&out.status!==0}function validateRepoPath(repo){let trimmed=repo.trim();if(!trimmed)return"repo path is required";let stat;try{stat=fs.statSync(trimmed)}catch{return`path does not exist: ${trimmed}`}if(!stat.isDirectory())return`not a directory: ${trimmed}`;let repoCheck=git(trimmed,["rev-parse","--git-dir"]);if(repoCheck.missing)return gitMissingReason();if(repoCheck.status!==0)return notAGitRepoReason(trimmed);if(hasNoCommits(trimmed))return noCommitsReason(trimmed);return null}function getCurrentBranch(repo){if(!repo)return null;let out=git(repo,["rev-parse","--abbrev-ref","HEAD"]);if(out.status!==0)return null;let name=out.stdout.trim();return!name||name==="HEAD"?null:name}function listLocalBranches(repo){if(!repo)return[];let out=git(repo,["for-each-ref","--format=%(refname:short)","refs/heads/"]);if(out.status!==0)return[];return out.stdout.split(`
@@ -64,7 +64,7 @@ ${D3.join(`
64
64
 
65
65
  ${refs}`}async function capture(cmd){try{let proc=Bun.spawn(cmd,{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),out=await new Response(proc.stdout).text();return await proc.exited===0?out:null}catch{return null}}async function captureClipboardAttachment(){if(process.platform==="darwin"){let furl=await capture(["osascript","-e","get POSIX path of (the clipboard as \xABclass furl\xBB)"]),fromFile=furl?asAttachmentPath(furl):null;if(fromFile)return fromFile;let dest=newAttachmentPath();return await capture(["osascript","-e","set png_data to (the clipboard as \xABclass PNGf\xBB)","-e",`set fp to open for access POSIX file "${dest}" with write permission`,"-e","write png_data to fp","-e","close access fp"])!==null&&existsSync(dest)?dest:null}if(process.platform==="linux"){for(let cmd of[["wl-paste","--type","image/png"],["xclip","-selection","clipboard","-t","image/png","-o"]])try{let proc=Bun.spawn(cmd,{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),bytes=new Uint8Array(await new Response(proc.stdout).arrayBuffer());if(await proc.exited===0&&bytes.length>0){let dest=newAttachmentPath();return writeFileSync(dest,bytes),dest}}catch{}return null}return null}function newAttachmentPath(){let dir=promptAttachmentsDir();mkdirSync(dir,{recursive:!0});let stamp=new Date().toISOString().slice(0,10).replaceAll("-","");return join(dir,`paste-${stamp}-${randomBytes(4).toString("hex")}.png`)}function useTerminalBindings(opts){let pageSize=opts.pageSize??DEFAULT_PAGE_SIZE,optsRef=useLatest(opts),pageSizeRef=useLatest(pageSize),bindings=import_react11.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(),"terminal.search":()=>optsRef.current.openSearch()}));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&&!optsRef.current.searchActive,bindings}));let searchBindings=import_react11.useMemo(()=>bindByIds({"terminal.search.older":()=>optsRef.current.stepSearch(-1),"terminal.search.newer":()=>optsRef.current.stepSearch(1),"terminal.search.cancel":()=>optsRef.current.closeSearch()}),[]);useBindings(()=>({enabled:optsRef.current.focused&&optsRef.current.searchActive,bindings:searchBindings}));let renderer=useRenderer();import_react11.useEffect(()=>{if(!renderer)return;let forwardUnhandled=(evt)=>{if(!optsRef.current.focused||optsRef.current.searchActive)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()||optsRef.current.searchActive)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])}import{TextAttributes as TextAttributes3}from"@opentui/core";var OVERLAY={position:"absolute",zIndex:11,left:0,right:0,bottom:0,flexDirection:"row",flexShrink:0,paddingLeft:1,paddingRight:1};function TerminalSearchBar(props){let{theme}=useTheme(),t3=useT(),surface=theme.backgroundElement;if(props.unavailable)return $jsx("box",{...OVERLAY,backgroundColor:surface,children:$jsx("text",{fg:theme.warning,wrapMode:"none",children:t3("terminal.search.unavailable")})});let status=props.query.length===0?t3("terminal.search.placeholder"):props.matchCount===0?t3("terminal.search.noMatches"):t3("terminal.search.position",{index:props.index+1,total:props.matchCount});return $jsxs("box",{...OVERLAY,gap:0,backgroundColor:surface,children:[$jsx("text",{fg:theme.info,wrapMode:"none",children:"/"}),$jsx("text",{fg:theme.text,wrapMode:"none",children:props.query}),$jsx("text",{fg:theme.info,attributes:TextAttributes3.BLINK,wrapMode:"none",children:"\u2588"}),$jsxs("text",{fg:theme.textMuted,wrapMode:"none",children:[" ",status]})]})}var import_react13=__toESM(require_react_production(),1);function useTerminalGeometry(){let[bodyEl,setBodyEl]=import_react13.useState(null),[bodyRows,setBodyRows]=import_react13.useState(4),[bodyGeometry,setBodyGeometry]=import_react13.useState(null),dims=useTerminalDimensions(),[geomTick,setGeomTick]=import_react13.useState(0),bumpGeomTick=import_react13.useCallback(()=>{setGeomTick((n2)=>n2+1&255)},[]);return import_react13.useEffect(()=>{if(!bodyEl)return;if(bodyEl.width<=0||bodyEl.height<=0)return;let cols=Math.max(20,bodyEl.width),rows=Math.max(4,bodyEl.height);setBodyRows(rows),setBodyGeometry((cur)=>cur&&cur.cols===cols&&cur.rows===rows?cur:{cols,rows})},[bodyEl,dims,geomTick]),{bodyEl,setBodyEl,bodyRows,bodyGeometry,bumpGeomTick,dims,geomTick}}var import_react15=__toESM(require_react_production(),1);function useTerminalHostCursor(opts){let{pty,bodyEl,bodyGeometry,visibleImeCursor,imeAnchorActive,dims,geomTick}=opts,renderer=useRenderer(),imeAnchorOwner=import_react15.useRef(Symbol("terminal-ime-anchor")).current,[imeScreenAnchorRetention]=import_react15.useState(()=>new ImeScreenAnchorRetention),lastResizeRef=import_react15.useRef(null);import_react15.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_react15.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_react15.useEffect(()=>{return()=>{try{if(imeAnchorController.release(imeAnchorOwner))renderer?.setCursorPosition(0,0,!1)}catch{}}},[renderer,imeAnchorOwner])}var import_react16=__toESM(require_react_production(),1);import{StyledText}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:`
66
66
  `});let row=rows[i2];if(!row)continue;for(let c2 of row)chunks.push(toTextChunk(c2))}return chunks}function isWrapContinuation(wrapped,row){return row>0&&wrapped?.[row]===!0}function logicalLines(rowTexts,wrapped){let out=[];for(let row=0;row<rowTexts.length;row++){let text=rowTexts[row]??"",last=out[out.length-1];if(last&&isWrapContinuation(wrapped,row)){last.starts.push(last.text.length),last.text+=text;continue}out.push({text,firstRow:row,starts:[0]})}return out}function rowAtOffset(line,offset){let i2=line.starts.length-1;while(i2>0&&line.starts[i2]>offset)i2--;return{row:line.firstRow+i2,start:line.starts[i2]}}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(range){let{anchor,head}=range;return head.row<anchor.row||head.row===anchor.row&&head.col<anchor.col?{start:head,end:anchor}:{start:anchor,end:head}}function rowSpan(range,row,width){let{start,end}=orderRange(range);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,range,wrapped){let{start,end}=orderRange(range),first=Math.max(0,start.row),lines=[];for(let r6=first;r6<=Math.min(rows.length-1,end.row);r6++){let text=rowText(rows[r6]??[]),span=rowSpan(range,r6,Math.max(textCells(text),1)),slice=span?sliceTextByCells(text,span[0],span[1]).selected:"";if(r6>first&&isWrapContinuation(wrapped,r6)&&lines.length>0)lines[lines.length-1]+=slice;else lines.push(slice)}return lines.map((line)=>line.trimEnd()).join(`
67
- `)}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,range,wrapped){if(shadow.above.length===0&&shadow.below.length===0)return extractSelection(snapshot,range,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:range.anchor.row+offset,col:range.anchor.col},head:{row:range.head.row+offset,col:range.head.col}},shifted)}function appTookMouse(previouslyOwned,ownedNow){return ownedNow&&!previouslyOwned}function overlaySelection(rows,range,firstRow,width,paint="inverse"){if(!range)return rows;return rows.map((row,i2)=>{let span=rowSpan(range,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)}}function useTerminalPaint(opts){let{visibleRows,firstRow,cols,selection,paintMatches,cursor,focused,colors}=opts,cursorRows=import_react16.useMemo(()=>profileSpan("overlay",()=>{let withSelection=overlaySelection(visibleRows,selection,firstRow,cols),withMatches=paintMatches(withSelection,firstRow,cols);return overlayCursor(withMatches,focused&&!selection?cursor:null,colors)}),[visibleRows,selection,firstRow,cols,paintMatches,cursor,focused,colors]),styledSnapshot=import_react16.useMemo(()=>profileSpan("styled",()=>{let resolved=resolveInverseAttributes(cursorRows,colors.foreground,colors.background),sealed=sealRowEndAttributes(resolved,cols,colors.foreground,colors.background);return new StyledText(rowsToStyledText(sealed))}),[cursorRows,cols,colors]),[snapshotTextEl,setSnapshotTextEl]=import_react16.useState(null);return import_react16.useEffect(()=>{if(snapshotTextEl&&!snapshotTextEl.isDestroyed)profileTick("push"),snapshotTextEl.content=styledSnapshot},[snapshotTextEl,styledSnapshot]),setSnapshotTextEl}var import_react17=__toESM(require_react_production(),1);function useTerminalPointerForward(opts){let{pty,bodyEl,scrollBy}=opts,mouseOwnedByApp=import_react17.useRef(!1),paneCell=(screenX,screenY,body)=>({col:Math.max(1,screenX-body.screenX+1),row:Math.max(1,screenY-body.screenY+1)});return{scrollFromPointer:(lines,screenX,screenY)=>{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)){for(let i2=1;i2<Math.abs(lines);i2++)pty.wheel(direction,col,row);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}}}var import_react18=__toESM(require_react_production(),1);var NO_WRAP=[];function useTerminalPty(opts){let[pty,setPty]=import_react18.useState(null),[acquireError,setAcquireError]=import_react18.useState(null),[snapshot,setSnapshot]=import_react18.useState([]),snapshotWindowRef=import_react18.useRef(null),wrappedRef=import_react18.useRef(NO_WRAP),[cursor,setCursor]=import_react18.useState(null),[exited,setExited]=import_react18.useState(!1),commandRef=useLatest(opts.command),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_react18.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})}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_react18.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_react18.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},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_react18.useRef(!1);return import_react18.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_react20=__toESM(require_react_production(),1);var import_react19=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes4}from"@opentui/core";function titlecase(s2){if(!s2)return s2;return s2.charAt(0).toUpperCase()+s2.slice(1)}function DialogConfirm(props){let dialog=useDialog(),{theme}=useTheme(),t3=useT(),padX=useDialogPaddingX(),[active,setActive]=import_react19.useState(props.initialActive??(props.danger?"cancel":"confirm"));return useBindings(()=>({bindings:[{key:"return",cmd:()=>{if(active==="confirm")props.onConfirm?.();if(active==="cancel")props.onCancel?.();dialog.clear()}},{key:"left",cmd:()=>setActive((a2)=>a2==="confirm"?"cancel":"confirm")},{key:"right",cmd:()=>setActive((a2)=>a2==="confirm"?"cancel":"confirm")}]})),$jsxs("box",{paddingLeft:padX,paddingRight:padX,paddingBottom:1,gap:0,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",children:[$jsx("text",{attributes:TextAttributes4.BOLD,fg:theme.text,children:props.title}),$jsx("text",{fg:theme.textMuted,onMouseUp:()=>dialog.clear(),children:"esc"})]}),$jsx("text",{fg:theme.textMuted,children:props.message}),$jsx("box",{flexDirection:"row",justifyContent:"flex-end",paddingTop:1,children:["cancel","confirm"].map((key)=>{let dangerConfirm=key==="confirm"&&props.danger;return $jsx("box",{paddingLeft:1,paddingRight:1,backgroundColor:key===active?dangerConfirm?theme.error:theme.primary:void 0,onMouseUp:()=>{if(key==="confirm")props.onConfirm?.();if(key==="cancel")props.onCancel?.();dialog.clear()},children:$jsx("text",{fg:key===active?theme.selectedListItemText:dangerConfirm?theme.error:theme.textMuted,children:titlecase(key==="cancel"?props.label??t3("common.cancel"):props.confirmLabel??t3("common.confirm"))})},key)})})]})}DialogConfirm.show=(dialog,title,message,label,confirmLabel,options)=>{return showDialog(dialog,(resolve)=>$jsx(DialogConfirm,{title,message,onConfirm:()=>resolve(!0),onCancel:()=>resolve(!1),label,confirmLabel,danger:options?.danger,initialActive:options?.initialActive}),{size:"small"})};function useTerminalReset(args){let t3=useT(),resetTaskIdRef=useLatest(args.taskId),resetCwdRef=useLatest(args.cwd),mountedRef=import_react20.useRef(!0);return import_react20.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)})}}import{decodePasteBytes as decodePasteBytes2}from"@opentui/core";var import_react22=__toESM(require_react_production(),1);function cellWidth2(text){let cells=0;for(let ch of text)cells+=charWidth(ch.codePointAt(0));return cells}function rowText2(row){let out="";for(let chunk of row)out+=chunk.text;return out}function foldCase(text){let lower=text.toLowerCase();return lower.length===text.length?lower:text}function matchRange(line,at2,to){if(cellWidth2(line.text.slice(at2,to))<=0)return null;let head=rowAtOffset(line,to-1),anchor=rowAtOffset(line,at2),headFrom=Math.max(at2,head.start),headCol=cellWidth2(line.text.slice(head.start,headFrom));return{anchor:{row:anchor.row,col:cellWidth2(line.text.slice(anchor.start,at2))},head:{row:head.row,col:headCol+cellWidth2(line.text.slice(headFrom,to))-1}}}function findMatches(rows,query,wrapped){let needle=foldCase(query);if(needle.length===0)return[];let out=[];for(let line of logicalLines(rows.map((row)=>rowText2(row??[])),wrapped)){let haystack=foldCase(line.text),from=0;for(;;){let at2=haystack.indexOf(needle,from);if(at2<0)break;from=at2+needle.length;let range=matchRange(line,at2,from);if(range)out.push(range)}}return out}function overlayMatches(rows,matches,current,firstRow,width,currentPaint){if(matches.length===0)return rows;let lastRow=firstRow+rows.length-1,out=rows;for(let i2=0;i2<matches.length;i2++){let match=matches[i2];if(match.head.row<firstRow||match.anchor.row>lastRow)continue;out=overlaySelection(out,match,firstRow,width,i2===current?currentPaint:"inverse")}return out}function scrollOffsetForRow(total,height,row){let body=Math.max(1,height),max=Math.max(0,total-body);return Math.min(max,Math.max(0,total-body+Math.floor(body/3)-row))}function parkHit(matches,at2,window2){let match=matches[at2];if(!match)return null;if(!window2)return{kind:"position",at:at2};return{kind:"line",epoch:window2.epoch,line:window2.startLine+match.anchor.row,col:match.anchor.col}}function resolveParkedIndex(parked,matches,window2){if(!parked||matches.length===0)return-1;if(parked.kind==="position")return Math.min(parked.at,matches.length-1);if(!window2||window2.epoch!==parked.epoch)return-1;let fallback=-1;for(let i2=0;i2<matches.length;i2++){let match=matches[i2],line=window2.startLine+match.anchor.row;if(line===parked.line&&match.anchor.col===parked.col)return i2;if(fallback<0&&line>=parked.line)fallback=i2}return fallback>=0?fallback:matches.length-1}var NO_MATCHES=[];function useTerminalSearch(opts){let[active,setActive]=import_react22.useState(!1),[query,setQuery]=import_react22.useState(""),[parked,setParked]=import_react22.useState(null),{theme}=useTheme(),optsRef=useLatest(opts),unavailable=active&&opts.onAlternateScreen,matches=import_react22.useMemo(()=>active&&!unavailable?findMatches(opts.snapshot,query,opts.wrapped):NO_MATCHES,[active,unavailable,opts.snapshot,opts.wrapped,query]),matchesRef=useLatest(matches),index=import_react22.useMemo(()=>resolveParkedIndex(parked,matches,opts.snapshotWindow),[parked,matches,opts.snapshotWindow]),indexRef=useLatest(index),jumpToRow=import_react22.useCallback((row)=>{let{snapshot,bodyRows,snapshotWindow,scrollState,setScrollState}=optsRef.current,target2=scrollOffsetForRow(snapshot.length,bodyRows,row),current=resolveViewportScrollOffset(snapshot.length,bodyRows,scrollState,snapshotWindow);if(current===target2)return;setScrollState(moveViewportScroll(scrollState,snapshot.length,bodyRows,current-target2,snapshotWindow))},[]),bookmarkRef=import_react22.useRef(null),open=import_react22.useCallback(()=>{bookmarkRef.current=optsRef.current.scrollState,setQuery(""),setParked(null),setActive(!0)},[]),close=import_react22.useCallback(()=>{let saved=bookmarkRef.current;if(bookmarkRef.current=null,setActive(!1),setQuery(""),setParked(null),saved)optsRef.current.setScrollState(saved)},[]),step=import_react22.useCallback((delta)=>{let list=matchesRef.current;if(list.length===0)return;let next=(((indexRef.current<0?delta>0?-1:0:indexRef.current)+delta)%list.length+list.length)%list.length;setParked(parkHit(list,next,optsRef.current.snapshotWindow)),jumpToRow(list[next].anchor.row)},[jumpToRow]);import_react22.useEffect(()=>{if(!active)return;let last=matches.length-1;if(setParked(parkHit(matches,last,optsRef.current.snapshotWindow)),last>=0)jumpToRow(matches[last].anchor.row)},[active,query]);let renderer=useRenderer();import_react22.useEffect(()=>{if(!active||!renderer)return;let listener=(evt)=>{if(!optsRef.current.focused||modalActive())return;setQuery((current)=>searchQueryKeystroke(current,evt)??current)},paste=(evt)=>{if(evt.defaultPrevented||!optsRef.current.focused||modalActive())return;let text=decodePasteBytes2(evt.bytes).replace(/[\r\n]+/g," ");setQuery((current)=>current+text),evt.preventDefault()};return renderer.keyInput.on("keypress",listener),renderer.keyInput.on("paste",paste),()=>{renderer.keyInput.off("keypress",listener),renderer.keyInput.off("paste",paste)}},[active,renderer]);let hitPaint=import_react22.useMemo(()=>{let[ar,ag,ab]=theme.accent.toInts(),[br,bg,bb]=theme.background.toInts();return{fg:[br,bg,bb],bg:[ar,ag,ab]}},[theme]),paint=import_react22.useCallback((rows,firstRow,width)=>overlayMatches(rows,matches,index,firstRow,width,hitPaint),[matches,index,hitPaint]);return{active,query,index,matchCount:matches.length,unavailable,open,close,step,paint}}var import_react24=__toESM(require_react_production(),1);import{spawn as spawn2}from"child_process";import{spawnSync as spawnSync2}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 spawnSync2(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((resolve)=>{try{let proc=spawn2(cmd[0],cmd.slice(1),{stdio:["pipe","ignore","ignore"]}),settled=!1,done=(ok)=>{if(settled)return;settled=!0,resolve(ok)};proc.on("error",()=>done(!1)),proc.stdin.on("error",()=>done(!1)),proc.on("close",(code)=>done(code===0)),proc.stdin.end(text)}catch{resolve(!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_react24.useState(null),[selHead,setSelHead]=import_react24.useState(null),draggingRef=import_react24.useRef(!1),anchorRef=import_react24.useRef(null),renderer=useRenderer(),notifications=useOptionalNotifications(),t3=useT(),selection=import_react24.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_react24.useRef(null),appScrolledRef=import_react24.useRef(!1),shadowRef=import_react24.useRef(EMPTY_SHADOW),lastSnapshotRef=import_react24.useRef(opts.snapshot),lastWindowRef=import_react24.useRef(opts.snapshotWindow),autoScrollRef=import_react24.useRef(null),tickRef=import_react24.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_react24.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_react24.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_react24.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_react24.useRef(opts.appOwnsMouse);return import_react24.useEffect(()=>{let took=appTookMouse(appOwnedMouseRef.current,opts.appOwnsMouse);if(appOwnedMouseRef.current=opts.appOwnsMouse,!took)return;stopDragging(),clearSelectionState()},[opts.appOwnsMouse]),import_react24.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}}}function Terminal(props){return $jsx(TerminalSession,{...props},props.taskId)}function TerminalSession(props){let{theme}=useTheme(),t3=useT(),registry=props.registry??getDefaultPtyRegistry(),[focusedLocal,setFocusedLocal]=import_react25.useState(!1),focused=props.focused??focusedLocal,[scrollState,setScrollState]=import_react25.useState(FOLLOW_VIEWPORT),{bodyEl,setBodyEl,bodyRows,bodyGeometry,bumpGeomTick,dims,geomTick}=useTerminalGeometry(),defaultColors=import_react25.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_react25.useMemo(()=>props.terminalPresentation?.alternateScreenStyleRewrites(defaultColors),[props.terminalPresentation,defaultColors]),{pty,snapshot,snapshotWindow,wrapped,cursor,exited,acquireError,forceReacquire}=useTerminalPty({cwd:props.cwd,taskId:props.taskId,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((current)=>moveViewportScroll(current,snapshot.length,bodyRows,lines,snapshotWindow))},{scrollFromPointer,forwardMouse}=useTerminalPointerForward({pty,bodyEl,scrollBy}),visibleRange=import_react25.useMemo(()=>computeViewport(snapshot.length,bodyRows,scrollOffset),[snapshot.length,bodyRows,scrollOffset]),visibleRows=import_react25.useMemo(()=>snapshot.slice(visibleRange.start,visibleRange.end),[snapshot,visibleRange]),visibleCursor=import_react25.useMemo(()=>viewportCursor(cursor,scrollOffset,visibleRange),[cursor,scrollOffset,visibleRange]),[imeCursorRetention]=import_react25.useState(()=>new ImeCursorRetention),imeCursor=imeCursorRetention.update(pty,cursor),visibleImeCursor=import_react25.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}),search=useTerminalSearch({focused,snapshot,snapshotWindow,wrapped,bodyRows,onAlternateScreen:pty?.onAlternateScreen??!1,scrollState,setScrollState}),terminalColors=import_react25.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]),setSnapshotTextEl=useTerminalPaint({visibleRows,firstRow:visibleRange.start,cols:bodyGeometry?.cols??80,selection:selection.selection,paintMatches:search.paint,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});return useTerminalBindings({focused,unfocusedAttachmentTarget,inputModes:()=>pty?.inputModes()??{applicationCursorKeys:!1,applicationKeypad:!1},write:(data)=>{if(!pty||pty.killed)return;pty.write(data),props.onUserInput?.(data)},paste:(text)=>{if(!pty||pty.killed)return;pty.paste(text)},scroll:scrollBy,reset:requestReset,searchActive:search.active,openSearch:search.open,stepSearch:search.step,closeSearch:search.close}),useTerminalHostCursor({pty,bodyEl,bodyGeometry,visibleImeCursor,imeAnchorActive,dims,geomTick}),$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)},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);if(scrollFromPointer(scroll.direction==="up"?-step:step,evt.x,evt.y))selection.noteAppScroll()},children:[exited?$jsx("box",{flexDirection:"row",flexShrink:0,paddingLeft:1,paddingRight:1,children:$jsx("text",{fg:theme.error,wrapMode:"none",children:t3("terminal.exited")})}):null,search.active?$jsx(TerminalSearchBar,{query:search.query,index:search.index,matchCount:search.matchCount,unavailable:search.unavailable}):null,scrollOffset>0&&!search.active?$jsx("box",{position:"absolute",zIndex:10,left:0,right:0,bottom:0,flexDirection:"row",paddingLeft:1,paddingRight:1,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:theme.warning,wrapMode:"none",children:t3("terminal.scrolledBack",{lines:scrollOffset})})}):null,$jsx("box",{ref:(r6)=>setBodyEl(r6),onSizeChange:bumpGeomTick,flexGrow:1,overflow:"hidden",children:pty?$jsx("text",{fg:theme.text,wrapMode:"none",selectable:!1,ref:(r6)=>setSnapshotTextEl(r6)}):$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.textMuted,children:t3("terminal.unavailable.retry")})]}):$jsx("text",{fg:theme.textMuted,children:t3("terminal.noTask")})})})]})}var import_react26=__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),vendors=new Map,misses=new Map,answered=new Set,auxPids=new Map,listeners=new Set,disposed=!1,emit=()=>{for(let l2 of listeners)l2()},store={async probe(){if(disposed)return;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)}let 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)}if(pids.size>0){let rows;try{rows=parsePsSnapshot(await snapshot([...pids.values()]))}catch{if(changed)emit();return}if(disposed)return;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(()=>{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 entry={pty,unsub:()=>{},title:void 0};entry.unsub=pty.onTitleChange((raw)=>{if(entry.title===raw)return;entry.title=raw,emit()}),subs.set(key,entry),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_react26.useRef(null);if(storeRef.current===null)storeRef.current=createTitleSubscriptions();let store=storeRef.current,[titles,setTitles]=import_react26.useState(new Map),ptyKeysRef=useLatest(ptyKeys),reconcile=import_react26.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_react26.useEffect(()=>{let timer=setInterval(reconcile,TITLE_ATTACH_MS);return()=>clearInterval(timer)},[reconcile]),import_react26.useEffect(()=>{reconcile()},[ptyKeys,reconcile]),import_react26.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_react26.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_react27.useState(state.activeLeafId);import_react27.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),useBoxFrames=normalizeSplitStyle(kv.get(SPLIT_STYLE_KEY))==="box"&&isSplit,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_react27.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),dividerProps=(divider,color)=>divider?{border:[divider],borderColor:color}:{border:!1},renderLeaf=(leaf,divider)=>{let focusThis=()=>setActiveLeaf(leaf.id),imeAnchorActive=activeLeaf===leaf.id,focused=leafFocused(leaf.id),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,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?$jsx("box",{position:"absolute",right:0,top:0,zIndex:10,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:focused?theme.focusAccent:theme.textMuted,attributes:focused?TextAttributes5.BOLD:TextAttributes5.DIM,wrapMode:"none",children:` ${leafNames.get(leaf.id)??""} `})}):null]});if(useBoxFrames)return $jsx("box",{flexGrow:1,flexShrink:1,flexBasis:0,...FRAME,borderColor:focused?theme.focusAccent:inactiveBorder,onMouseUp:focusThis,children:body},leaf.id);return divider?$jsx("box",{flexGrow:1,flexShrink:1,flexBasis:0,border:[divider],borderColor:focused?theme.focusAccent:inactiveBorder,onMouseUp:focusThis,children:body},leaf.id):$jsx("box",{flexGrow:1,flexShrink:1,flexBasis:0,border:!1,onMouseUp:focusThis,children:body},leaf.id)},renderNode=(node,groupKey,divider)=>node.kind==="leaf"?renderLeaf(node,divider):$jsx("box",{flexDirection:node.orientation,flexGrow:1,flexShrink:1,flexBasis:0,...dividerProps(useBoxFrames?void 0:divider,inactiveBorder),children:node.children.map((child,i2)=>renderNode(child,child.kind==="leaf"?child.id:`${groupKey}.${i2}`,i2>0?node.orientation==="row"?"left":"top":void 0))},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,onUserInput:props.onUserInput,onExit:props.onExit,resetToken:props.resetToken,focused:props.focused,imeAnchorActive:!0,onRequestFocus:props.onRequestFocus})}var tabsByTask=new Map,tabsRevision=createStateCell(0,"tabs.revision");function setTaskTabs(taskId,state){tabsByTask.set(taskId,state),tabsRevision.update((n2)=>n2+1)}function reviveEmptiedTabs(kv,taskId,shell){let known=knownTabsState(kv,taskId);if(!known||known.tabs.length>0)return!1;return setTaskTabs(taskId,reopenTabs(known,shell)),!0}function deleteTaskTabs(taskId){if(!tabsByTask.delete(taskId))return;tabsRevision.update((n2)=>n2+1)}function activeTabIdFor(taskId){return tabsByTask.get(taskId)?.activeId??null}function knownTabsState(kv,taskId){let live=tabsByTask.get(taskId);if(live)return live;let saved=kv?.store[terminalTabsKey(taskId)];return saved&&Array.isArray(saved.tabs)?saved:null}function knownTaskTab(kv,taskId,tabId){return knownTabsState(kv,taskId)?.tabs.find((tab)=>tab.id===tabId)}function taskTabExists(kv,taskId,tabId){let known=knownTaskTabs(kv,taskId);if(known===null)return;return known.tabs.some((tab)=>tab.id===tabId)}function knownTaskTabs(kv,taskId){let state=knownTabsState(kv,taskId);return state?{tabs:state.tabs,activeId:state.activeId}:null}var tabActivationListeners=new Set;function requestBox(){let pending=null;return{request(taskId,payload){pending={taskId,payload};for(let listener of tabActivationListeners)listener()},take(taskId){if(pending?.taskId!==taskId)return null;let{payload}=pending;return pending=null,payload},takeUnclaimed(){let claimed=pending;return pending=null,claimed}}}var activationBox=requestBox(),openBox=requestBox(),newTabBox=requestBox(),paneCloseBox=requestBox(),tabCloseBox=requestBox(),adoptBox=requestBox(),moveBox=requestBox(),renameBox=requestBox(),requestTabActivation=activationBox.request,takeTabActivation=activationBox.take;function requestTabOpen(taskId,argv,title,placement,direction,tabId){openBox.request(taskId,{argv,title,placement,direction,tabId})}var takeTabOpen=openBox.take,requestNewTab=newTabBox.request,takeNewTab=newTabBox.take;function requestPaneClose(taskId,title,tabId){paneCloseBox.request(taskId,{title,tabId})}var takePaneClose=paneCloseBox.take,requestTabClose=tabCloseBox.request,takeTabClose=tabCloseBox.take;function takeUnclaimedTabClose(){let claimed=tabCloseBox.takeUnclaimed();return claimed&&{taskId:claimed.taskId,tabId:claimed.payload}}var{request:requestTabAdopt,take:takeTabAdopt}=adoptBox;function takeUnclaimedTabAdopt(){let claimed=adoptBox.takeUnclaimed();return claimed&&{taskId:claimed.taskId,tabIds:claimed.payload}}function requestTabMove(taskId,tabId,delta){moveBox.request(taskId,{tabId,delta})}var takeTabMove=moveBox.take;function takeUnclaimedTabMove(){let claimed=moveBox.takeUnclaimed();return claimed&&{taskId:claimed.taskId,...claimed.payload}}function requestTabRename(taskId,tabId,title){renameBox.request(taskId,{tabId,title})}var takeTabRename=renameBox.take;function takeUnclaimedTabRename(){let claimed=renameBox.takeUnclaimed();return claimed&&{taskId:claimed.taskId,...claimed.payload}}var uiEventReporter=null;function setUiEventReporter(fn){uiEventReporter=fn}function tabDetail(tab){return{tabId:tab.id,kind:tab.kind,...tab.title?{title:tab.title}:{},...tab.kind==="engine"&&tab.vendor?{vendor:tab.vendor}:{},...tab.kind==="command"&&tab.purpose?{purpose:tab.purpose}:{}}}function reportTabsDelta(taskId,prev,next){if(!uiEventReporter||prev===next)return;let report=uiEventReporter,prevIds=new Set(prev.map((tab)=>tab.id)),nextIds=new Set(next.map((tab)=>tab.id));for(let tab of next)if(!prevIds.has(tab.id))report("tab.opened",taskId,tabDetail(tab));for(let tab of prev){if(nextIds.has(tab.id))continue;if(report("tab.closed",taskId,tabDetail(tab)),tab.kind==="command"&&tab.purpose==="editor"){let path=[...tab.command].reverse().find((arg)=>arg.startsWith("/"));report("file.closed",taskId,{...path?{path}:{},...tab.title?{title:tab.title}:{}})}}}function forgetTaskTabs(kv,taskId){deleteTaskTabs(taskId),forgetTaskTabsSnapshot(kv,taskId)}function currentTabsState(kv,taskId,shell){let inMemory=tabsByTask.get(taskId);if(inMemory)return inMemory;let saved=kv.store[terminalTabsKey(taskId)];return saved&&Array.isArray(saved.tabs)?rehydrateTabs(saved,[shell]):initialTabs()}function appendBackgroundEngineTab(kv,taskId,shell,spec){let state=currentTabsState(kv,taskId,shell),ordinal=state.nextOrdinal,sessionId=spec.sessionId!==void 0?spec.sessionId:withPinnedSessionId(engineLaunchArgv({vendor:spec.vendor}),spec.vendor).sessionId,tab={kind:"engine",id:`tab-${ordinal}`,title:null,ordinal,vendor:spec.vendor,sessionId,spawned:!0,...spec.ptyTask?{ptyTask:spec.ptyTask}:{}},next={tabs:[...state.tabs,tab],activeId:tab.id,nextOrdinal:ordinal+1};return setTaskTabs(taskId,next),kv.set(terminalTabsKey(taskId),next),reportTabsDelta(taskId,state.tabs,next.tabs),{state:next,tab}}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)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 setTaskTabs(taskId,next),kv.set(terminalTabsKey(taskId),next),reportTabsDelta(taskId,state.tabs,next.tabs),releaseClosedTabPtys(taskId,closing,closedId),!0}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 setTaskTabs(taskId,next),kv.set(terminalTabsKey(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_PROMPTS=createStateCell(null);function useDaemonTabOpens(orch){let request=useAccessor(orch?orch.tabOpenStore():NO_TAB_OPENS),seenAt=import_react28.useRef(null);import_react28.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_react28.useRef(null);import_react28.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_react28.useRef(null);import_react28.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 useDaemonPrompts(orch,dialog){let request=useAccessor(orch?orch.uiPromptStore():NO_PROMPTS),seenAt=import_react28.useRef(null),dialogRef=import_react28.useRef(dialog);dialogRef.current=dialog,import_react28.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),useDaemonPrompts(orch,dialog);let notice=useAccessor(orch?orch.noticeStore():NO_NOTICES),seenAt=import_react28.useRef(null),notifyRef=import_react28.useRef(notify);notifyRef.current=notify,import_react28.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])}var import_react29=__toESM(require_react_production(),1),SORT_MODE_CYCLE=["default","recent","attention"];function readSortMode(stored){return SORT_MODE_CYCLE.find((mode)=>mode===stored)??"default"}function useSidebarHostState(args){let{kv,tasks,setSelectedId}=args,[sortMode,setSortMode]=import_react29.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,setMoveMode]=import_react29.useState(!1);return{sortMode,setSortMode,toggleSortMode,moveMode,setMoveMode,onLocalMergeRequest:(id)=>{if(!tasks.find((t3)=>t3.id===id))return;setSelectedId(id),setMoveMode((cur)=>!cur)}}}import{spawnSync as spawnSync3}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(`
67
+ `)}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,range,wrapped){if(shadow.above.length===0&&shadow.below.length===0)return extractSelection(snapshot,range,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:range.anchor.row+offset,col:range.anchor.col},head:{row:range.head.row+offset,col:range.head.col}},shifted)}function appTookMouse(previouslyOwned,ownedNow){return ownedNow&&!previouslyOwned}function overlaySelection(rows,range,firstRow,width,paint="inverse"){if(!range)return rows;return rows.map((row,i2)=>{let span=rowSpan(range,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)}}function useTerminalPaint(opts){let{visibleRows,firstRow,cols,selection,paintMatches,cursor,focused,colors}=opts,cursorRows=import_react16.useMemo(()=>profileSpan("overlay",()=>{let withSelection=overlaySelection(visibleRows,selection,firstRow,cols),withMatches=paintMatches(withSelection,firstRow,cols);return overlayCursor(withMatches,focused&&!selection?cursor:null,colors)}),[visibleRows,selection,firstRow,cols,paintMatches,cursor,focused,colors]),styledSnapshot=import_react16.useMemo(()=>profileSpan("styled",()=>{let resolved=resolveInverseAttributes(cursorRows,colors.foreground,colors.background),sealed=sealRowEndAttributes(resolved,cols,colors.foreground,colors.background);return new StyledText(rowsToStyledText(sealed))}),[cursorRows,cols,colors]),[snapshotTextEl,setSnapshotTextEl]=import_react16.useState(null);return import_react16.useEffect(()=>{if(snapshotTextEl&&!snapshotTextEl.isDestroyed)profileTick("push"),snapshotTextEl.content=styledSnapshot},[snapshotTextEl,styledSnapshot]),setSnapshotTextEl}var import_react17=__toESM(require_react_production(),1);function useTerminalPointerForward(opts){let{pty,bodyEl,scrollBy}=opts,mouseOwnedByApp=import_react17.useRef(!1),paneCell=(screenX,screenY,body)=>({col:Math.max(1,screenX-body.screenX+1),row:Math.max(1,screenY-body.screenY+1)});return{scrollFromPointer:(lines,screenX,screenY)=>{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)){for(let i2=1;i2<Math.abs(lines);i2++)pty.wheel(direction,col,row);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}}}var import_react18=__toESM(require_react_production(),1);var NO_WRAP=[];function useTerminalPty(opts){let[pty,setPty]=import_react18.useState(null),[acquireError,setAcquireError]=import_react18.useState(null),[snapshot,setSnapshot]=import_react18.useState([]),snapshotWindowRef=import_react18.useRef(null),wrappedRef=import_react18.useRef(NO_WRAP),[cursor,setCursor]=import_react18.useState(null),[exited,setExited]=import_react18.useState(!1),commandRef=useLatest(opts.command),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_react18.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})}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_react18.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_react18.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},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_react18.useRef(!1);return import_react18.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_react20=__toESM(require_react_production(),1);var import_react19=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes4}from"@opentui/core";function titlecase(s2){if(!s2)return s2;return s2.charAt(0).toUpperCase()+s2.slice(1)}function DialogConfirm(props){let dialog=useDialog(),{theme}=useTheme(),t3=useT(),padX=useDialogPaddingX(),[active,setActive]=import_react19.useState(props.initialActive??(props.danger?"cancel":"confirm"));return useBindings(()=>({bindings:[{key:"return",cmd:()=>{if(active==="confirm")props.onConfirm?.();if(active==="cancel")props.onCancel?.();dialog.clear()}},{key:"left",cmd:()=>setActive((a2)=>a2==="confirm"?"cancel":"confirm")},{key:"right",cmd:()=>setActive((a2)=>a2==="confirm"?"cancel":"confirm")}]})),$jsxs("box",{paddingLeft:padX,paddingRight:padX,paddingBottom:1,gap:0,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",children:[$jsx("text",{attributes:TextAttributes4.BOLD,fg:theme.text,children:props.title}),$jsx("text",{fg:theme.textMuted,onMouseUp:()=>dialog.clear(),children:"esc"})]}),$jsx("text",{fg:theme.textMuted,children:props.message}),$jsx("box",{flexDirection:"row",justifyContent:"flex-end",paddingTop:1,children:["cancel","confirm"].map((key)=>{let dangerConfirm=key==="confirm"&&props.danger;return $jsx("box",{paddingLeft:1,paddingRight:1,backgroundColor:key===active?dangerConfirm?theme.error:theme.primary:void 0,onMouseUp:()=>{if(key==="confirm")props.onConfirm?.();if(key==="cancel")props.onCancel?.();dialog.clear()},children:$jsx("text",{fg:key===active?theme.selectedListItemText:dangerConfirm?theme.error:theme.textMuted,children:titlecase(key==="cancel"?props.label??t3("common.cancel"):props.confirmLabel??t3("common.confirm"))})},key)})})]})}DialogConfirm.show=(dialog,title,message,label,confirmLabel,options)=>{return showDialog(dialog,(resolve)=>$jsx(DialogConfirm,{title,message,onConfirm:()=>resolve(!0),onCancel:()=>resolve(!1),label,confirmLabel,danger:options?.danger,initialActive:options?.initialActive}),{size:"small"})};function useTerminalReset(args){let t3=useT(),resetTaskIdRef=useLatest(args.taskId),resetCwdRef=useLatest(args.cwd),mountedRef=import_react20.useRef(!0);return import_react20.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)})}}import{decodePasteBytes as decodePasteBytes2}from"@opentui/core";var import_react22=__toESM(require_react_production(),1);function cellWidth2(text){let cells=0;for(let ch of text)cells+=charWidth(ch.codePointAt(0));return cells}function rowText2(row){let out="";for(let chunk of row)out+=chunk.text;return out}function foldCase(text){let lower=text.toLowerCase();return lower.length===text.length?lower:text}function matchRange(line,at2,to){if(cellWidth2(line.text.slice(at2,to))<=0)return null;let head=rowAtOffset(line,to-1),anchor=rowAtOffset(line,at2),headFrom=Math.max(at2,head.start),headCol=cellWidth2(line.text.slice(head.start,headFrom));return{anchor:{row:anchor.row,col:cellWidth2(line.text.slice(anchor.start,at2))},head:{row:head.row,col:headCol+cellWidth2(line.text.slice(headFrom,to))-1}}}function findMatches(rows,query,wrapped){let needle=foldCase(query);if(needle.length===0)return[];let out=[];for(let line of logicalLines(rows.map((row)=>rowText2(row??[])),wrapped)){let haystack=foldCase(line.text),from=0;for(;;){let at2=haystack.indexOf(needle,from);if(at2<0)break;from=at2+needle.length;let range=matchRange(line,at2,from);if(range)out.push(range)}}return out}function overlayMatches(rows,matches,current,firstRow,width,currentPaint){if(matches.length===0)return rows;let lastRow=firstRow+rows.length-1,out=rows;for(let i2=0;i2<matches.length;i2++){let match=matches[i2];if(match.head.row<firstRow||match.anchor.row>lastRow)continue;out=overlaySelection(out,match,firstRow,width,i2===current?currentPaint:"inverse")}return out}function scrollOffsetForRow(total,height,row){let body=Math.max(1,height),max=Math.max(0,total-body);return Math.min(max,Math.max(0,total-body+Math.floor(body/3)-row))}function parkHit(matches,at2,window2){let match=matches[at2];if(!match)return null;if(!window2)return{kind:"position",at:at2};return{kind:"line",epoch:window2.epoch,line:window2.startLine+match.anchor.row,col:match.anchor.col}}function resolveParkedIndex(parked,matches,window2){if(!parked||matches.length===0)return-1;if(parked.kind==="position")return Math.min(parked.at,matches.length-1);if(!window2||window2.epoch!==parked.epoch)return-1;let fallback=-1;for(let i2=0;i2<matches.length;i2++){let match=matches[i2],line=window2.startLine+match.anchor.row;if(line===parked.line&&match.anchor.col===parked.col)return i2;if(fallback<0&&line>=parked.line)fallback=i2}return fallback>=0?fallback:matches.length-1}var NO_MATCHES=[];function useTerminalSearch(opts){let[active,setActive]=import_react22.useState(!1),[query,setQuery]=import_react22.useState(""),[parked,setParked]=import_react22.useState(null),{theme}=useTheme(),optsRef=useLatest(opts),unavailable=active&&opts.onAlternateScreen,matches=import_react22.useMemo(()=>active&&!unavailable?findMatches(opts.snapshot,query,opts.wrapped):NO_MATCHES,[active,unavailable,opts.snapshot,opts.wrapped,query]),matchesRef=useLatest(matches),index=import_react22.useMemo(()=>resolveParkedIndex(parked,matches,opts.snapshotWindow),[parked,matches,opts.snapshotWindow]),indexRef=useLatest(index),jumpToRow=import_react22.useCallback((row)=>{let{snapshot,bodyRows,snapshotWindow,scrollState,setScrollState}=optsRef.current,target2=scrollOffsetForRow(snapshot.length,bodyRows,row),current=resolveViewportScrollOffset(snapshot.length,bodyRows,scrollState,snapshotWindow);if(current===target2)return;setScrollState(moveViewportScroll(scrollState,snapshot.length,bodyRows,current-target2,snapshotWindow))},[]),bookmarkRef=import_react22.useRef(null),open=import_react22.useCallback(()=>{bookmarkRef.current=optsRef.current.scrollState,setQuery(""),setParked(null),setActive(!0)},[]),close=import_react22.useCallback(()=>{let saved=bookmarkRef.current;if(bookmarkRef.current=null,setActive(!1),setQuery(""),setParked(null),saved)optsRef.current.setScrollState(saved)},[]),step=import_react22.useCallback((delta)=>{let list=matchesRef.current;if(list.length===0)return;let next=(((indexRef.current<0?delta>0?-1:0:indexRef.current)+delta)%list.length+list.length)%list.length;setParked(parkHit(list,next,optsRef.current.snapshotWindow)),jumpToRow(list[next].anchor.row)},[jumpToRow]);import_react22.useEffect(()=>{if(!active)return;let last=matches.length-1;if(setParked(parkHit(matches,last,optsRef.current.snapshotWindow)),last>=0)jumpToRow(matches[last].anchor.row)},[active,query]);let renderer=useRenderer();import_react22.useEffect(()=>{if(!active||!renderer)return;let listener=(evt)=>{if(!optsRef.current.focused||modalActive())return;setQuery((current)=>searchQueryKeystroke(current,evt)??current)},paste=(evt)=>{if(evt.defaultPrevented||!optsRef.current.focused||modalActive())return;let text=decodePasteBytes2(evt.bytes).replace(/[\r\n]+/g," ");setQuery((current)=>current+text),evt.preventDefault()};return renderer.keyInput.on("keypress",listener),renderer.keyInput.on("paste",paste),()=>{renderer.keyInput.off("keypress",listener),renderer.keyInput.off("paste",paste)}},[active,renderer]);let hitPaint=import_react22.useMemo(()=>{let[ar,ag,ab]=theme.accent.toInts(),[br,bg,bb]=theme.background.toInts();return{fg:[br,bg,bb],bg:[ar,ag,ab]}},[theme]),paint=import_react22.useCallback((rows,firstRow,width)=>overlayMatches(rows,matches,index,firstRow,width,hitPaint),[matches,index,hitPaint]);return{active,query,index,matchCount:matches.length,unavailable,open,close,step,paint}}var import_react24=__toESM(require_react_production(),1);import{spawn as spawn2}from"child_process";import{spawnSync as spawnSync2}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 spawnSync2(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((resolve)=>{try{let proc=spawn2(cmd[0],cmd.slice(1),{stdio:["pipe","ignore","ignore"]}),settled=!1,done=(ok)=>{if(settled)return;settled=!0,resolve(ok)};proc.on("error",()=>done(!1)),proc.stdin.on("error",()=>done(!1)),proc.on("close",(code)=>done(code===0)),proc.stdin.end(text)}catch{resolve(!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_react24.useState(null),[selHead,setSelHead]=import_react24.useState(null),draggingRef=import_react24.useRef(!1),anchorRef=import_react24.useRef(null),renderer=useRenderer(),notifications=useOptionalNotifications(),t3=useT(),selection=import_react24.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_react24.useRef(null),appScrolledRef=import_react24.useRef(!1),shadowRef=import_react24.useRef(EMPTY_SHADOW),lastSnapshotRef=import_react24.useRef(opts.snapshot),lastWindowRef=import_react24.useRef(opts.snapshotWindow),autoScrollRef=import_react24.useRef(null),tickRef=import_react24.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_react24.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_react24.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_react24.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_react24.useRef(opts.appOwnsMouse);return import_react24.useEffect(()=>{let took=appTookMouse(appOwnedMouseRef.current,opts.appOwnsMouse);if(appOwnedMouseRef.current=opts.appOwnsMouse,!took)return;stopDragging(),clearSelectionState()},[opts.appOwnsMouse]),import_react24.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}}}function Terminal(props){return $jsx(TerminalSession,{...props},props.taskId)}function TerminalSession(props){let{theme}=useTheme(),t3=useT(),registry=props.registry??getDefaultPtyRegistry(),[focusedLocal,setFocusedLocal]=import_react25.useState(!1),focused=props.focused??focusedLocal,[scrollState,setScrollState]=import_react25.useState(FOLLOW_VIEWPORT),{bodyEl,setBodyEl,bodyRows,bodyGeometry,bumpGeomTick,dims,geomTick}=useTerminalGeometry(),defaultColors=import_react25.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_react25.useMemo(()=>props.terminalPresentation?.alternateScreenStyleRewrites(defaultColors),[props.terminalPresentation,defaultColors]),{pty,snapshot,snapshotWindow,wrapped,cursor,exited,acquireError,forceReacquire}=useTerminalPty({cwd:props.cwd,taskId:props.taskId,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((current)=>moveViewportScroll(current,snapshot.length,bodyRows,lines,snapshotWindow))},{scrollFromPointer,forwardMouse}=useTerminalPointerForward({pty,bodyEl,scrollBy}),visibleRange=import_react25.useMemo(()=>computeViewport(snapshot.length,bodyRows,scrollOffset),[snapshot.length,bodyRows,scrollOffset]),visibleRows=import_react25.useMemo(()=>snapshot.slice(visibleRange.start,visibleRange.end),[snapshot,visibleRange]),visibleCursor=import_react25.useMemo(()=>viewportCursor(cursor,scrollOffset,visibleRange),[cursor,scrollOffset,visibleRange]),[imeCursorRetention]=import_react25.useState(()=>new ImeCursorRetention),imeCursor=imeCursorRetention.update(pty,cursor),visibleImeCursor=import_react25.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}),search=useTerminalSearch({focused,snapshot,snapshotWindow,wrapped,bodyRows,onAlternateScreen:pty?.onAlternateScreen??!1,scrollState,setScrollState}),terminalColors=import_react25.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]),setSnapshotTextEl=useTerminalPaint({visibleRows,firstRow:visibleRange.start,cols:bodyGeometry?.cols??80,selection:selection.selection,paintMatches:search.paint,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});return useTerminalBindings({focused,unfocusedAttachmentTarget,inputModes:()=>pty?.inputModes()??{applicationCursorKeys:!1,applicationKeypad:!1},write:(data)=>{if(process.platform==="win32"&&data==="\x03"&&selection.selection){selection.copySelection(),selection.endDragging(),selection.clearSelection();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:requestReset,searchActive:search.active,openSearch:search.open,stepSearch:search.step,closeSearch:search.close}),useTerminalHostCursor({pty,bodyEl,bodyGeometry,visibleImeCursor,imeAnchorActive,dims,geomTick}),$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)},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);if(scrollFromPointer(scroll.direction==="up"?-step:step,evt.x,evt.y))selection.noteAppScroll()},children:[exited?$jsx("box",{flexDirection:"row",flexShrink:0,paddingLeft:1,paddingRight:1,children:$jsx("text",{fg:theme.error,wrapMode:"none",children:t3("terminal.exited")})}):null,search.active?$jsx(TerminalSearchBar,{query:search.query,index:search.index,matchCount:search.matchCount,unavailable:search.unavailable}):null,scrollOffset>0&&!search.active?$jsx("box",{position:"absolute",zIndex:10,left:0,right:0,bottom:0,flexDirection:"row",paddingLeft:1,paddingRight:1,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:theme.warning,wrapMode:"none",children:t3("terminal.scrolledBack",{lines:scrollOffset})})}):null,$jsx("box",{ref:(r6)=>setBodyEl(r6),onSizeChange:bumpGeomTick,flexGrow:1,overflow:"hidden",children:pty?$jsx("text",{fg:theme.text,wrapMode:"none",selectable:!1,ref:(r6)=>setSnapshotTextEl(r6)}):$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.textMuted,children:t3("terminal.unavailable.retry")})]}):$jsx("text",{fg:theme.textMuted,children:t3("terminal.noTask")})})})]})}var import_react26=__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),vendors=new Map,misses=new Map,answered=new Set,auxPids=new Map,listeners=new Set,disposed=!1,emit=()=>{for(let l2 of listeners)l2()},store={async probe(){if(disposed)return;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)}let 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)}if(pids.size>0){let rows;try{rows=parsePsSnapshot(await snapshot([...pids.values()]))}catch{if(changed)emit();return}if(disposed)return;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(()=>{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 entry={pty,unsub:()=>{},title:void 0};entry.unsub=pty.onTitleChange((raw)=>{if(entry.title===raw)return;entry.title=raw,emit()}),subs.set(key,entry),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_react26.useRef(null);if(storeRef.current===null)storeRef.current=createTitleSubscriptions();let store=storeRef.current,[titles,setTitles]=import_react26.useState(new Map),ptyKeysRef=useLatest(ptyKeys),reconcile=import_react26.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_react26.useEffect(()=>{let timer=setInterval(reconcile,TITLE_ATTACH_MS);return()=>clearInterval(timer)},[reconcile]),import_react26.useEffect(()=>{reconcile()},[ptyKeys,reconcile]),import_react26.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_react26.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_react27.useState(state.activeLeafId);import_react27.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),useBoxFrames=normalizeSplitStyle(kv.get(SPLIT_STYLE_KEY))==="box"&&isSplit,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_react27.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),dividerProps=(divider,color)=>divider?{border:[divider],borderColor:color}:{border:!1},renderLeaf=(leaf,divider)=>{let focusThis=()=>setActiveLeaf(leaf.id),imeAnchorActive=activeLeaf===leaf.id,focused=leafFocused(leaf.id),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,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?$jsx("box",{position:"absolute",right:0,top:0,zIndex:10,backgroundColor:theme.backgroundElement,children:$jsx("text",{fg:focused?theme.focusAccent:theme.textMuted,attributes:focused?TextAttributes5.BOLD:TextAttributes5.DIM,wrapMode:"none",children:` ${leafNames.get(leaf.id)??""} `})}):null]});if(useBoxFrames)return $jsx("box",{flexGrow:1,flexShrink:1,flexBasis:0,...FRAME,borderColor:focused?theme.focusAccent:inactiveBorder,onMouseUp:focusThis,children:body},leaf.id);return divider?$jsx("box",{flexGrow:1,flexShrink:1,flexBasis:0,border:[divider],borderColor:focused?theme.focusAccent:inactiveBorder,onMouseUp:focusThis,children:body},leaf.id):$jsx("box",{flexGrow:1,flexShrink:1,flexBasis:0,border:!1,onMouseUp:focusThis,children:body},leaf.id)},renderNode=(node,groupKey,divider)=>node.kind==="leaf"?renderLeaf(node,divider):$jsx("box",{flexDirection:node.orientation,flexGrow:1,flexShrink:1,flexBasis:0,...dividerProps(useBoxFrames?void 0:divider,inactiveBorder),children:node.children.map((child,i2)=>renderNode(child,child.kind==="leaf"?child.id:`${groupKey}.${i2}`,i2>0?node.orientation==="row"?"left":"top":void 0))},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,onUserInput:props.onUserInput,onExit:props.onExit,resetToken:props.resetToken,focused:props.focused,imeAnchorActive:!0,onRequestFocus:props.onRequestFocus})}var tabsByTask=new Map,tabsRevision=createStateCell(0,"tabs.revision");function setTaskTabs(taskId,state){tabsByTask.set(taskId,state),tabsRevision.update((n2)=>n2+1)}function reviveEmptiedTabs(kv,taskId,shell){let known=knownTabsState(kv,taskId);if(!known||known.tabs.length>0)return!1;return setTaskTabs(taskId,reopenTabs(known,shell)),!0}function deleteTaskTabs(taskId){if(!tabsByTask.delete(taskId))return;tabsRevision.update((n2)=>n2+1)}function activeTabIdFor(taskId){return tabsByTask.get(taskId)?.activeId??null}function knownTabsState(kv,taskId){let live=tabsByTask.get(taskId);if(live)return live;let saved=kv?.store[terminalTabsKey(taskId)];return saved&&Array.isArray(saved.tabs)?saved:null}function knownTaskTab(kv,taskId,tabId){return knownTabsState(kv,taskId)?.tabs.find((tab)=>tab.id===tabId)}function taskTabExists(kv,taskId,tabId){let known=knownTaskTabs(kv,taskId);if(known===null)return;return known.tabs.some((tab)=>tab.id===tabId)}function knownTaskTabs(kv,taskId){let state=knownTabsState(kv,taskId);return state?{tabs:state.tabs,activeId:state.activeId}:null}var tabActivationListeners=new Set;function requestBox(){let pending=null;return{request(taskId,payload){pending={taskId,payload};for(let listener of tabActivationListeners)listener()},take(taskId){if(pending?.taskId!==taskId)return null;let{payload}=pending;return pending=null,payload},takeUnclaimed(){let claimed=pending;return pending=null,claimed}}}var activationBox=requestBox(),openBox=requestBox(),newTabBox=requestBox(),paneCloseBox=requestBox(),tabCloseBox=requestBox(),adoptBox=requestBox(),moveBox=requestBox(),renameBox=requestBox(),requestTabActivation=activationBox.request,takeTabActivation=activationBox.take;function requestTabOpen(taskId,argv,title,placement,direction,tabId){openBox.request(taskId,{argv,title,placement,direction,tabId})}var takeTabOpen=openBox.take,requestNewTab=newTabBox.request,takeNewTab=newTabBox.take;function requestPaneClose(taskId,title,tabId){paneCloseBox.request(taskId,{title,tabId})}var takePaneClose=paneCloseBox.take,requestTabClose=tabCloseBox.request,takeTabClose=tabCloseBox.take;function takeUnclaimedTabClose(){let claimed=tabCloseBox.takeUnclaimed();return claimed&&{taskId:claimed.taskId,tabId:claimed.payload}}var{request:requestTabAdopt,take:takeTabAdopt}=adoptBox;function takeUnclaimedTabAdopt(){let claimed=adoptBox.takeUnclaimed();return claimed&&{taskId:claimed.taskId,tabIds:claimed.payload}}function requestTabMove(taskId,tabId,delta){moveBox.request(taskId,{tabId,delta})}var takeTabMove=moveBox.take;function takeUnclaimedTabMove(){let claimed=moveBox.takeUnclaimed();return claimed&&{taskId:claimed.taskId,...claimed.payload}}function requestTabRename(taskId,tabId,title){renameBox.request(taskId,{tabId,title})}var takeTabRename=renameBox.take;function takeUnclaimedTabRename(){let claimed=renameBox.takeUnclaimed();return claimed&&{taskId:claimed.taskId,...claimed.payload}}var uiEventReporter=null;function setUiEventReporter(fn){uiEventReporter=fn}function tabDetail(tab){return{tabId:tab.id,kind:tab.kind,...tab.title?{title:tab.title}:{},...tab.kind==="engine"&&tab.vendor?{vendor:tab.vendor}:{},...tab.kind==="command"&&tab.purpose?{purpose:tab.purpose}:{}}}function reportTabsDelta(taskId,prev,next){if(!uiEventReporter||prev===next)return;let report=uiEventReporter,prevIds=new Set(prev.map((tab)=>tab.id)),nextIds=new Set(next.map((tab)=>tab.id));for(let tab of next)if(!prevIds.has(tab.id))report("tab.opened",taskId,tabDetail(tab));for(let tab of prev){if(nextIds.has(tab.id))continue;if(report("tab.closed",taskId,tabDetail(tab)),tab.kind==="command"&&tab.purpose==="editor"){let path=[...tab.command].reverse().find((arg)=>arg.startsWith("/"));report("file.closed",taskId,{...path?{path}:{},...tab.title?{title:tab.title}:{}})}}}function forgetTaskTabs(kv,taskId){deleteTaskTabs(taskId),forgetTaskTabsSnapshot(kv,taskId)}function currentTabsState(kv,taskId,shell){let inMemory=tabsByTask.get(taskId);if(inMemory)return inMemory;let saved=kv.store[terminalTabsKey(taskId)];return saved&&Array.isArray(saved.tabs)?rehydrateTabs(saved,[shell]):initialTabs()}function appendBackgroundEngineTab(kv,taskId,shell,spec){let state=currentTabsState(kv,taskId,shell),ordinal=state.nextOrdinal,sessionId=spec.sessionId!==void 0?spec.sessionId:withPinnedSessionId(engineLaunchArgv({vendor:spec.vendor}),spec.vendor).sessionId,tab={kind:"engine",id:`tab-${ordinal}`,title:null,ordinal,vendor:spec.vendor,sessionId,spawned:!0,...spec.ptyTask?{ptyTask:spec.ptyTask}:{}},next={tabs:[...state.tabs,tab],activeId:tab.id,nextOrdinal:ordinal+1};return setTaskTabs(taskId,next),kv.set(terminalTabsKey(taskId),next),reportTabsDelta(taskId,state.tabs,next.tabs),{state:next,tab}}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)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 setTaskTabs(taskId,next),kv.set(terminalTabsKey(taskId),next),reportTabsDelta(taskId,state.tabs,next.tabs),releaseClosedTabPtys(taskId,closing,closedId),!0}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 setTaskTabs(taskId,next),kv.set(terminalTabsKey(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_PROMPTS=createStateCell(null);function useDaemonTabOpens(orch){let request=useAccessor(orch?orch.tabOpenStore():NO_TAB_OPENS),seenAt=import_react28.useRef(null);import_react28.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_react28.useRef(null);import_react28.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_react28.useRef(null);import_react28.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 useDaemonPrompts(orch,dialog){let request=useAccessor(orch?orch.uiPromptStore():NO_PROMPTS),seenAt=import_react28.useRef(null),dialogRef=import_react28.useRef(dialog);dialogRef.current=dialog,import_react28.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),useDaemonPrompts(orch,dialog);let notice=useAccessor(orch?orch.noticeStore():NO_NOTICES),seenAt=import_react28.useRef(null),notifyRef=import_react28.useRef(notify);notifyRef.current=notify,import_react28.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])}var import_react29=__toESM(require_react_production(),1),SORT_MODE_CYCLE=["default","recent","attention"];function readSortMode(stored){return SORT_MODE_CYCLE.find((mode)=>mode===stored)??"default"}function useSidebarHostState(args){let{kv,tasks,setSelectedId}=args,[sortMode,setSortMode]=import_react29.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,setMoveMode]=import_react29.useState(!1);return{sortMode,setSortMode,toggleSortMode,moveMode,setMoveMode,onLocalMergeRequest:(id)=>{if(!tasks.find((t3)=>t3.id===id))return;setSelectedId(id),setMoveMode((cur)=>!cur)}}}import{spawnSync as spawnSync3}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(`
68
68
  ${opts.notice}
69
69
  `);let execve=process.execve;if(execve)try{execve(command,argv,opts.env??process.env)}catch{}let result=spawnSync3(command,args,{stdio:"inherit",env:opts.env??process.env});if(result.error)process.stderr.write(`
70
70
  rove: could not relaunch (${result.error.message})
@@ -161,4 +161,4 @@ ${body}`}).join(`
161
161
  `)}function renderCIPrompt(template,state){let replacements={branch:state.branch,prSentence:prSentence(state.prNumber),jobsSentence:jobsSentence(state),logs:logs(state.checks)};return template.replace(/\{\{([a-zA-Z][a-zA-Z0-9_]*)\}\}/g,(match,key)=>Object.hasOwn(replacements,key)?replacements[key]:match)}var CI_INSTRUCTION_FILENAME="ci-instructions.md";function loadTemplate2(worktree){return readFirstNonEmptyRepoFile(worktree,CI_INSTRUCTION_FILENAME)??DEFAULT_CI_PROMPT_TEMPLATE}async function buildCIPromptForWorktree(worktree,state){return renderCIPrompt(loadTemplate2(worktree),state)}function firstLine(detail){return detail.split(`
162
162
  `).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,send=deps.sendToEngineFn.current,task=deps.getTask(taskId);if(!wt||!send||!task)return;let{checks,totalFailing,unavailable}=await deps.fetchChecks(taskId);if(unavailable)return deps.notifyError(deps.t("files.toast.ciChecksUnavailable",{detail:firstLine(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!==send)return;send(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 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_react109.useRef(null),sendToEngineFn=import_react109.useRef(null),pasteToEngineFn=import_react109.useRef(null),openDiffTabFn=import_react109.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)}),{openFileInEditor,openDiff}=useFileOpenActions({orch:orchestrator,worktree,selectedId,focus,openEditorTabFn,openDiffTabFn,selectedWorktreeRef});return{onEditorTabReady:(open)=>{openEditorTabFn.current=open},onEngineSendReady:(send)=>{if(sendToEngineFn.current=send,takeCreatePR(selectedId))createPR();let parked=takeFixCI(selectedId);if(parked)fixCI(parked)},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)},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_react112=__toESM(require_react_production(),1);import{TextAttributes as TextAttributes36}from"@opentui/core";var import_react111=__toESM(require_react_production(),1);function itemColor(state,theme){if(state==="permission_needed")return theme.warning;if(state==="turn_complete")return theme.success;if(state==="rate_limited")return theme.warning;return theme.error}function itemGlyph(state){if(state==="permission_needed")return"?";if(state==="turn_complete")return"\u2713";if(state==="rate_limited")return"\u25F7";if(state==="dead")return"\u2020";if(state==="routine_failed")return"\u21BB";return"!"}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";return"workspace.inbox.state.error"}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"})})}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 tabLabel(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;let frames=DEFAULT_SPINNER_FRAMES;return{glyph:frames[opts.frame%frames.length]??frames[0]??"\u280B",label:opts.t("workspace.inbox.state.running"),color:opts.theme.textMuted}}var NOOP_SUBSCRIBE2=()=>()=>{},ZERO_FRAME2=()=>0;function useSpinnerFrame2(active){return import_react111.useSyncExternalStore(active?subscribeSpinnerFrame:NOOP_SUBSCRIBE2,active?spinnerFrameSnapshot:ZERO_FRAME2)}function InboxCard(props){let{theme}=useTheme(),dimensions=useTerminalDimensions(),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=resolveRowSelectionChrome(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?TextAttributes36.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=useTerminalDimensions(),[cursor,setCursor]=import_react111.useState(0),[now,setNow]=import_react111.useState(()=>Date.now()),{availableItems}=import_react111.useMemo(()=>partitionAttentionInboxAvailability(props.items,props.tasks,(taskId,tabId)=>taskTabExists(props.kv,taskId,tabId)),[props.items,props.tasks,props.kv]),visits=import_react111.useMemo(()=>readInboxVisits(props.kv),[props.kv]),selectedTabId=props.selectedId?activeTabIdFor(props.selectedId):null,rows=import_react111.useMemo(()=>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]),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),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_react111.useEffect(()=>{if(cursor!==safeCursor)setCursor(safeCursor)},[cursor,safeCursor]),import_react111.useEffect(()=>{let timer2=setInterval(()=>setNow(Date.now()),AGE_REFRESH_MS);return()=>clearInterval(timer2)},[]);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,tabLabel(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")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:TextAttributes36.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:TextAttributes36.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,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=tabLabel(item,task,props.kv),routine=item.detail?.routine,title=routine?.name??task?.title??item.taskId??"",resumeNote=quotaResumeNote(item.state,task,t3),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:contextLine,badge:{glyph:itemGlyph(item.state),label:t3(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:selected()?.kind==="attention"?void 0:TextAttributes36.DIM,wrapMode:"none",children:t3("workspace.inbox.clearHint")})]})]})}function AttentionInboxDialog(props){let dialog=useDialog(),kv=useKV(),items=useAccessor(props.orchestrator.attentionInboxSignal()),tasks=useAccessor(props.orchestrator.tasksSignal()),engineStates=useAccessor(props.orchestrator.engineStateSignal());return $jsx(AttentionInboxPane,{items,tasks,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){let automationId=item.detail?.routine?.automationId;if(item.state==="routine_failed"&&automationId)return rpc.dismissRoutineAttention(automationId);return item.taskId===null?Promise.resolve(!1):rpc.dismissAttention(item.taskId,item.tabId,item.at)}function episodeKey(item){return`${attentionInboxKey(item)}\x00${item.at}`}function episodeSignature(items){return items.map(episodeKey).sort().join(`
163
163
  `)}function useInboxHost(args){let{orchestrator:orch}=args,t3=useT(),{availableItems,unavailableItems}=import_react112.useMemo(()=>partitionAttentionInboxAvailability(args.items,args.tasks,(taskId,tabId)=>taskTabExists(args.kv,taskId,tabId)),[args.items,args.tasks,args.kv]),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,counts2=attentionInboxCounts(visibleItems),notifyErrorRef=useLatest(args.notifyError),unavailableItemsRef=useLatest(unavailableItems),unavailableSignature=episodeSignature(unavailableItems),attemptedUnavailable=import_react112.useRef(new Set);import_react112.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(item.state==="routine_failed"){if(notifyInboxRpcFailure(dismissEpisode(item,orch),"dismiss",args.notifyError),args.dialog.stack.length>0)args.dialog.clear({refocus:!1});args.openAutomations();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 show12(){AttentionInboxDialog.show(args.dialog,{orchestrator:orch,selectedId:args.selectedId,onOpen:openItem,onOpenTask:openTask,onDelete:(item)=>notifyInboxRpcFailure(dismissEpisode(item,orch),"dismiss",args.notifyError)})}let availableItemsRef=useLatest(availableItems),availableSignature=episodeSignature(availableItems),selectedIdRef=useLatest(args.selectedId),attemptedResolved=import_react112.useRef(new Set),resolveEpisodes=import_react112.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_react112.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:counts2,openItem,show:show12,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]},spawn6=engineTabSpawnFor(state,tab,base,{live:!1,shell:input.shell??defaultShell(),prompt:issueWorktreePrompt2(input.issue,input.api),task:{id:input.taskId,kind:"task",vendor:input.vendor,repo:input.repoRoot},worktreePath:input.worktreePath});return{ptyKey:tabPtyKey(input.taskId,tab.id),command:spawn6.command,initialInput:spawn6.initialInput,firstMessage:spawn6.firstMessage,engineBin:spawn6.engineBin,tabsSnapshot:setTabSpawned(state,tab.id,!0)}}function buildIssueTabSpawn(input){let base=interactiveEngineCommand(input.vendor),fresh={...input.tab,spawned:!1},synthetic={tabs:[fresh],activeId:fresh.id,nextOrdinal:fresh.ordinal+1},spawn6=engineTabSpawnFor(synthetic,fresh,base,{live:!1,shell:input.shell??defaultShell(),prompt:input.prompt,task:{id:input.taskId,kind:"main",vendor:input.vendor,repo:input.repoRoot},worktreePath:input.worktreePath});return{ptyKey:tabPtyKey(input.taskId,fresh.id),command:spawn6.command,firstMessage:spawn6.firstMessage,engineBin:spawn6.engineBin}}function useIssueChat(orch,hooks){let t3=useT(),kv=useKV();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.setVendor(main.id,vendor),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{tab}=appendBackgroundEngineTab(kv,main.id,defaultShell(),{vendor}),spawn6=buildIssueTabSpawn({taskId:main.id,repoRoot,worktreePath:main.worktreePath,tab,vendor,prompt:issueProjectPrompt2(issue,api)});getDefaultPtyRegistry().acquire(spawn6.ptyKey,main.worktreePath,{command:spawn6.command,firstMessage:spawn6.firstMessage,engineBin:spawn6.engineBin}),await finish(request,main.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),spawn6=buildIssueChatBackgroundSpawn({issue,taskId:task.id,repoRoot,worktreePath,vendor,api});return getDefaultPtyRegistry().acquire(spawn6.ptyKey,worktreePath,{command:spawn6.command,initialInput:spawn6.initialInput,firstMessage:spawn6.firstMessage,engineBin:spawn6.engineBin}),kv.set(terminalTabsKey(task.id),spawn6.tabsSnapshot),{task,worktreePath,tab:spawn6.tabsSnapshot.tabs[0]}}async function start(request){try{let api=kobeApiInvocation();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);appendBackgroundEngineTab(kv,main.id,defaultShell(),{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_react113=__toESM(require_react_production(),1);function usePrCheckNotifier(args){let notif=useLatest(args.notif),t3=useLatest(useT()),prev=import_react113.useRef(new Map);import_react113.useEffect(()=>{let next=new Map;for(let task of args.tasks){let state=task.prStatus?.checkState;if(state===void 0)continue;next.set(task.id,state);let landed=checkResolutionNotify(prev.current.get(task.id),state);if(!landed)continue;notif.current.notify({kind:landed==="passing"?"done":"error",taskId:task.id,tabId:"",title:t3.current(landed==="passing"?"tasks.toast.checksPassingTitle":"tasks.toast.checksFailingTitle",{title:task.title}),body:t3.current("tasks.toast.checksResolvedBody",{pr:task.prStatus?.number===void 0?"\u2014":`#${task.prStatus.number}`,branch:task.branch||"\u2014"})})}prev.current=next},[args.tasks])}import{homedir as homedir2}from"os";var import_react114=__toESM(require_react_production(),1);import{readlinkSync}from"fs";function parseLsofCwd(output){for(let line of output.split(`
164
- `))if(line.startsWith("n")&&line.length>1)return line.slice(1);return null}var lsofCwd=async(pid)=>{let proc=Bun.spawn(["lsof","-a","-p",String(pid),"-d","cwd","-Fn"],{stdout:"pipe",stderr:"ignore"});return await new Response(proc.stdout).text()};async function processCwd(pid,lsof=lsofCwd){if(!Number.isInteger(pid)||pid<=0)return null;try{return readlinkSync(`/proc/${pid}/cwd`)}catch{}try{return parseLsofCwd(await lsof(pid))}catch{return null}}function decideScratchAdopt(input){if(!input.repoRoot||!input.harnessLive)return{kind:"stay"};let owners=input.ownerTasks.filter((task)=>task.dir!=="");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.KOBE_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),next=1+(knownTaskTabs(io.kv,targetTaskId)?.tabs??[]).reduce((max,tab)=>Math.max(max,tabNumber(tab.id)),0),folded=[];for(let tabId of scratchTabIds){let from=tabPtyKey(scratchTaskId,tabId),ok=await rename(from,tabPtyKey(targetTaskId,`tab-${next}`));if(!ok)next++,ok=await rename(from,tabPtyKey(targetTaskId,`tab-${next}`));if(!ok)continue;folded.push(`tab-${next}`),next++}if(folded.length===0)return null;return adoptTaskTabs(io.kv,targetTaskId,folded),{activeTabId:folded[0]}}var POLL_MS4=5000;function scratchOwnerTasks(tasks){return tasks.filter((task)=>!task.deletion&&task.scratch!==!0&&task.worktreePath!=="").map((task)=>({id:task.id,kind:task.kind??"task",dir:canonPath(task.worktreePath)}))}function useScratchAdopt(deps){let{tasks,orchestrator,kv,notifyInfo}=deps,onFoldRef=useLatest(deps.onFold),enabled=deps.enabled??!0,scratchIds=tasks.filter((t3)=>t3.kind==="dir"&&t3.scratch===!0).map((t3)=>t3.id).join(",");import_react114.useEffect(()=>{if(!enabled||scratchIds==="")return;let cancelled=!1,inFlight=new Set,tick2=async()=>{let scratch=tasks.filter((t3)=>t3.kind==="dir"&&t3.scratch===!0);if(scratch.length===0)return;let known=new Set([...getSavedRepos(),...tasks.map((t3)=>t3.repo)]),owners=scratchOwnerTasks(tasks),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)}}};tick2();let timer2=setInterval(()=>void tick2(),POLL_MS4);return()=>{cancelled=!0,clearInterval(timer2)}},[enabled,scratchIds,orchestrator,kv,notifyInfo,tasks])}var scratchTeardowns=new Set;function useScratchShell(deps){let{orchestrator,enterTask,forgetTaskTabs:forgetTaskTabs2,notifyError}=deps;return 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)}}),{openScratchShell:()=>{orchestrator.openDirectoryTask({dir:homedir2(),scratch:!0}).then((task)=>enterTask(task.id)).catch((err)=>notifyError(t("tasks.toast.scratchOpenFailed",{message:userFacingErrorMessage(err)})))},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)}))}})()}}}var import_react115=__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(tasks,activeId,lastActiveId){let alive=(id)=>id?tasks.find((task)=>task.id===id&&!task.deletion):void 0,active=alive(activeId)??alive(lastActiveId);if(active)return active;let live=tasks.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)??tasks.find((task)=>!task.deletion)}function useWorkspaceSelection(args){let{orch,tasks,activeTaskId,kv}=args,t3=useT(),[selectedId,setSelectedId]=import_react115.useState(()=>orch.activeTaskSignal()()??readLastActiveTaskId()),focusRestoredRef=import_react115.useRef(!1),userPickedRef=import_react115.useRef(!1),bootFocusRef=import_react115.useRef(!1);import_react115.useEffect(()=>{if(!focusRestoredRef.current&&activeTaskId&&tasks.some((task)=>task.id===activeTaskId)){if(focusRestoredRef.current=!0,!userPickedRef.current&&selectedId!==activeTaskId){setSelectedId(activeTaskId);return}}if(!bootFocusRef.current&&!userPickedRef.current&&selectedId&&tasks.some((task)=>task.id===selectedId))bootFocusRef.current=!0,args.focusWorkspace();if(selectedId&&tasks.some((task)=>task.id===selectedId&&!task.deletion))return;setSelectedId(firstSelectableTask(tasks,activeTaskId,readLastActiveTaskId())?.id??null)},[tasks,activeTaskId,selectedId,args.focusWorkspace]),import_react115.useEffect(()=>{if(tasks.length===0)return;sweepOrphanTabsSnapshots(kv,tasks.map((task)=>task.id))},[tasks,kv]);let notifyWorktreeGoneRef=useLatest(args.notifyWorktreeGone),liveTaskIdsRef=import_react115.useRef(new Set),worktreePathsRef=import_react115.useRef(new Map);import_react115.useEffect(()=>{let next=new Set(tasks.filter((task)=>!task.deletion).map((task)=>task.id)),registry=getDefaultPtyRegistry();for(let id of liveTaskIdsRef.current)if(!next.has(id))registry.releaseWhere((key)=>key===id||key.startsWith(`${id}::`));liveTaskIdsRef.current=next;let paths=new Map;for(let task of tasks)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=tasks.find((candidate)=>candidate.id===id);notifyWorktreeGoneRef.current?.({taskId:id,title:task?.title??id,branch:task?.branch??"",closed})}worktreePathsRef.current=paths},[tasks,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=tasks.find((task)=>task.id===id)?.kind==="main"?"project.opened":"task.opened";orch.reportUiEvent(kind,id)}let activationGenerationRef=import_react115.useRef(0);async function activateTask(id){let generation=++activationGenerationRef.current;reviveEmptiedTabs(kv,id,defaultShell()),await activateWorkspaceTask({getTask:(taskId)=>tasks.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?tasks.find((task)=>task.id===selectedId):void 0;return{selectedId,setSelectedId,selectedTask,selectTask,activateTask}}var import_react116=__toESM(require_react_production(),1);function useZenMode(deps){let{kv,focus}=deps,[zen,setZen]=import_react116.useState(()=>kv.get(ZEN_ACTIVE_KEY,!1)===!0);function toggleZen(){let next=!zen;if(setZen(next),kv.set(ZEN_ACTIVE_KEY,next),next)focus.setFocused("workspace")}return import_react116.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=useTerminalDimensions(),renderer=useRenderer(),notif=useNotifications(),orch=props.orchestrator;useDaemonNotices(orch,notif.notify,dialog);let{tasks,activeTaskId,engineState,engineLifecycle,engineTabState,sidebarEngineState,inboxItems,taskJobs,worktreeChanges:worktreeChanges2,transcriptActivity}=useDaemonState(orch),[searchActive,setSearchActive]=import_react118.useState(!1),t3=useT(),{notifyError,notifyInfo,notifyNeedsInput,notifyWorktreeGone}=useHostNotifiers({notif,t:t3,selectedId:()=>selectedId}),{selectedId,setSelectedId,selectedTask,selectTask,activateTask}=useWorkspaceSelection({orch,tasks,activeTaskId,focusWorkspace:()=>focus.setFocused("workspace"),kv,notifyWorktreeGone,notifyError}),worktree=selectedTask?.worktreePath||null,{sortMode,toggleSortMode,moveMode,setMoveMode,onLocalMergeRequest}=useSidebarHostState({kv,tasks,setSelectedId}),inbox=useInboxHost({orchestrator:orch,items:inboxItems,tasks,kv,dialog,selectedId,selectTask,openAutomations:()=>pages.openAutomations(),focusWorkspace:()=>focus.setFocused("workspace"),notifyError}),{jumpToNextAttention}=useAttention({tasks,engineState,engineTabState,inboxItems:inbox.availableItems,selectedId,kv,notif,openAttention:inbox.openItem,noTasksMessage:t3("workspace.attention.none")});usePrCheckNotifier({tasks,notif});let taskActions=useWorkspaceTaskActions({orchestrator:orch,tasks:()=>tasks,dialog,notifyError,notifyInfo,notifyNeedsInput,t:t3,selectedId:()=>selectedId,setSelectedId,selectedTask:()=>selectedTask,activateTask,forgetTaskTabs:(id)=>forgetTaskTabs(kv,id)}),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,kv,selectedId:()=>selectedId,selectTask:setSelectedId,enterTask:(id)=>void activateTask(id),forgetTaskTabs:(id)=>forgetTaskTabs(kv,id),notifyError,notifyInfo}),{zen,toggleZen}=useZenMode({kv,focus});import_react118.useEffect(()=>{return setUiEventReporter((kind,taskId,detail)=>orch.reportUiEvent(kind,taskId,detail)),()=>setUiEventReporter(null)},[orch]);let pages=useHostPagesState(focus),selectedTabId=selectedId===null?null:activeTabIdFor(selectedId),issueChat=useIssueChat(orch,{selectTask:setSelectedId,enterTask:activateTask,closeKanban:pages.closeKanban,notifyError,notifyInfo}),pageRender=useHostPagesRender({orchestrator:orch,pages,focus,dialog,kv,dims,selectedTask,activeTaskId,tasks,engineState,startIssueChat:issueChat.start,activateTask}),openTaskWorktree=(id)=>openTaskWorktreeFor(id,{tasks,ensureWorktree:orch.ensureWorktree.bind(orch),notifyError}),cursorTaskIdRef=import_react118.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,createPR:()=>void editor.onCreatePR(),createPRFor:(id)=>{requestCreatePR(id),activateTask(id)},fixChecksFor:editor.onFixChecks,syncBaseFor:(id)=>void taskActions.syncBase(id),enterMoveMode:()=>{let target2=selectedId??tasks[0]?.id;if(!target2)return;focus.setFocused("sidebar"),setSelectedId(String(target2)),setMoveMode(!0)},toggleSortMode,refresh:{available:banner.refresh.available,run:refreshRove}});let activePane=dialog.stack.length>0?null:focus.focused,fullWindow=pageRender.settingsPage??pageRender.fullWindowPage;if(fullWindow)return $jsx(FullWindowPage,{banner:banner.element,background:theme.background,children:fullWindow});return $jsxs(WorkspaceFrame,{orchestrator:orch,onOpenSettings:pages.openSettings,banner:banner.element,activeTaskId:selectedId,activeTabId:selectedTabId,children:[pageRender.showSidebar?$jsx(HostSidebarMount,{terminalWidth:dims.width,showContent:pageRender.showContent,recentTask:pageRender.recentTask,tasks,selectedId,selectedTabId,selectTask,activateTask,daemon:{sidebarEngineState,engineTabState,engineLifecycle,taskJobs,worktreeChanges:worktreeChanges2,transcriptActivity},actions:taskActions,pages,focus,inbox,update:banner.update,onFixChecks:editor.onFixChecks,runAgain:quickFork.runAgain,activePane,zen,toggleZen,sortMode,moveMode,exitMoveMode:()=>setMoveMode(!1),onLocalMergeRequest,onSearchActiveChange:setSearchActive,cursorTaskIdRef,openTaskWorktree,t:t3}):null,pageRender.showContent?$jsx("box",{flexGrow:1,flexShrink:1,borderStyle:"rounded",borderColor:focus.focused==="workspace"?theme.focusAccent:inactiveBorder,onMouseUp:()=>focus.setFocused("workspace"),children:pageRender.contentPage??$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,onQuickFork:quickFork.onQuickFork,initialPrompt:quickFork.initialPromptFor(selectedTask?.id),onTabVisited:inbox.resolveVisited,onScratchExit:scratch.onScratchExit,onOpenScratch:scratch.openScratchShell,onEngineChosen:taskActions.setVendor})}):null,!zen&&pageRender.contentPage==null&&pageRender.showSidebar&&pageRender.showContent?$jsx(HostFilesPane,{worktree,prBaseRef:selectedTask?.prStatus?.baseRef,focused:activePane==="files",onOpenFile:(relPath)=>void editor.onOpenFile(relPath),onOpenDiff:editor.onOpenDiff,onMention:editor.onMention,onZenToggle:toggleZen,onCreatePR:()=>void editor.onCreatePR(),taskKind:selectedTask?.kind,remoteHost:selectedTask?.origin&&selectedTask.origin.machineId!=="local"?selectedTask.origin.hostLabel:void 0}):null,$jsx(ToastOverlay,{}),$jsx(PrefixHud,{left:1,width:sidebarWidthFor(dims.width)-2})]})}async function startWorkspaceHost(){await bootPaneHost({logContext:"workspace",providers:{kv:!0,focus:!0,notifications:!0},setup:async()=>{let client=await connectOrStartDaemon(),orchestrator=new RemoteOrchestrator(client,{role:"gui"});await orchestrator.init(),process.env.KOBE_DAEMON_SOCKET_PATH=client.socketPath;let{MachineHub}=await import("./chunk-00zwq5t0.js"),{setMachineHub}=await import("./chunk-e4m00wxs.js"),machines=new MachineHub(orchestrator);return machines.attach(),setMachineHub(machines),{root:()=>$jsx(WorkspaceRoot,{orchestrator}),onDestroy:()=>{setMachineHub(null),machines.dispose(),orchestrator.dispose(),getDefaultPtyRegistry().detachAll()}}}})}export{startWorkspaceHost};
164
+ `))if(line.startsWith("n")&&line.length>1)return line.slice(1);return null}var lsofCwd=async(pid)=>{let proc=Bun.spawn(["lsof","-a","-p",String(pid),"-d","cwd","-Fn"],{stdout:"pipe",stderr:"ignore"});return await new Response(proc.stdout).text()};async function processCwd(pid,lsof=lsofCwd){if(!Number.isInteger(pid)||pid<=0)return null;try{return readlinkSync(`/proc/${pid}/cwd`)}catch{}try{return parseLsofCwd(await lsof(pid))}catch{return null}}function decideScratchAdopt(input){if(!input.repoRoot||!input.harnessLive)return{kind:"stay"};let owners=input.ownerTasks.filter((task)=>task.dir!=="");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.KOBE_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),next=1+(knownTaskTabs(io.kv,targetTaskId)?.tabs??[]).reduce((max,tab)=>Math.max(max,tabNumber(tab.id)),0),folded=[];for(let tabId of scratchTabIds){let from=tabPtyKey(scratchTaskId,tabId),ok=await rename(from,tabPtyKey(targetTaskId,`tab-${next}`));if(!ok)next++,ok=await rename(from,tabPtyKey(targetTaskId,`tab-${next}`));if(!ok)continue;folded.push(`tab-${next}`),next++}if(folded.length===0)return null;return adoptTaskTabs(io.kv,targetTaskId,folded),{activeTabId:folded[0]}}var POLL_MS4=5000;function scratchOwnerTasks(tasks){return tasks.filter((task)=>!task.deletion&&task.scratch!==!0&&task.worktreePath!=="").map((task)=>({id:task.id,kind:task.kind??"task",dir:canonPath(task.worktreePath)}))}function useScratchAdopt(deps){let{tasks,orchestrator,kv,notifyInfo}=deps,onFoldRef=useLatest(deps.onFold),enabled=deps.enabled??!0,scratchIds=tasks.filter((t3)=>t3.kind==="dir"&&t3.scratch===!0).map((t3)=>t3.id).join(",");import_react114.useEffect(()=>{if(!enabled||scratchIds==="")return;let cancelled=!1,inFlight=new Set,tick2=async()=>{let scratch=tasks.filter((t3)=>t3.kind==="dir"&&t3.scratch===!0);if(scratch.length===0)return;let known=new Set([...getSavedRepos(),...tasks.map((t3)=>t3.repo)]),owners=scratchOwnerTasks(tasks),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)}}};tick2();let timer2=setInterval(()=>void tick2(),POLL_MS4);return()=>{cancelled=!0,clearInterval(timer2)}},[enabled,scratchIds,orchestrator,kv,notifyInfo,tasks])}var scratchTeardowns=new Set;function useScratchShell(deps){let{orchestrator,enterTask,forgetTaskTabs:forgetTaskTabs2,notifyError}=deps;return 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)}}),{openScratchShell:()=>{orchestrator.openDirectoryTask({dir:homedir2(),scratch:!0}).then((task)=>enterTask(task.id)).catch((err)=>notifyError(t("tasks.toast.scratchOpenFailed",{message:userFacingErrorMessage(err)})))},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)}))}})()}}}var import_react115=__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(tasks,activeId,lastActiveId){let alive=(id)=>id?tasks.find((task)=>task.id===id&&!task.deletion):void 0,active=alive(activeId)??alive(lastActiveId);if(active)return active;let live=tasks.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)??tasks.find((task)=>!task.deletion)}function useWorkspaceSelection(args){let{orch,tasks,activeTaskId,kv}=args,t3=useT(),[selectedId,setSelectedId]=import_react115.useState(()=>orch.activeTaskSignal()()??readLastActiveTaskId()),focusRestoredRef=import_react115.useRef(!1),userPickedRef=import_react115.useRef(!1),bootFocusRef=import_react115.useRef(!1);import_react115.useEffect(()=>{if(!focusRestoredRef.current&&activeTaskId&&tasks.some((task)=>task.id===activeTaskId)){if(focusRestoredRef.current=!0,!userPickedRef.current&&selectedId!==activeTaskId){setSelectedId(activeTaskId);return}}if(!bootFocusRef.current&&!userPickedRef.current&&selectedId&&tasks.some((task)=>task.id===selectedId))bootFocusRef.current=!0,args.focusWorkspace();if(selectedId&&tasks.some((task)=>task.id===selectedId&&!task.deletion))return;setSelectedId(firstSelectableTask(tasks,activeTaskId,readLastActiveTaskId())?.id??null)},[tasks,activeTaskId,selectedId,args.focusWorkspace]),import_react115.useEffect(()=>{if(tasks.length===0)return;sweepOrphanTabsSnapshots(kv,tasks.map((task)=>task.id))},[tasks,kv]);let notifyWorktreeGoneRef=useLatest(args.notifyWorktreeGone),liveTaskIdsRef=import_react115.useRef(new Set),worktreePathsRef=import_react115.useRef(new Map);import_react115.useEffect(()=>{let next=new Set(tasks.filter((task)=>!task.deletion).map((task)=>task.id)),registry=getDefaultPtyRegistry();for(let id of liveTaskIdsRef.current)if(!next.has(id))registry.releaseWhere((key)=>key===id||key.startsWith(`${id}::`));liveTaskIdsRef.current=next;let paths=new Map;for(let task of tasks)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=tasks.find((candidate)=>candidate.id===id);notifyWorktreeGoneRef.current?.({taskId:id,title:task?.title??id,branch:task?.branch??"",closed})}worktreePathsRef.current=paths},[tasks,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=tasks.find((task)=>task.id===id)?.kind==="main"?"project.opened":"task.opened";orch.reportUiEvent(kind,id)}let activationGenerationRef=import_react115.useRef(0);async function activateTask(id){let generation=++activationGenerationRef.current;reviveEmptiedTabs(kv,id,defaultShell()),await activateWorkspaceTask({getTask:(taskId)=>tasks.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?tasks.find((task)=>task.id===selectedId):void 0;return{selectedId,setSelectedId,selectedTask,selectTask,activateTask}}var import_react116=__toESM(require_react_production(),1);function useZenMode(deps){let{kv,focus}=deps,[zen,setZen]=import_react116.useState(()=>kv.get(ZEN_ACTIVE_KEY,!1)===!0);function toggleZen(){let next=!zen;if(setZen(next),kv.set(ZEN_ACTIVE_KEY,next),next)focus.setFocused("workspace")}return import_react116.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=useTerminalDimensions(),renderer=useRenderer(),notif=useNotifications(),orch=props.orchestrator;useDaemonNotices(orch,notif.notify,dialog);let{tasks,activeTaskId,engineState,engineLifecycle,engineTabState,sidebarEngineState,inboxItems,taskJobs,worktreeChanges:worktreeChanges2,transcriptActivity}=useDaemonState(orch),[searchActive,setSearchActive]=import_react118.useState(!1),t3=useT(),{notifyError,notifyInfo,notifyNeedsInput,notifyWorktreeGone}=useHostNotifiers({notif,t:t3,selectedId:()=>selectedId}),{selectedId,setSelectedId,selectedTask,selectTask,activateTask}=useWorkspaceSelection({orch,tasks,activeTaskId,focusWorkspace:()=>focus.setFocused("workspace"),kv,notifyWorktreeGone,notifyError}),worktree=selectedTask?.worktreePath||null,{sortMode,toggleSortMode,moveMode,setMoveMode,onLocalMergeRequest}=useSidebarHostState({kv,tasks,setSelectedId}),inbox=useInboxHost({orchestrator:orch,items:inboxItems,tasks,kv,dialog,selectedId,selectTask,openAutomations:()=>pages.openAutomations(),focusWorkspace:()=>focus.setFocused("workspace"),notifyError}),{jumpToNextAttention}=useAttention({tasks,engineState,engineTabState,inboxItems:inbox.availableItems,selectedId,kv,notif,openAttention:inbox.openItem,noTasksMessage:t3("workspace.attention.none")});usePrCheckNotifier({tasks,notif});let taskActions=useWorkspaceTaskActions({orchestrator:orch,tasks:()=>tasks,dialog,notifyError,notifyInfo,notifyNeedsInput,t:t3,selectedId:()=>selectedId,setSelectedId,selectedTask:()=>selectedTask,activateTask,forgetTaskTabs:(id)=>forgetTaskTabs(kv,id)}),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,kv,selectedId:()=>selectedId,selectTask:setSelectedId,enterTask:(id)=>void activateTask(id),forgetTaskTabs:(id)=>forgetTaskTabs(kv,id),notifyError,notifyInfo}),{zen,toggleZen}=useZenMode({kv,focus});import_react118.useEffect(()=>{return setUiEventReporter((kind,taskId,detail)=>orch.reportUiEvent(kind,taskId,detail)),()=>setUiEventReporter(null)},[orch]);let pages=useHostPagesState(focus),selectedTabId=selectedId===null?null:activeTabIdFor(selectedId),issueChat=useIssueChat(orch,{selectTask:setSelectedId,enterTask:activateTask,closeKanban:pages.closeKanban,notifyError,notifyInfo}),pageRender=useHostPagesRender({orchestrator:orch,pages,focus,dialog,kv,dims,selectedTask,activeTaskId,tasks,engineState,startIssueChat:issueChat.start,activateTask}),openTaskWorktree=(id)=>openTaskWorktreeFor(id,{tasks,ensureWorktree:orch.ensureWorktree.bind(orch),notifyError}),cursorTaskIdRef=import_react118.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,createPR:()=>void editor.onCreatePR(),createPRFor:(id)=>{requestCreatePR(id),activateTask(id)},fixChecksFor:editor.onFixChecks,syncBaseFor:(id)=>void taskActions.syncBase(id),enterMoveMode:()=>{let target2=selectedId??tasks[0]?.id;if(!target2)return;focus.setFocused("sidebar"),setSelectedId(String(target2)),setMoveMode(!0)},toggleSortMode,refresh:{available:banner.refresh.available,run:refreshRove}});let activePane=dialog.stack.length>0?null:focus.focused,fullWindow=pageRender.settingsPage??pageRender.fullWindowPage;if(fullWindow)return $jsx(FullWindowPage,{banner:banner.element,background:theme.background,children:fullWindow});return $jsxs(WorkspaceFrame,{orchestrator:orch,onOpenSettings:pages.openSettings,banner:banner.element,activeTaskId:selectedId,activeTabId:selectedTabId,children:[pageRender.showSidebar?$jsx(HostSidebarMount,{terminalWidth:dims.width,showContent:pageRender.showContent,recentTask:pageRender.recentTask,tasks,selectedId,selectedTabId,selectTask,activateTask,daemon:{sidebarEngineState,engineTabState,engineLifecycle,taskJobs,worktreeChanges:worktreeChanges2,transcriptActivity},actions:taskActions,pages,focus,inbox,update:banner.update,onFixChecks:editor.onFixChecks,runAgain:quickFork.runAgain,activePane,zen,toggleZen,sortMode,moveMode,exitMoveMode:()=>setMoveMode(!1),onLocalMergeRequest,onSearchActiveChange:setSearchActive,cursorTaskIdRef,openTaskWorktree,t:t3}):null,pageRender.showContent?$jsx("box",{flexGrow:1,flexShrink:1,borderStyle:"rounded",borderColor:focus.focused==="workspace"?theme.focusAccent:inactiveBorder,onMouseUp:()=>focus.setFocused("workspace"),children:pageRender.contentPage??$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,onQuickFork:quickFork.onQuickFork,initialPrompt:quickFork.initialPromptFor(selectedTask?.id),onTabVisited:inbox.resolveVisited,onScratchExit:scratch.onScratchExit,onOpenScratch:scratch.openScratchShell,onEngineChosen:taskActions.setVendor})}):null,!zen&&pageRender.contentPage==null&&pageRender.showSidebar&&pageRender.showContent?$jsx(HostFilesPane,{worktree,prBaseRef:selectedTask?.prStatus?.baseRef,focused:activePane==="files",onOpenFile:(relPath)=>void editor.onOpenFile(relPath),onOpenDiff:editor.onOpenDiff,onMention:editor.onMention,onZenToggle:toggleZen,onCreatePR:()=>void editor.onCreatePR(),taskKind:selectedTask?.kind,remoteHost:selectedTask?.origin&&selectedTask.origin.machineId!=="local"?selectedTask.origin.hostLabel:void 0}):null,$jsx(ToastOverlay,{}),$jsx(PrefixHud,{left:1,width:sidebarWidthFor(dims.width)-2})]})}async function startWorkspaceHost(){await bootPaneHost({logContext:"workspace",providers:{kv:!0,focus:!0,notifications:!0},setup:async()=>{let client=await connectOrStartDaemon(),orchestrator=new RemoteOrchestrator(client,{role:"gui"});await orchestrator.init(),process.env.KOBE_DAEMON_SOCKET_PATH=client.socketPath;let{MachineHub}=await import("./chunk-s5qy4qxf.js"),{setMachineHub}=await import("./chunk-e4m00wxs.js"),machines=new MachineHub(orchestrator);return machines.attach(),setMachineHub(machines),{root:()=>$jsx(WorkspaceRoot,{orchestrator}),onDestroy:()=>{setMachineHub(null),machines.dispose(),orchestrator.dispose(),getDefaultPtyRegistry().detachAll()}}}})}export{startWorkspaceHost};