@staff0rd/assist 0.284.0 → 0.285.0

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.
package/README.md CHANGED
@@ -253,6 +253,10 @@ The first backlog command in a repository that still has a local `.assist/backlo
253
253
 
254
254
  Web sessions are owned by a long-lived daemon process, not the web server: the server is a thin client that relays WebSocket traffic to the daemon over a local IPC socket (unix domain socket at `~/.assist/daemon/daemon.sock`; named pipe `\\.\pipe\assist-sessions-daemon` on Windows). Restarting the web server leaves sessions running with scrollback intact. The daemon logs to `~/.assist/daemon/daemon.log` (timestamped lines tagged with the daemon's pid, including why it spawned and which sessions it restored) and auto-exits once no sessions remain and no client has been connected for 60 seconds (it is respawned on demand by the web server). Daemon spawning is arbitrated by an `O_EXCL` lockfile so racing clients start at most one daemon; sessions are only restored after the daemon owns the IPC socket, and a daemon that loses ownership of `daemon.pid` shuts down its sessions and exits rather than running orphaned.
255
255
 
256
+ Set `sessions.windowsProjectsRoot` in config to the Windows `.claude/projects` directory as seen from WSL (e.g. `/mnt/c/Users/<user>/.claude/projects`) to surface Windows-host repos in the selector. Their transcripts are discovered alongside local ones and tagged as windows-origin (the project name is derived with Windows path rules so `C:\…` cwds name correctly).
257
+
258
+ Selecting a windows-origin repo (cwd like `C:\…`) from the WSL UI runs an interactive session natively on Windows: the WSL daemon launches a second assist daemon on the Windows host on demand via interop (`cmd.exe /c start "" assist daemon run`), connects to it over TCP (the WSL daemon cannot reach the Windows named pipe directly), and proxies create/resume and I/O to the Windows daemon's native PTY. Windows sessions appear in the same list as local ones (their ids are namespaced internally to avoid collisions) with live output, scrollback, and resume. The TCP connection performs a version handshake on connect; a mismatch is logged (auto-healing comes later). A native Windows daemon listens for the WSL bridge on `sessions.windowsDaemonPort` (default `51764`); the WSL daemon dials `sessions.windowsDaemonHost` (default `127.0.0.1`, which works under WSL2 mirrored networking — NAT-mode setups should set it to the Windows host IP).
259
+
256
260
  When iterating on assist itself: web server changes only need the `assist sessions` process restarted — sessions survive. Daemon/session-core changes need `assist daemon restart` to load the new code; this kills the PTYs, then claude sessions — including assist sessions that wrap claude, like `assist draft` — are auto-respawned via `claude --resume` with scrollback starting fresh, while run sessions (and assist sessions whose claude sessionId was never discovered) reappear as not-restored tiles that can be retried.
257
261
  - `assist next [id] [--once]` - Alias for `backlog next [id]`; `--once` exits after the first completed item run instead of prompting for another
258
262
  - `assist draft [description] [--once]` (alias: `feat`) - Launch Claude in `/draft` mode, chain into next on `/next` signal; an optional `description` is forwarded as `/draft <description>`; `--once` exits when the done signal arrives after the initial draft completes
@@ -235,7 +235,7 @@ ${u.join(`
235
235
  `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),iR&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),r=this._model.finalSelectionStart,o=this._model.finalSelectionEnd;return!r||!o||!t?!1:this._areCoordsInSelection(t,r,o)}isCellInSelection(e,t){let r=this._model.finalSelectionStart,o=this._model.finalSelectionEnd;return!r||!o?!1:this._areCoordsInSelection([e,t],r,o)}_areCoordsInSelection(e,t,r){return e[1]>t[1]&&e[1]<r[1]||t[1]===r[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<r[0]||t[1]<r[1]&&e[1]===r[1]&&e[0]<r[0]||t[1]<r[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let r=this._linkifier.currentLink?.link?.range;if(r)return this._model.selectionStart=[r.start.x-1,r.start.y-1],this._model.selectionStartLength=Mz(r,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let o=this._getMouseBufferCoords(e);return o?(this._selectWordAt(o,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=oR(this._coreBrowserService.window,e,this._screenElement)[1],r=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=r?0:(t>r&&(t-=r),t=Math.min(Math.max(t,-iP),iP),t/=iP,t/Math.abs(t)+Math.round(t*(qre-1)))}shouldForceSelection(e){return A0?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Kre)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(A0&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let r=this._bufferService.buffer;if(this._model.selectionEnd[1]<r.lines.length){let o=r.lines.get(this._model.selectionEnd[1]);o&&o.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(!(!this._model.selectionEnd||!this._model.selectionStart)&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<Gre&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let r=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(r&&r[0]!==void 0&&r[1]!==void 0){let o=zre(r[0]-1,r[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(o,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,r=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!r){this._oldHasSelection&&this._fireOnSelectionChange(e,t,r);return}!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,r)}_fireOnSelectionChange(e,t,r){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=r,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(t=>this._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let r=t;for(let o=0;t>=o;o++){let i=e.loadCell(o,this._workCell).getChars().length;this._workCell.getWidth()===0?r--:i>1&&t!==o&&(r+=i-1)}return r}setSelection(e,t,r){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=r,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,r=!0,o=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,n=i.lines.get(e[1]);if(!n)return;let s=i.translateBufferLineToString(e[1],!1),a=this._convertViewportColToCharacterIndex(n,e[0]),l=a,c=e[0]-a,u=0,p=0,f=0,d=0;if(s.charAt(a)===" "){for(;a>0&&s.charAt(a-1)===" ";)a--;for(;l<s.length&&s.charAt(l+1)===" ";)l++}else{let _=e[0],m=e[0];n.getWidth(_)===0&&(u++,_--),n.getWidth(m)===2&&(p++,m++);let g=n.getString(m).length;for(g>1&&(d+=g-1,l+=g-1);_>0&&a>0&&!this._isCharWordSeparator(n.loadCell(_-1,this._workCell));){n.loadCell(_-1,this._workCell);let v=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,_--):v>1&&(f+=v-1,a-=v-1),a--,_--}for(;m<n.length&&l+1<s.length&&!this._isCharWordSeparator(n.loadCell(m+1,this._workCell));){n.loadCell(m+1,this._workCell);let v=this._workCell.getChars().length;this._workCell.getWidth()===2?(p++,m++):v>1&&(d+=v-1,l+=v-1),l++,m++}}l++;let h=a+c-u+f,y=Math.min(this._bufferService.cols,l-a+u+p-f-d);if(!(!t&&s.slice(a,l).trim()==="")){if(r&&h===0&&n.getCodePoint(0)!==32){let _=i.lines.get(e[1]-1);if(_&&n.isWrapped&&_.getCodePoint(this._bufferService.cols-1)!==32){let m=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(m){let g=this._bufferService.cols-m.start;h-=g,y+=g}}}if(o&&h+y===this._bufferService.cols&&n.getCodePoint(this._bufferService.cols-1)!==32){let _=i.lines.get(e[1]+1);if(_?.isWrapped&&_.getCodePoint(0)!==32){let m=this._getWordAt([0,e[1]+1],!1,!1,!0);m&&(y+=m.length)}}return{start:h,length:y}}}_selectWordAt(e,t){let r=this._getWordAt(e,t);if(r){for(;r.start<0;)r.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[r.start,e[1]],this._model.selectionStartLength=r.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let r=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,r--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,r++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,r]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),r={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Mz(r,this._bufferService.cols)}};FP=er([ne(3,ko),ne(4,nu),ne(5,XP),ne(6,Oo),ne(7,pa),ne(8,ua)],FP);var Dz=class{constructor(){this._data={}}set(e,t,r){this._data[e]||(this._data[e]={}),this._data[e][t]=r}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Az=class{constructor(){this._color=new Dz,this._css=new Dz}setCss(e,t,r){this._css.set(e,t,r)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,r){this._color.set(e,t,r)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Pr=Object.freeze((()=>{let e=[Vt.toColor("#2e3436"),Vt.toColor("#cc0000"),Vt.toColor("#4e9a06"),Vt.toColor("#c4a000"),Vt.toColor("#3465a4"),Vt.toColor("#75507b"),Vt.toColor("#06989a"),Vt.toColor("#d3d7cf"),Vt.toColor("#555753"),Vt.toColor("#ef2929"),Vt.toColor("#8ae234"),Vt.toColor("#fce94f"),Vt.toColor("#729fcf"),Vt.toColor("#ad7fa8"),Vt.toColor("#34e2e2"),Vt.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let r=0;r<216;r++){let o=t[r/36%6|0],i=t[r/6%6|0],n=t[r%6];e.push({css:vr.toCss(o,i,n),rgba:vr.toRgba(o,i,n)})}for(let r=0;r<24;r++){let o=8+r*10;e.push({css:vr.toCss(o,o,o),rgba:vr.toRgba(o,o,o)})}return e})()),Jc=Vt.toColor("#ffffff"),cy=Vt.toColor("#000000"),Bz=Vt.toColor("#ffffff"),Nz=cy,oy={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Zre=Jc,HP=class extends Ee{constructor(e){super(),this._optionsService=e,this._contrastCache=new Az,this._halfContrastCache=new Az,this._onChangeColors=this._register(new J),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:Jc,background:cy,cursor:Bz,cursorAccent:Nz,selectionForeground:void 0,selectionBackgroundTransparent:oy,selectionBackgroundOpaque:Dt.blend(cy,oy),selectionInactiveBackgroundTransparent:oy,selectionInactiveBackgroundOpaque:Dt.blend(cy,oy),scrollbarSliderBackground:Dt.opacity(Jc,.2),scrollbarSliderHoverBackground:Dt.opacity(Jc,.4),scrollbarSliderActiveBackground:Dt.opacity(Jc,.5),overviewRulerBorder:Jc,ansi:Pr.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=ht(e.foreground,Jc),t.background=ht(e.background,cy),t.cursor=Dt.blend(t.background,ht(e.cursor,Bz)),t.cursorAccent=Dt.blend(t.background,ht(e.cursorAccent,Nz)),t.selectionBackgroundTransparent=ht(e.selectionBackground,oy),t.selectionBackgroundOpaque=Dt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=ht(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Dt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?ht(e.selectionForeground,Ez):void 0,t.selectionForeground===Ez&&(t.selectionForeground=void 0),Dt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Dt.opacity(t.selectionBackgroundTransparent,.3)),Dt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Dt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=ht(e.scrollbarSliderBackground,Dt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=ht(e.scrollbarSliderHoverBackground,Dt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=ht(e.scrollbarSliderActiveBackground,Dt.opacity(t.foreground,.5)),t.overviewRulerBorder=ht(e.overviewRulerBorder,Zre),t.ansi=Pr.slice(),t.ansi[0]=ht(e.black,Pr[0]),t.ansi[1]=ht(e.red,Pr[1]),t.ansi[2]=ht(e.green,Pr[2]),t.ansi[3]=ht(e.yellow,Pr[3]),t.ansi[4]=ht(e.blue,Pr[4]),t.ansi[5]=ht(e.magenta,Pr[5]),t.ansi[6]=ht(e.cyan,Pr[6]),t.ansi[7]=ht(e.white,Pr[7]),t.ansi[8]=ht(e.brightBlack,Pr[8]),t.ansi[9]=ht(e.brightRed,Pr[9]),t.ansi[10]=ht(e.brightGreen,Pr[10]),t.ansi[11]=ht(e.brightYellow,Pr[11]),t.ansi[12]=ht(e.brightBlue,Pr[12]),t.ansi[13]=ht(e.brightMagenta,Pr[13]),t.ansi[14]=ht(e.brightCyan,Pr[14]),t.ansi[15]=ht(e.brightWhite,Pr[15]),e.extendedAnsi){let r=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let o=0;o<r;o++)t.ansi[o+16]=ht(e.extendedAnsi[o],Pr[o+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0){for(let t=0;t<this._restoreColors.ansi.length;++t)this._colors.ansi[t]=this._restoreColors.ansi[t];return}switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};HP=er([ne(0,Oo)],HP);function ht(e,t){if(e!==void 0)try{return Vt.toColor(e)}catch{}return t}var Qre=class{constructor(...e){this._entries=new Map;for(let[t,r]of e)this.set(t,r)}set(e,t){let r=this._entries.get(e);return this._entries.set(e,t),r}forEach(e){for(let[t,r]of this._entries.entries())e(t,r)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},Jre=class{constructor(){this._services=new Qre,this._services.set(YP,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let r=bee(e).sort((n,s)=>n.index-s.index),o=[];for(let n of r){let s=this._services.get(n.id);if(!s)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${n.id._id}.`);o.push(s)}let i=r.length>0?r[0].index:t.length;if(t.length!==i)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...o)}},eoe={trace:0,debug:1,info:2,warn:3,error:4,off:5},toe="xterm.js: ",UP=class extends Ee{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),roe=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=eoe[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]=="function"&&(e[t]=e[t]())}_log(e,t,r){this._evalLazyOptionalParams(r),e.call(console,(this._optionsService.options.logger?"":toe)+t,...r)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};UP=er([ne(0,Oo)],UP);var roe,Lz=class extends Ee{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new J),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new J),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new J),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=new Array(e);for(let r=0;r<Math.min(e,this.length);r++)t[r]=this._array[this._getCyclicIndex(r)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new 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(e,t,...r){if(t){for(let o=e;o<this._length-t;o++)this._array[this._getCyclicIndex(o)]=this._array[this._getCyclicIndex(o+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let o=this._length-1;o>=e;o--)this._array[this._getCyclicIndex(o+r.length)]=this._array[this._getCyclicIndex(o)];for(let o=0;o<r.length;o++)this._array[this._getCyclicIndex(e+o)]=r[o];if(r.length&&this.onInsertEmitter.fire({index:e,amount:r.length}),this._length+r.length>this._maxLength){let o=this._length+r.length-this._maxLength;this._startIndex+=o,this._length=this._maxLength,this.onTrimEmitter.fire(o)}else this._length+=r.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,r){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+r<0)throw new Error("Cannot shift elements in list beyond index 0");if(r>0){for(let i=t-1;i>=0;i--)this.set(e+i+r,this.get(e+i));let o=e+t+r-this._length;if(o>0)for(this._length+=o;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let o=0;o<t;o++)this.set(e+o+r,this.get(e+o))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},Oe=3,gr=Object.freeze(new by),y0=0,nP=2,uy=class X6{constructor(t,r,o=!1){this.isWrapped=o,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(t*Oe);let i=r||Zi.fromCharData([0,s6,1,0]);for(let n=0;n<t;++n)this.setCell(n,i);this.length=t}get(t){let r=this._data[t*Oe+0],o=r&2097151;return[this._data[t*Oe+1],r&2097152?this._combined[t]:o?_l(o):"",r>>22,r&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):o]}set(t,r){this._data[t*Oe+1]=r[0],r[1].length>1?(this._combined[t]=r[1],this._data[t*Oe+0]=t|2097152|r[2]<<22):this._data[t*Oe+0]=r[1].charCodeAt(0)|r[2]<<22}getWidth(t){return this._data[t*Oe+0]>>22}hasWidth(t){return this._data[t*Oe+0]&12582912}getFg(t){return this._data[t*Oe+1]}getBg(t){return this._data[t*Oe+2]}hasContent(t){return this._data[t*Oe+0]&4194303}getCodePoint(t){let r=this._data[t*Oe+0];return r&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):r&2097151}isCombined(t){return this._data[t*Oe+0]&2097152}getString(t){let r=this._data[t*Oe+0];return r&2097152?this._combined[t]:r&2097151?_l(r&2097151):""}isProtected(t){return this._data[t*Oe+2]&536870912}loadCell(t,r){return y0=t*Oe,r.content=this._data[y0+0],r.fg=this._data[y0+1],r.bg=this._data[y0+2],r.content&2097152&&(r.combinedData=this._combined[t]),r.bg&268435456&&(r.extended=this._extendedAttrs[t]),r}setCell(t,r){r.content&2097152&&(this._combined[t]=r.combinedData),r.bg&268435456&&(this._extendedAttrs[t]=r.extended),this._data[t*Oe+0]=r.content,this._data[t*Oe+1]=r.fg,this._data[t*Oe+2]=r.bg}setCellFromCodepoint(t,r,o,i){i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*Oe+0]=r|o<<22,this._data[t*Oe+1]=i.fg,this._data[t*Oe+2]=i.bg}addCodepointToCell(t,r,o){let i=this._data[t*Oe+0];i&2097152?this._combined[t]+=_l(r):i&2097151?(this._combined[t]=_l(i&2097151)+_l(r),i&=-2097152,i|=2097152):i=r|1<<22,o&&(i&=-12582913,i|=o<<22),this._data[t*Oe+0]=i}insertCells(t,r,o){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,o),r<this.length-t){let i=new Zi;for(let n=this.length-t-r-1;n>=0;--n)this.setCell(t+r+n,this.loadCell(t+n,i));for(let n=0;n<r;++n)this.setCell(t+n,o)}else for(let i=t;i<this.length;++i)this.setCell(i,o);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,o)}deleteCells(t,r,o){if(t%=this.length,r<this.length-t){let i=new Zi;for(let n=0;n<this.length-t-r;++n)this.setCell(t+n,this.loadCell(t+r+n,i));for(let n=this.length-r;n<this.length;++n)this.setCell(n,o)}else for(let i=t;i<this.length;++i)this.setCell(i,o);t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,o),this.getWidth(t)===0&&!this.hasContent(t)&&this.setCellFromCodepoint(t,0,1,o)}replaceCells(t,r,o,i=!1){if(i){for(t&&this.getWidth(t-1)===2&&!this.isProtected(t-1)&&this.setCellFromCodepoint(t-1,0,1,o),r<this.length&&this.getWidth(r-1)===2&&!this.isProtected(r)&&this.setCellFromCodepoint(r,0,1,o);t<r&&t<this.length;)this.isProtected(t)||this.setCell(t,o),t++;return}for(t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,o),r<this.length&&this.getWidth(r-1)===2&&this.setCellFromCodepoint(r,0,1,o);t<r&&t<this.length;)this.setCell(t++,o)}resize(t,r){if(t===this.length)return this._data.length*4*nP<this._data.buffer.byteLength;let o=t*Oe;if(t>this.length){if(this._data.buffer.byteLength>=o*4)this._data=new Uint32Array(this._data.buffer,0,o);else{let i=new Uint32Array(o);i.set(this._data),this._data=i}for(let i=this.length;i<t;++i)this.setCell(i,r)}else{this._data=this._data.subarray(0,o);let i=Object.keys(this._combined);for(let s=0;s<i.length;s++){let a=parseInt(i[s],10);a>=t&&delete this._combined[a]}let n=Object.keys(this._extendedAttrs);for(let s=0;s<n.length;s++){let a=parseInt(n[s],10);a>=t&&delete this._extendedAttrs[a]}}return this.length=t,o*4*nP<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*nP<this._data.buffer.byteLength){let t=new Uint32Array(this._data.length);return t.set(this._data),this._data=t,1}return 0}fill(t,r=!1){if(r){for(let o=0;o<this.length;++o)this.isProtected(o)||this.setCell(o,t);return}this._combined={},this._extendedAttrs={};for(let o=0;o<this.length;++o)this.setCell(o,t)}copyFrom(t){this.length!==t.length?this._data=new Uint32Array(t._data):this._data.set(t._data),this.length=t.length,this._combined={};for(let r in t._combined)this._combined[r]=t._combined[r];this._extendedAttrs={};for(let r in t._extendedAttrs)this._extendedAttrs[r]=t._extendedAttrs[r];this.isWrapped=t.isWrapped}clone(){let t=new X6(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let r in this._combined)t._combined[r]=this._combined[r];for(let r in this._extendedAttrs)t._extendedAttrs[r]=this._extendedAttrs[r];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*Oe+0]&4194303)return t+(this._data[t*Oe+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*Oe+0]&4194303||this._data[t*Oe+2]&50331648)return t+(this._data[t*Oe+0]>>22);return 0}copyCellsFrom(t,r,o,i,n){let s=t._data;if(n)for(let l=i-1;l>=0;l--){for(let c=0;c<Oe;c++)this._data[(o+l)*Oe+c]=s[(r+l)*Oe+c];s[(r+l)*Oe+2]&268435456&&(this._extendedAttrs[o+l]=t._extendedAttrs[r+l])}else for(let l=0;l<i;l++){for(let c=0;c<Oe;c++)this._data[(o+l)*Oe+c]=s[(r+l)*Oe+c];s[(r+l)*Oe+2]&268435456&&(this._extendedAttrs[o+l]=t._extendedAttrs[r+l])}let a=Object.keys(t._combined);for(let l=0;l<a.length;l++){let c=parseInt(a[l],10);c>=r&&(this._combined[c-r+o]=t._combined[c])}}translateToString(t,r,o,i){r=r??0,o=o??this.length,t&&(o=Math.min(o,this.getTrimmedLength())),i&&(i.length=0);let n="";for(;r<o;){let s=this._data[r*Oe+0],a=s&2097151,l=s&2097152?this._combined[r]:a?_l(a):Sl;if(n+=l,i)for(let c=0;c<l.length;++c)i.push(r);r+=s>>22||1}return i&&i.push(r),n}};function ooe(e,t,r,o,i,n){let s=[];for(let a=0;a<e.length-1;a++){let l=a,c=e.get(++l);if(!c.isWrapped)continue;let u=[e.get(a)];for(;l<e.length&&c.isWrapped;)u.push(c),c=e.get(++l);if(!n&&o>=a&&o<l){a+=u.length-1;continue}let p=0,f=vy(u,p,t),d=1,h=0;for(;d<u.length;){let _=vy(u,d,t),m=_-h,g=r-f,v=Math.min(m,g);u[p].copyCellsFrom(u[d],h,f,v,!1),f+=v,f===r&&(p++,f=0),h+=v,h===_&&(d++,h=0),f===0&&p!==0&&u[p-1].getWidth(r-1)===2&&(u[p].copyCellsFrom(u[p-1],r-1,f++,1,!1),u[p-1].setCell(r-1,i))}u[p].replaceCells(f,r,i);let y=0;for(let _=u.length-1;_>0&&(_>p||u[_].getTrimmedLength()===0);_--)y++;y>0&&(s.push(a+u.length-y),s.push(y)),a+=u.length-1}return s}function ioe(e,t){let r=[],o=0,i=t[o],n=0;for(let s=0;s<e.length;s++)if(i===s){let a=t[++o];e.onDeleteEmitter.fire({index:s-n,amount:a}),s+=a-1,n+=a,i=t[++o]}else r.push(s);return{layout:r,countRemoved:n}}function noe(e,t){let r=[];for(let o=0;o<t.length;o++)r.push(e.get(t[o]));for(let o=0;o<r.length;o++)e.set(o,r[o]);e.length=t.length}function soe(e,t,r){let o=[],i=e.map((l,c)=>vy(e,c,t)).reduce((l,c)=>l+c),n=0,s=0,a=0;for(;a<i;){if(i-a<r){o.push(i-a);break}n+=r;let l=vy(e,s,t);n>l&&(n-=l,s++);let c=e[s].getWidth(n-1)===2;c&&n--;let u=c?r-1:r;o.push(u),a+=u}return o}function vy(e,t,r){if(t===e.length-1)return e[t].getTrimmedLength();let o=!e[t].hasContent(r-1)&&e[t].getWidth(r-1)===1,i=e[t+1].getWidth(0)===2;return o&&i?r-1:r}var Z6=class Q6{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Q6._nextId++,this._onDispose=this.register(new J),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),ou(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};Z6._nextId=1;var aoe=Z6,Er={},eu=Er.B;Er[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"};Er.A={"#":"\xA3"};Er.B=void 0;Er[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"};Er.C=Er[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};Er.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"};Er.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"};Er.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"};Er.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"};Er.E=Er[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"};Er.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"};Er.H=Er[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};Er["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"};var Iz=4294967295,zz=class{constructor(e,t,r){this._hasScrollback=e,this._optionsService=t,this._bufferService=r,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=gr.clone(),this.savedCharset=eu,this.markers=[],this._nullCell=Zi.fromCharData([0,s6,1,0]),this._whitespaceCell=Zi.fromCharData([0,Sl,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new B0,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Lz(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new R0),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new R0),this._whitespaceCell}getBlankLine(e,t){return new uy(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>Iz?Iz:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=gr);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Lz(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let r=this.getNullCell(gr),o=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let s=0;s<this.lines.length;s++)o+=+this.lines.get(s).resize(e,r);let n=0;if(this._rows<t)for(let s=this._rows;s<t;s++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new uy(e,r)):this.ybase>0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new uy(e,r)));else for(let s=this._rows;s>t;s--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let s=this.lines.length-i;s>0&&(this.lines.trimStart(s),this.ybase=Math.max(this.ybase-s,0),this.ydisp=Math.max(this.ydisp-s,0),this.savedY=Math.max(this.savedY-s,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let n=0;n<this.lines.length;n++)o+=+this.lines.get(n).resize(e,r);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),o>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let r=this._optionsService.rawOptions.reflowCursorLine,o=ooe(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(gr),r);if(o.length>0){let i=ioe(this.lines,o);noe(this.lines,i.layout),this._reflowLargerAdjustViewport(e,t,i.countRemoved)}}_reflowLargerAdjustViewport(e,t,r){let o=this.getNullCell(gr),i=r;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new uy(e,o))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-r,0)}_reflowSmaller(e,t){let r=this._optionsService.rawOptions.reflowCursorLine,o=this.getNullCell(gr),i=[],n=0;for(let s=this.lines.length-1;s>=0;s--){let a=this.lines.get(s);if(!a||!a.isWrapped&&a.getTrimmedLength()<=e)continue;let l=[a];for(;a.isWrapped&&s>0;)a=this.lines.get(--s),l.unshift(a);if(!r){let v=this.ybase+this.y;if(v>=s&&v<s+l.length)continue}let c=l[l.length-1].getTrimmedLength(),u=soe(l,this._cols,e),p=u.length-l.length,f;this.ybase===0&&this.y!==this.lines.length-1?f=Math.max(0,this.y-this.lines.maxLength+p):f=Math.max(0,this.lines.length-this.lines.maxLength+p);let d=[];for(let v=0;v<p;v++){let S=this.getBlankLine(gr,!0);d.push(S)}d.length>0&&(i.push({start:s+l.length+n,newLines:d}),n+=d.length),l.push(...d);let h=u.length-1,y=u[h];y===0&&(h--,y=u[h]);let _=l.length-p-1,m=c;for(;_>=0;){let v=Math.min(m,y);if(l[h]===void 0)break;if(l[h].copyCellsFrom(l[_],m-v,y-v,v,!0),y-=v,y===0&&(h--,y=u[h]),m-=v,m===0){_--;let S=Math.max(_,0);m=vy(l,S,this._cols)}}for(let v=0;v<l.length;v++)u[v]<e&&l[v].setCell(u[v],o);let g=p-f;for(;g-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+n)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+p,this.ybase+t-1)}if(i.length>0){let s=[],a=[];for(let y=0;y<this.lines.length;y++)a.push(this.lines.get(y));let l=this.lines.length,c=l-1,u=0,p=i[u];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+n);let f=0;for(let y=Math.min(this.lines.maxLength-1,l+n-1);y>=0;y--)if(p&&p.start>c+f){for(let _=p.newLines.length-1;_>=0;_--)this.lines.set(y--,p.newLines[_]);y++,s.push({index:c+1,amount:p.newLines.length}),f+=p.newLines.length,p=i[++u]}else this.lines.set(y,a[c--]);let d=0;for(let y=s.length-1;y>=0;y--)s[y].index+=d,this.lines.onInsertEmitter.fire(s[y]),d+=s[y].amount;let h=Math.max(0,l+n-this.lines.maxLength);h>0&&this.lines.onTrimEmitter.fire(h)}}translateBufferLineToString(e,t,r=0,o){let i=this.lines.get(e);return i?i.translateToString(t,r,o):""}getWrappedRangeForLine(e){let t=e,r=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;r+1<this.lines.length&&this.lines.get(r+1).isWrapped;)r++;return{first:t,last:r}}setupTabStops(e){for(e!=null?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e==null&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new aoe(e);return this.markers.push(t),t.register(this.lines.onTrim(r=>{t.line-=r,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(r=>{t.line>=r.index&&(t.line+=r.amount)})),t.register(this.lines.onDelete(r=>{t.line>=r.index&&t.line<r.index+r.amount&&t.dispose(),t.line>r.index&&(t.line-=r.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},loe=class extends Ee{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new J),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 zz(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new zz(!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(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),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(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},J6=2,eF=1,$P=class extends Ee{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new J),this.onResize=this._onResize.event,this._onScroll=this._register(new J),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,J6),this.rows=Math.max(e.rawOptions.rows||0,eF),this.buffers=this._register(new loe(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let r=this.cols!==e,o=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:r,rowsChanged:o})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let r=this.buffer,o;o=this._cachedBlankLine,(!o||o.length!==this.cols||o.getFg(0)!==e.fg||o.getBg(0)!==e.bg)&&(o=r.getBlankLine(e,t),this._cachedBlankLine=o),o.isWrapped=t;let i=r.ybase+r.scrollTop,n=r.ybase+r.scrollBottom;if(r.scrollTop===0){let s=r.lines.isFull;n===r.lines.length-1?s?r.lines.recycle().copyFrom(o):r.lines.push(o.clone()):r.lines.splice(n+1,0,o.clone()),s?this.isUserScrolling&&(r.ydisp=Math.max(r.ydisp-1,0)):(r.ybase++,this.isUserScrolling||r.ydisp++)}else{let s=n-i+1;r.lines.shiftElements(i+1,s-1,-1),r.lines.set(n,o.clone())}this.isUserScrolling||(r.ydisp=r.ybase),this._onScroll.fire(r.ydisp)}scrollLines(e,t){let r=this.buffer;if(e<0){if(r.ydisp===0)return;this.isUserScrolling=!0}else e+r.ydisp>=r.ybase&&(this.isUserScrolling=!1);let o=r.ydisp;r.ydisp=Math.max(Math.min(r.ydisp+e,r.ybase),0),o!==r.ydisp&&(t||this._onScroll.fire(r.ydisp))}};$P=er([ne(0,Oo)],$P);var Qd={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:1e3,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:A0,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},coe=["normal","bold","100","200","300","400","500","600","700","800","900"],uoe=class extends Ee{constructor(e){super(),this._onOptionChange=this._register(new J),this.onOptionChange=this._onOptionChange.event;let t={...Qd};for(let r in e)if(r in t)try{let o=e[r];t[r]=this._sanitizeAndValidateOption(r,o)}catch(o){console.error(o)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(At(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(r=>{r===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(r=>{e.indexOf(r)!==-1&&t()})}_setupOptions(){let e=r=>{if(!(r in Qd))throw new Error(`No option with key "${r}"`);return this.rawOptions[r]},t=(r,o)=>{if(!(r in Qd))throw new Error(`No option with key "${r}"`);o=this._sanitizeAndValidateOption(r,o),this.rawOptions[r]!==o&&(this.rawOptions[r]=o,this._onOptionChange.fire(r))};for(let r in this.rawOptions){let o={get:e.bind(this,r),set:t.bind(this,r)};Object.defineProperty(this.options,r,o)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Qd[e]),!poe(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Qd[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=coe.includes(t)?t:Qd[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function poe(e){return e==="block"||e==="underline"||e==="bar"}function py(e,t=5){if(typeof e!="object")return e;let r=Array.isArray(e)?[]:{};for(let o in e)r[o]=t<=1?e[o]:e[o]&&py(e[o],t-1);return r}var Fz=Object.freeze({insertMode:!1}),Hz=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),jP=class extends Ee{constructor(e,t,r){super(),this._bufferService=e,this._logService=t,this._optionsService=r,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new J),this.onData=this._onData.event,this._onUserInput=this._register(new J),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new J),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new J),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=py(Fz),this.decPrivateModes=py(Hz)}reset(){this.modes=py(Fz),this.decPrivateModes=py(Hz)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let r=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&r.ybase!==r.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(o=>o.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};jP=er([ne(0,ko),ne(1,p6),ne(2,Oo)],jP);var Uz={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function sP(e,t){let r=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(r|=64,r|=e.action):(r|=e.button&3,e.button&4&&(r|=64),e.button&8&&(r|=128),e.action===32?r|=32:e.action===0&&!t&&(r|=3)),r}var aP=String.fromCharCode,$z={DEFAULT:e=>{let t=[sP(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${aP(t[0])}${aP(t[1])}${aP(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${sP(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${sP(e,!0)};${e.x};${e.y}${t}`}},WP=class extends Ee{constructor(e,t,r){super(),this._bufferService=e,this._coreService=t,this._optionsService=r,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new J),this.onProtocolChange=this._onProtocolChange.event;for(let o of Object.keys(Uz))this.addProtocol(o,Uz[o]);for(let o of Object.keys($z))this.addEncoding(o,$z[o]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,r){if(e.deltaY===0||e.shiftKey||t===void 0||r===void 0)return 0;let o=t/r,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=o+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,r){if(r){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};WP=er([ne(0,ko),ne(1,nu),ne(2,Oo)],WP);var lP=[[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]],doe=[[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]],Rr;function foe(e,t){let r=0,o=t.length-1,i;if(e<t[0][0]||e>t[o][1])return!1;for(;o>=r;)if(i=r+o>>1,e>t[i][1])r=i+1;else if(e<t[i][0])o=i-1;else return!0;return!1}var hoe=class{constructor(){if(this.version="6",!Rr){Rr=new Uint8Array(65536),Rr.fill(1),Rr[0]=0,Rr.fill(0,1,32),Rr.fill(0,127,160),Rr.fill(2,4352,4448),Rr[9001]=2,Rr[9002]=2,Rr.fill(2,11904,42192),Rr[12351]=1,Rr.fill(2,44032,55204),Rr.fill(2,63744,64256),Rr.fill(2,65040,65050),Rr.fill(2,65072,65136),Rr.fill(2,65280,65377),Rr.fill(2,65504,65511);for(let e=0;e<lP.length;++e)Rr.fill(0,lP[e][0],lP[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?Rr[e]:foe(e,doe)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let r=this.wcwidth(e),o=r===0&&t!==0;if(o){let i=tu.extractWidth(t);i===0?o=!1:i>r&&(r=i)}return tu.createPropertyValue(0,r,o)}},tu=class P0{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new J,this.onChange=this._onChange.event;let t=new hoe;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,r,o=!1){return(t&16777215)<<3|(r&3)<<1|(o?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let r=0,o=0,i=t.length;for(let n=0;n<i;++n){let s=t.charCodeAt(n);if(55296<=s&&s<=56319){if(++n>=i)return r+this.wcwidth(s);let c=t.charCodeAt(n);56320<=c&&c<=57343?s=(s-55296)*1024+c-56320+65536:r+=this.wcwidth(c)}let a=this.charProperties(s,o),l=P0.extractWidth(a);P0.extractShouldJoin(a)&&(l-=P0.extractWidth(o)),r+=l,o=a}return r}charProperties(t,r){return this._activeProvider.charProperties(t,r)}},moe=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function jz(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),r=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);r&&t&&(r.isWrapped=t[3]!==0&&t[3]!==32)}var iy=2147483647,yoe=256,tF=class VP{constructor(t=32,r=32){if(this.maxLength=t,this.maxSubParamsLength=r,r>yoe)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(r),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let r=new VP;if(!t.length)return r;for(let o=Array.isArray(t[0])?1:0;o<t.length;++o){let i=t[o];if(Array.isArray(i))for(let n=0;n<i.length;++n)r.addSubParam(i[n]);else r.addParam(i)}return r}clone(){let t=new VP(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let t=[];for(let r=0;r<this.length;++r){t.push(this.params[r]);let o=this._subParamsIdx[r]>>8,i=this._subParamsIdx[r]&255;i-o>0&&t.push(Array.prototype.slice.call(this._subParams,o,i))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>iy?iy:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>iy?iy:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let r=this._subParamsIdx[t]>>8,o=this._subParamsIdx[t]&255;return o-r>0?this._subParams.subarray(r,o):null}getSubParamsAll(){let t={};for(let r=0;r<this.length;++r){let o=this._subParamsIdx[r]>>8,i=this._subParamsIdx[r]&255;i-o>0&&(t[r]=this._subParams.slice(o,i))}return t}addDigit(t){let r;if(this._rejectDigits||!(r=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let o=this._digitIsSub?this._subParams:this.params,i=o[r-1];o[r-1]=~i?Math.min(i*10+t,iy):t}},ny=[],goe=class{constructor(){this._state=0,this._active=ny,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let r=this._handlers[e];return r.push(t),{dispose:()=>{let o=r.indexOf(t);o!==-1&&r.splice(o,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=ny}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=ny,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||ny,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,r){if(!this._active.length)this._handlerFb(this._id,"PUT",L0(e,t,r));else for(let o=this._active.length-1;o>=0;o--)this._active[o].put(e,t,r)}start(){this.reset(),this._state=1}put(e,t,r){if(this._state!==3){if(this._state===1)for(;t<r;){let o=e[t++];if(o===59){this._state=2,this._start();break}if(o<48||57<o){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+o-48}this._state===2&&r-t>0&&this._put(e,t,r)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let r=!1,o=this._active.length-1,i=!1;if(this._stack.paused&&(o=this._stack.loopPosition-1,r=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&r===!1){for(;o>=0&&(r=this._active[o].end(e),r!==!0);o--)if(r instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=o,this._stack.fallThrough=!1,r;o--}for(;o>=0;o--)if(r=this._active[o].end(!1),r instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=o,this._stack.fallThrough=!0,r}this._active=ny,this._id=-1,this._state=0}}},bi=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,r){this._hitLimit||(this._data+=L0(e,t,r),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(r=>(this._data="",this._hitLimit=!1,r));return this._data="",this._hitLimit=!1,t}},sy=[],voe=class{constructor(){this._handlers=Object.create(null),this._active=sy,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=sy}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let r=this._handlers[e];return r.push(t),{dispose:()=>{let o=r.indexOf(t);o!==-1&&r.splice(o,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=sy,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||sy,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let r=this._active.length-1;r>=0;r--)this._active[r].hook(t)}put(e,t,r){if(!this._active.length)this._handlerFb(this._ident,"PUT",L0(e,t,r));else for(let o=this._active.length-1;o>=0;o--)this._active[o].put(e,t,r)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let r=!1,o=this._active.length-1,i=!1;if(this._stack.paused&&(o=this._stack.loopPosition-1,r=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&r===!1){for(;o>=0&&(r=this._active[o].unhook(e),r!==!0);o--)if(r instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=o,this._stack.fallThrough=!1,r;o--}for(;o>=0;o--)if(r=this._active[o].unhook(!1),r instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=o,this._stack.fallThrough=!0,r}this._active=sy,this._ident=0}},dy=new tF;dy.addParam(0);var Wz=class{constructor(e){this._handler=e,this._data="",this._params=dy,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():dy,this._data="",this._hitLimit=!1}put(e,t,r){this._hitLimit||(this._data+=L0(e,t,r),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(r=>(this._params=dy,this._data="",this._hitLimit=!1,r));return this._params=dy,this._data="",this._hitLimit=!1,t}},boe=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,r,o){this.table[t<<8|e]=r<<4|o}addMany(e,t,r,o){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=r<<4|o}},Xi=160,_oe=(function(){let e=new boe(4095),t=Array.apply(null,Array(256)).map((a,l)=>l),r=(a,l)=>t.slice(a,l),o=r(32,127),i=r(0,24);i.push(25),i.push.apply(i,r(28,32));let n=r(0,14),s;e.setDefault(1,0),e.addMany(o,0,2,0);for(s in n)e.addMany([24,26,153,154],s,3,0),e.addMany(r(128,144),s,3,0),e.addMany(r(144,152),s,3,0),e.add(156,s,0,0),e.add(27,s,11,1),e.add(157,s,4,8),e.addMany([152,158,159],s,0,7),e.add(155,s,11,3),e.add(144,s,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(o,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(r(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(o,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(r(64,127),3,7,0),e.addMany(r(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(r(48,60),4,8,4),e.addMany(r(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(r(32,64),6,0,6),e.add(127,6,0,6),e.addMany(r(64,127),6,0,0),e.addMany(r(32,48),3,9,5),e.addMany(r(32,48),5,9,5),e.addMany(r(48,64),5,0,6),e.addMany(r(64,127),5,7,0),e.addMany(r(32,48),4,9,5),e.addMany(r(32,48),1,9,2),e.addMany(r(32,48),2,9,2),e.addMany(r(48,127),2,10,0),e.addMany(r(48,80),1,10,0),e.addMany(r(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(r(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(r(28,32),9,0,9),e.addMany(r(32,48),9,9,12),e.addMany(r(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(r(32,128),11,0,11),e.addMany(r(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(r(28,32),10,0,10),e.addMany(r(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(r(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(r(28,32),12,0,12),e.addMany(r(32,48),12,9,12),e.addMany(r(48,64),12,0,11),e.addMany(r(64,127),12,12,13),e.addMany(r(64,127),10,12,13),e.addMany(r(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(o,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Xi,0,2,0),e.add(Xi,8,5,8),e.add(Xi,6,0,6),e.add(Xi,11,0,11),e.add(Xi,13,13,13),e})(),Soe=class extends Ee{constructor(e=_oe){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new tF,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,r,o)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,r)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(At(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new goe),this._dcsParser=this._register(new voe),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let r=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(r=e.prefix.charCodeAt(0),r&&60>r||r>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let i=0;i<e.intermediates.length;++i){let n=e.intermediates.charCodeAt(i);if(32>n||n>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");r<<=8,r|=n}}if(e.final.length!==1)throw new Error("final must be a single byte");let o=e.final.charCodeAt(0);if(t[0]>o||o>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return r<<=8,r|=o,r}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let r=this._identifier(e,[48,126]);this._escHandlers[r]===void 0&&(this._escHandlers[r]=[]);let o=this._escHandlers[r];return o.push(t),{dispose:()=>{let i=o.indexOf(t);i!==-1&&o.splice(i,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let r=this._identifier(e);this._csiHandlers[r]===void 0&&(this._csiHandlers[r]=[]);let o=this._csiHandlers[r];return o.push(t),{dispose:()=>{let i=o.indexOf(t);i!==-1&&o.splice(i,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}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(e,t,r,o,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=r,this._parseStack.transition=o,this._parseStack.chunkPos=i}parse(e,t,r){let o=0,i=0,n=0,s;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,n=this._parseStack.chunkPos+1;else{if(r===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let a=this._parseStack.handlers,l=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(r===!1&&l>-1){for(;l>=0&&(s=a[l](this._params),s!==!0);l--)if(s instanceof Promise)return this._parseStack.handlerPos=l,s}this._parseStack.handlers=[];break;case 4:if(r===!1&&l>-1){for(;l>=0&&(s=a[l](),s!==!0);l--)if(s instanceof Promise)return this._parseStack.handlerPos=l,s}this._parseStack.handlers=[];break;case 6:if(o=e[this._parseStack.chunkPos],s=this._dcsParser.unhook(o!==24&&o!==26,r),s)return s;o===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(o=e[this._parseStack.chunkPos],s=this._oscParser.end(o!==24&&o!==26,r),s)return s;o===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,n=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let a=n;a<t;++a){switch(o=e[a],i=this._transitions.table[this.currentState<<8|(o<160?o:Xi)],i>>4){case 2:for(let f=a+1;;++f){if(f>=t||(o=e[f])<32||o>126&&o<Xi){this._printHandler(e,a,f),a=f-1;break}if(++f>=t||(o=e[f])<32||o>126&&o<Xi){this._printHandler(e,a,f),a=f-1;break}if(++f>=t||(o=e[f])<32||o>126&&o<Xi){this._printHandler(e,a,f),a=f-1;break}if(++f>=t||(o=e[f])<32||o>126&&o<Xi){this._printHandler(e,a,f),a=f-1;break}}break;case 3:this._executeHandlers[o]?this._executeHandlers[o]():this._executeHandlerFb(o),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:a,code:o,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let l=this._csiHandlers[this._collect<<8|o],c=l?l.length-1:-1;for(;c>=0&&(s=l[c](this._params),s!==!0);c--)if(s instanceof Promise)return this._preserveStack(3,l,c,i,a),s;c<0&&this._csiHandlerFb(this._collect<<8|o,this._params),this.precedingJoinState=0;break;case 8:do switch(o){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(o-48)}while(++a<t&&(o=e[a])>47&&o<60);a--;break;case 9:this._collect<<=8,this._collect|=o;break;case 10:let u=this._escHandlers[this._collect<<8|o],p=u?u.length-1:-1;for(;p>=0&&(s=u[p](),s!==!0);p--)if(s instanceof Promise)return this._preserveStack(4,u,p,i,a),s;p<0&&this._escHandlerFb(this._collect<<8|o),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|o,this._params);break;case 13:for(let f=a+1;;++f)if(f>=t||(o=e[f])===24||o===26||o===27||o>127&&o<Xi){this._dcsParser.put(e,a,f),a=f-1;break}break;case 14:if(s=this._dcsParser.unhook(o!==24&&o!==26),s)return this._preserveStack(6,[],0,i,a),s;o===27&&(i|=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 f=a+1;;f++)if(f>=t||(o=e[f])<32||o>127&&o<Xi){this._oscParser.put(e,a,f),a=f-1;break}break;case 6:if(s=this._oscParser.end(o!==24&&o!==26),s)return this._preserveStack(5,[],0,i,a),s;o===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=i&15}}},xoe=/^([\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})$/,Toe=/^[\da-f]+$/;function Vz(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf("rgb:")===0){t=t.slice(4);let r=xoe.exec(t);if(r){let o=r[1]?15:r[4]?255:r[7]?4095:65535;return[Math.round(parseInt(r[1]||r[4]||r[7]||r[10],16)/o*255),Math.round(parseInt(r[2]||r[5]||r[8]||r[11],16)/o*255),Math.round(parseInt(r[3]||r[6]||r[9]||r[12],16)/o*255)]}}else if(t.indexOf("#")===0&&(t=t.slice(1),Toe.exec(t)&&[3,6,9,12].includes(t.length))){let r=t.length/3,o=[0,0,0];for(let i=0;i<3;++i){let n=parseInt(t.slice(r*i,r*i+r),16);o[i]=r===1?n<<4:r===2?n:r===3?n>>4:n>>8}return o}}function cP(e,t){let r=e.toString(16),o=r.length<2?"0"+r:r;switch(t){case 4:return r[0];case 8:return o;case 12:return(o+o).slice(0,3);default:return o+o}}function woe(e,t=16){let[r,o,i]=e;return`rgb:${cP(r,t)}/${cP(o,t)}/${cP(i,t)}`}var Coe={"(":0,")":1,"*":2,"+":3,"-":1,".":2},bl=131072,qz=10;function Kz(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Gz=5e3,Yz=0,Poe=class extends Ee{constructor(e,t,r,o,i,n,s,a,l=new Soe){super(),this._bufferService=e,this._charsetService=t,this._coreService=r,this._logService=o,this._optionsService=i,this._oscLinkService=n,this._coreMouseService=s,this._unicodeService=a,this._parser=l,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new gee,this._utf8Decoder=new vee,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=gr.clone(),this._eraseAttrDataInternal=gr.clone(),this._onRequestBell=this._register(new J),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new J),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new J),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new J),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new J),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new J),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new J),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new J),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new J),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new J),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new J),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new J),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new J),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 qP(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(c=>this._activeBuffer=c.activeBuffer)),this._parser.setCsiHandlerFallback((c,u)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(c),params:u.toArray()})}),this._parser.setEscHandlerFallback(c=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(c)})}),this._parser.setExecuteHandlerFallback(c=>{this._logService.debug("Unknown EXECUTE code: ",{code:c})}),this._parser.setOscHandlerFallback((c,u,p)=>{this._logService.debug("Unknown OSC code: ",{identifier:c,action:u,data:p})}),this._parser.setDcsHandlerFallback((c,u,p)=>{u==="HOOK"&&(p=p.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(c),action:u,payload:p})}),this._parser.setPrintHandler((c,u,p)=>this.print(c,u,p)),this._parser.registerCsiHandler({final:"@"},c=>this.insertChars(c)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},c=>this.scrollLeft(c)),this._parser.registerCsiHandler({final:"A"},c=>this.cursorUp(c)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},c=>this.scrollRight(c)),this._parser.registerCsiHandler({final:"B"},c=>this.cursorDown(c)),this._parser.registerCsiHandler({final:"C"},c=>this.cursorForward(c)),this._parser.registerCsiHandler({final:"D"},c=>this.cursorBackward(c)),this._parser.registerCsiHandler({final:"E"},c=>this.cursorNextLine(c)),this._parser.registerCsiHandler({final:"F"},c=>this.cursorPrecedingLine(c)),this._parser.registerCsiHandler({final:"G"},c=>this.cursorCharAbsolute(c)),this._parser.registerCsiHandler({final:"H"},c=>this.cursorPosition(c)),this._parser.registerCsiHandler({final:"I"},c=>this.cursorForwardTab(c)),this._parser.registerCsiHandler({final:"J"},c=>this.eraseInDisplay(c,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},c=>this.eraseInDisplay(c,!0)),this._parser.registerCsiHandler({final:"K"},c=>this.eraseInLine(c,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},c=>this.eraseInLine(c,!0)),this._parser.registerCsiHandler({final:"L"},c=>this.insertLines(c)),this._parser.registerCsiHandler({final:"M"},c=>this.deleteLines(c)),this._parser.registerCsiHandler({final:"P"},c=>this.deleteChars(c)),this._parser.registerCsiHandler({final:"S"},c=>this.scrollUp(c)),this._parser.registerCsiHandler({final:"T"},c=>this.scrollDown(c)),this._parser.registerCsiHandler({final:"X"},c=>this.eraseChars(c)),this._parser.registerCsiHandler({final:"Z"},c=>this.cursorBackwardTab(c)),this._parser.registerCsiHandler({final:"`"},c=>this.charPosAbsolute(c)),this._parser.registerCsiHandler({final:"a"},c=>this.hPositionRelative(c)),this._parser.registerCsiHandler({final:"b"},c=>this.repeatPrecedingCharacter(c)),this._parser.registerCsiHandler({final:"c"},c=>this.sendDeviceAttributesPrimary(c)),this._parser.registerCsiHandler({prefix:">",final:"c"},c=>this.sendDeviceAttributesSecondary(c)),this._parser.registerCsiHandler({final:"d"},c=>this.linePosAbsolute(c)),this._parser.registerCsiHandler({final:"e"},c=>this.vPositionRelative(c)),this._parser.registerCsiHandler({final:"f"},c=>this.hVPosition(c)),this._parser.registerCsiHandler({final:"g"},c=>this.tabClear(c)),this._parser.registerCsiHandler({final:"h"},c=>this.setMode(c)),this._parser.registerCsiHandler({prefix:"?",final:"h"},c=>this.setModePrivate(c)),this._parser.registerCsiHandler({final:"l"},c=>this.resetMode(c)),this._parser.registerCsiHandler({prefix:"?",final:"l"},c=>this.resetModePrivate(c)),this._parser.registerCsiHandler({final:"m"},c=>this.charAttributes(c)),this._parser.registerCsiHandler({final:"n"},c=>this.deviceStatus(c)),this._parser.registerCsiHandler({prefix:"?",final:"n"},c=>this.deviceStatusPrivate(c)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},c=>this.softReset(c)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},c=>this.setCursorStyle(c)),this._parser.registerCsiHandler({final:"r"},c=>this.setScrollRegion(c)),this._parser.registerCsiHandler({final:"s"},c=>this.saveCursor(c)),this._parser.registerCsiHandler({final:"t"},c=>this.windowOptions(c)),this._parser.registerCsiHandler({final:"u"},c=>this.restoreCursor(c)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},c=>this.insertColumns(c)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},c=>this.deleteColumns(c)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},c=>this.selectProtected(c)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},c=>this.requestMode(c,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},c=>this.requestMode(c,!1)),this._parser.setExecuteHandler(V.BEL,()=>this.bell()),this._parser.setExecuteHandler(V.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(V.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(V.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(V.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(V.BS,()=>this.backspace()),this._parser.setExecuteHandler(V.HT,()=>this.tab()),this._parser.setExecuteHandler(V.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(V.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(w0.IND,()=>this.index()),this._parser.setExecuteHandler(w0.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(w0.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new bi(c=>(this.setTitle(c),this.setIconName(c),!0))),this._parser.registerOscHandler(1,new bi(c=>this.setIconName(c))),this._parser.registerOscHandler(2,new bi(c=>this.setTitle(c))),this._parser.registerOscHandler(4,new bi(c=>this.setOrReportIndexedColor(c))),this._parser.registerOscHandler(8,new bi(c=>this.setHyperlink(c))),this._parser.registerOscHandler(10,new bi(c=>this.setOrReportFgColor(c))),this._parser.registerOscHandler(11,new bi(c=>this.setOrReportBgColor(c))),this._parser.registerOscHandler(12,new bi(c=>this.setOrReportCursorColor(c))),this._parser.registerOscHandler(104,new bi(c=>this.restoreIndexedColor(c))),this._parser.registerOscHandler(110,new bi(c=>this.restoreFgColor(c))),this._parser.registerOscHandler(111,new bi(c=>this.restoreBgColor(c))),this._parser.registerOscHandler(112,new bi(c=>this.restoreCursorColor(c))),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 c in Er)this._parser.registerEscHandler({intermediates:"(",final:c},()=>this.selectCharset("("+c)),this._parser.registerEscHandler({intermediates:")",final:c},()=>this.selectCharset(")"+c)),this._parser.registerEscHandler({intermediates:"*",final:c},()=>this.selectCharset("*"+c)),this._parser.registerEscHandler({intermediates:"+",final:c},()=>this.selectCharset("+"+c)),this._parser.registerEscHandler({intermediates:"-",final:c},()=>this.selectCharset("-"+c)),this._parser.registerEscHandler({intermediates:".",final:c},()=>this.selectCharset("."+c)),this._parser.registerEscHandler({intermediates:"/",final:c},()=>this.selectCharset("/"+c));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(c=>(this._logService.error("Parsing error: ",c),c)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Wz((c,u)=>this.requestStatusString(c,u)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,r,o){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=r,this._parseStack.position=o}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,r)=>setTimeout(()=>r("#SLOW_TIMEOUT"),Gz))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Gz} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let r,o=this._activeBuffer.x,i=this._activeBuffer.y,n=0,s=this._parseStack.paused;if(s){if(r=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(r),r;o=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>bl&&(n=this._parseStack.position+bl)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,c=>String.fromCharCode(c)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(c=>c.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<bl&&(this._parseBuffer=new Uint32Array(Math.min(e.length,bl))),s||this._dirtyRowTracker.clearRange(),e.length>bl)for(let c=n;c<e.length;c+=bl){let u=c+bl<e.length?c+bl:e.length,p=typeof e=="string"?this._stringDecoder.decode(e.substring(c,u),this._parseBuffer):this._utf8Decoder.decode(e.subarray(c,u),this._parseBuffer);if(r=this._parser.parse(this._parseBuffer,p))return this._preserveStack(o,i,p,c),this._logSlowResolvingAsync(r),r}else if(!s){let c=typeof e=="string"?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(r=this._parser.parse(this._parseBuffer,c))return this._preserveStack(o,i,c,0),this._logSlowResolvingAsync(r),r}(this._activeBuffer.x!==o||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let a=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),l=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);l<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(l,this._bufferService.rows-1),end:Math.min(a,this._bufferService.rows-1)})}print(e,t,r){let o,i,n=this._charsetService.charset,s=this._optionsService.rawOptions.screenReaderMode,a=this._bufferService.cols,l=this._coreService.decPrivateModes.wraparound,c=this._coreService.modes.insertMode,u=this._curAttrData,p=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&r-t>0&&p.getWidth(this._activeBuffer.x-1)===2&&p.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let d=t;d<r;++d){if(o=e[d],o<127&&n){let m=n[String.fromCharCode(o)];m&&(o=m.charCodeAt(0))}let h=this._unicodeService.charProperties(o,f);i=tu.extractWidth(h);let y=tu.extractShouldJoin(h),_=y?tu.extractWidth(f):0;if(f=h,s&&this._onA11yChar.fire(_l(o)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-_>a){if(l){let m=p,g=this._activeBuffer.x-_;for(this._activeBuffer.x=_,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),p=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),_>0&&p instanceof uy&&p.copyCellsFrom(m,g,0,_,!1);g<a;)m.setCellFromCodepoint(g++,0,1,u)}else if(this._activeBuffer.x=a-1,i===2)continue}if(y&&this._activeBuffer.x){let m=p.getWidth(this._activeBuffer.x-1)?1:2;p.addCodepointToCell(this._activeBuffer.x-m,o,i);for(let g=i-_;--g>=0;)p.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(c&&(p.insertCells(this._activeBuffer.x,i-_,this._activeBuffer.getNullCell(u)),p.getWidth(a-1)===2&&p.setCellFromCodepoint(a-1,0,1,u)),p.setCellFromCodepoint(this._activeBuffer.x++,o,i,u),i>0)for(;--i;)p.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<a&&r-t>0&&p.getWidth(this._activeBuffer.x)===0&&!p.hasContent(this._activeBuffer.x)&&p.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,r=>Kz(r.params[0],this._optionsService.rawOptions.windowOptions)?t(r):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Wz(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new bi(t))}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 e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,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(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,r,o=!1,i=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,r,this._activeBuffer.getNullCell(this._eraseAttrData()),i),o&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);r&&(r.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),r.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let r;switch(e.params[0]){case 0:for(r=this._activeBuffer.y,this._dirtyRowTracker.markDirty(r),this._eraseInBufferLine(r++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);r<this._bufferService.rows;r++)this._resetBufferLine(r,t);this._dirtyRowTracker.markDirty(r);break;case 1:for(r=this._activeBuffer.y,this._dirtyRowTracker.markDirty(r),this._eraseInBufferLine(r,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(r+1).isWrapped=!1);r--;)this._resetBufferLine(r,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(r=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,r-1);r--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+r)?.getTrimmedLength(););for(;r>=0;r--)this._bufferService.scroll(this._eraseAttrData())}else{for(r=this._bufferService.rows,this._dirtyRowTracker.markDirty(r-1);r--;)this._resetBufferLine(r,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let o=this._activeBuffer.lines.length-this._bufferService.rows;o>0&&(this._activeBuffer.lines.trimStart(o),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-o,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-o,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let r=this._activeBuffer.ybase+this._activeBuffer.y,o=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-o+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let r=this._activeBuffer.ybase+this._activeBuffer.y,o;for(o=this._bufferService.rows-1-this._activeBuffer.scrollBottom,o=this._bufferService.rows-1+this._activeBuffer.ybase-o;t--;)this._activeBuffer.lines.splice(r,1),this._activeBuffer.lines.splice(o,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)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(e){let t=e.params[0]||1;for(;t--;)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(gr));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let r=this._activeBuffer.scrollTop;r<=this._activeBuffer.scrollBottom;++r){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);o.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),o.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let r=this._activeBuffer.scrollTop;r<=this._activeBuffer.scrollBottom;++r){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);o.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),o.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let r=this._activeBuffer.scrollTop;r<=this._activeBuffer.scrollBottom;++r){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);o.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),o.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let r=this._activeBuffer.scrollTop;r<=this._activeBuffer.scrollBottom;++r){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);o.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),o.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let r=e.params[0]||1,o=tu.extractWidth(t),i=this._activeBuffer.x-o,n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),s=new Uint32Array(n.length*r),a=0;for(let c=0;c<n.length;){let u=n.codePointAt(c)||0;s[a++]=u,c+=u>65535?2:1}let l=a;for(let c=1;c<r;++c)s.copyWithin(l,0,a),l+=a;return this.print(s,0,l),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(V.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(V.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(V.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(V.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(V.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0;break}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,eu),this._charsetService.setgCharset(1,eu),this._charsetService.setgCharset(2,eu),this._charsetService.setgCharset(3,eu);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 1e3: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;break}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1;break}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){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 1e3: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:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===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);break}return!0}requestMode(e,t){(y=>(y[y.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",y[y.SET=1]="SET",y[y.RESET=2]="RESET",y[y.PERMANENTLY_SET=3]="PERMANENTLY_SET",y[y.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(r={}));let o=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:n}=this._coreMouseService,s=this._coreService,{buffers:a,cols:l}=this._bufferService,{active:c,alt:u}=a,p=this._optionsService.rawOptions,f=(y,_)=>(s.triggerDataEvent(`${V.ESC}[${t?"":"?"}${y};${_}$y`),!0),d=y=>y?1:2,h=e.params[0];return t?h===2?f(h,4):h===4?f(h,d(s.modes.insertMode)):h===12?f(h,3):h===20?f(h,d(p.convertEol)):f(h,0):h===1?f(h,d(o.applicationCursorKeys)):h===3?f(h,p.windowOptions.setWinLines?l===80?2:l===132?1:0:0):h===6?f(h,d(o.origin)):h===7?f(h,d(o.wraparound)):h===8?f(h,3):h===9?f(h,d(i==="X10")):h===12?f(h,d(p.cursorBlink)):h===25?f(h,d(!s.isCursorHidden)):h===45?f(h,d(o.reverseWraparound)):h===66?f(h,d(o.applicationKeypad)):h===67?f(h,4):h===1e3?f(h,d(i==="VT200")):h===1002?f(h,d(i==="DRAG")):h===1003?f(h,d(i==="ANY")):h===1004?f(h,d(o.sendFocus)):h===1005?f(h,4):h===1006?f(h,d(n==="SGR")):h===1015?f(h,4):h===1016?f(h,d(n==="SGR_PIXELS")):h===1048?f(h,1):h===47||h===1047||h===1049?f(h,d(c===u)):h===2004?f(h,d(o.bracketedPasteMode)):h===2026?f(h,d(o.synchronizedOutput)):f(h,0)}_updateAttrColor(e,t,r,o,i){return t===2?(e|=50331648,e&=-16777216,e|=by.fromColorRGB([r,o,i])):t===5&&(e&=-50331904,e|=33554432|r&255),e}_extractColor(e,t,r){let o=[0,0,-1,0,0,0],i=0,n=0;do{if(o[n+i]=e.params[t+n],e.hasSubParams(t+n)){let s=e.getSubParams(t+n),a=0;do o[1]===5&&(i=1),o[n+a+1+i]=s[a];while(++a<s.length&&a+n+1+i<o.length);break}if(o[1]===5&&n+i>=2||o[1]===2&&n+i>=5)break;o[1]&&(i=1)}while(++n+t<e.length&&n+i<o.length);for(let s=2;s<o.length;++s)o[s]===-1&&(o[s]=0);switch(o[0]){case 38:r.fg=this._updateAttrColor(r.fg,o[1],o[3],o[4],o[5]);break;case 48:r.bg=this._updateAttrColor(r.bg,o[1],o[3],o[4],o[5]);break;case 58:r.extended=r.extended.clone(),r.extended.underlineColor=this._updateAttrColor(r.extended.underlineColor,o[1],o[3],o[4],o[5])}return n}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=gr.fg,e.bg=gr.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,r,o=this._curAttrData;for(let i=0;i<t;i++)r=e.params[i],r>=30&&r<=37?(o.fg&=-50331904,o.fg|=16777216|r-30):r>=40&&r<=47?(o.bg&=-50331904,o.bg|=16777216|r-40):r>=90&&r<=97?(o.fg&=-50331904,o.fg|=16777216|r-90|8):r>=100&&r<=107?(o.bg&=-50331904,o.bg|=16777216|r-100|8):r===0?this._processSGR0(o):r===1?o.fg|=134217728:r===3?o.bg|=67108864:r===4?(o.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,o)):r===5?o.fg|=536870912:r===7?o.fg|=67108864:r===8?o.fg|=1073741824:r===9?o.fg|=2147483648:r===2?o.bg|=134217728:r===21?this._processUnderline(2,o):r===22?(o.fg&=-134217729,o.bg&=-134217729):r===23?o.bg&=-67108865:r===24?(o.fg&=-268435457,this._processUnderline(0,o)):r===25?o.fg&=-536870913:r===27?o.fg&=-67108865:r===28?o.fg&=-1073741825:r===29?o.fg&=2147483647:r===39?(o.fg&=-67108864,o.fg|=gr.fg&16777215):r===49?(o.bg&=-67108864,o.bg|=gr.bg&16777215):r===38||r===48||r===58?i+=this._extractColor(e,i,o):r===53?o.bg|=1073741824:r===55?o.bg&=-1073741825:r===59?(o.extended=o.extended.clone(),o.extended.underlineColor=-1,o.updateExtended()):r===100?(o.fg&=-67108864,o.fg|=gr.fg&16777215,o.bg&=-67108864,o.bg|=gr.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",r);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${V.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${V.ESC}[${t};${r}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${V.ESC}[?${t};${r}R`);break;case 15:break;case 25:break;case 26:break;case 53:break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=gr.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(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){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";break}let r=t%2===1;this._coreService.decPrivateModes.cursorBlink=r}return!0}setScrollRegion(e){let t=e.params[0]||1,r;return(e.length<2||(r=e.params[1])>this._bufferService.rows||r===0)&&(r=this._bufferService.rows),r>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=r-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Kz(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${V.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>qz&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>qz&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){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(e){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(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],r=e.split(";");for(;r.length>1;){let o=r.shift(),i=r.shift();if(/^\d+$/.exec(o)){let n=parseInt(o);if(Xz(n))if(i==="?")t.push({type:0,index:n});else{let s=Vz(i);s&&t.push({type:1,index:n,color:s})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let r=e.slice(0,t).trim(),o=e.slice(t+1);return o?this._createHyperlink(r,o):r.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let r=e.split(":"),o,i=r.findIndex(n=>n.startsWith("id="));return i!==-1&&(o=r[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:o,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let r=e.split(";");for(let o=0;o<r.length&&!(t>=this._specialColors.length);++o,++t)if(r[o]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let i=Vz(r[o]);i&&this._onColor.fire([{type:1,index:this._specialColors[t],color:i}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],r=e.split(";");for(let o=0;o<r.length;++o)if(/^\d+$/.exec(r[o])){let i=parseInt(r[o]);Xz(i)&&t.push({type:2,index:i})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){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,eu),!0}selectCharset(e){return e.length!==2?(this.selectDefaultCharset(),!0):(e[0]==="/"||this._charsetService.setgCharset(Coe[e[0]],Er[e[1]]||eu),!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 e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,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=gr.clone(),this._eraseAttrDataInternal=gr.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Zi;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let r=this._activeBuffer.ybase+this._activeBuffer.y+t,o=this._activeBuffer.lines.get(r);o&&(o.fill(e),o.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let r=s=>(this._coreService.triggerDataEvent(`${V.ESC}${s}${V.ESC}\\`),!0),o=this._bufferService.buffer,i=this._optionsService.rawOptions;return r(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${o.scrollTop+1};${o.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-(i.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},qP=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Yz=e,e=t,t=Yz),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};qP=er([ne(0,ko)],qP);function Xz(e){return 0<=e&&e<256}var Roe=5e7,Zz=12,Eoe=50,koe=class extends Ee{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new J),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let r;for(;r=this._writeBuffer.shift();){this._action(r);let o=this._callbacks.shift();o&&o()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>Roe)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let r=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let o=this._writeBuffer[this._bufferOffset],i=this._action(o,t);if(i){let s=a=>performance.now()-r>=Zz?setTimeout(()=>this._innerWrite(0,a)):this._innerWrite(r,a);i.catch(a=>(queueMicrotask(()=>{throw a}),Promise.resolve(!1))).then(s);return}let n=this._callbacks[this._bufferOffset];if(n&&n(),this._bufferOffset++,this._pendingData-=o.length,performance.now()-r>=Zz)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>Eoe&&(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()}},KP=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let a=t.addMarker(t.ybase+t.y),l={data:e,id:this._nextId++,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(l,a)),this._dataByLinkId.set(l.id,l),l.id}let r=e,o=this._getEntryIdKey(r),i=this._entriesWithId.get(o);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let n=t.addMarker(t.ybase+t.y),s={id:this._nextId++,key:this._getEntryIdKey(r),data:r,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(s,n)),this._entriesWithId.set(s.key,s),this._dataByLinkId.set(s.id,s),s.id}addLineToLink(e,t){let r=this._dataByLinkId.get(e);if(r&&r.lines.every(o=>o.line!==t)){let o=this._bufferService.buffer.addMarker(t);r.lines.push(o),o.onDispose(()=>this._removeMarkerFromLink(r,o))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let r=e.lines.indexOf(t);r!==-1&&(e.lines.splice(r,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};KP=er([ne(0,ko)],KP);var Qz=!1,Ooe=class extends Ee{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new ef),this._onBinary=this._register(new J),this.onBinary=this._onBinary.event,this._onData=this._register(new J),this.onData=this._onData.event,this._onLineFeed=this._register(new J),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new J),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new J),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new J),this._instantiationService=new Jre,this.optionsService=this._register(new uoe(e)),this._instantiationService.setService(Oo,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance($P)),this._instantiationService.setService(ko,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(UP)),this._instantiationService.setService(p6,this._logService),this.coreService=this._register(this._instantiationService.createInstance(jP)),this._instantiationService.setService(nu,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(WP)),this._instantiationService.setService(u6,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(tu)),this._instantiationService.setService(xee,this.unicodeService),this._charsetService=this._instantiationService.createInstance(moe),this._instantiationService.setService(See,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(KP),this._instantiationService.setService(d6,this._oscLinkService),this._inputHandler=this._register(new Poe(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(no.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(no.forward(this._bufferService.onResize,this._onResize)),this._register(no.forward(this.coreService.onData,this._onData)),this._register(no.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 koe((t,r)=>this._inputHandler.parse(t,r))),this._register(no.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new J),this._onScroll.event(e=>{this._onScrollApi?.fire(e.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(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Qz&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Qz=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,J6),t=Math.max(t,eF),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(jz.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(jz(this._bufferService),!1))),this._windowsWrappingHeuristics.value=At(()=>{for(let t of e)t.dispose()})}}},Moe={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function Doe(e,t,r,o){let i={type:0,cancel:!1,key:void 0},n=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?i.key=V.ESC+"OA":i.key=V.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?i.key=V.ESC+"OD":i.key=V.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?i.key=V.ESC+"OC":i.key=V.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?i.key=V.ESC+"OB":i.key=V.ESC+"[B");break;case 8:i.key=e.ctrlKey?"\b":V.DEL,e.altKey&&(i.key=V.ESC+i.key);break;case 9:if(e.shiftKey){i.key=V.ESC+"[Z";break}i.key=V.HT,i.cancel=!0;break;case 13:i.key=e.altKey?V.ESC+V.CR:V.CR,i.cancel=!0;break;case 27:i.key=V.ESC,e.altKey&&(i.key=V.ESC+V.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;n?i.key=V.ESC+"[1;"+(n+1)+"D":t?i.key=V.ESC+"OD":i.key=V.ESC+"[D";break;case 39:if(e.metaKey)break;n?i.key=V.ESC+"[1;"+(n+1)+"C":t?i.key=V.ESC+"OC":i.key=V.ESC+"[C";break;case 38:if(e.metaKey)break;n?i.key=V.ESC+"[1;"+(n+1)+"A":t?i.key=V.ESC+"OA":i.key=V.ESC+"[A";break;case 40:if(e.metaKey)break;n?i.key=V.ESC+"[1;"+(n+1)+"B":t?i.key=V.ESC+"OB":i.key=V.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=V.ESC+"[2~");break;case 46:n?i.key=V.ESC+"[3;"+(n+1)+"~":i.key=V.ESC+"[3~";break;case 36:n?i.key=V.ESC+"[1;"+(n+1)+"H":t?i.key=V.ESC+"OH":i.key=V.ESC+"[H";break;case 35:n?i.key=V.ESC+"[1;"+(n+1)+"F":t?i.key=V.ESC+"OF":i.key=V.ESC+"[F";break;case 33:e.shiftKey?i.type=2:e.ctrlKey?i.key=V.ESC+"[5;"+(n+1)+"~":i.key=V.ESC+"[5~";break;case 34:e.shiftKey?i.type=3:e.ctrlKey?i.key=V.ESC+"[6;"+(n+1)+"~":i.key=V.ESC+"[6~";break;case 112:n?i.key=V.ESC+"[1;"+(n+1)+"P":i.key=V.ESC+"OP";break;case 113:n?i.key=V.ESC+"[1;"+(n+1)+"Q":i.key=V.ESC+"OQ";break;case 114:n?i.key=V.ESC+"[1;"+(n+1)+"R":i.key=V.ESC+"OR";break;case 115:n?i.key=V.ESC+"[1;"+(n+1)+"S":i.key=V.ESC+"OS";break;case 116:n?i.key=V.ESC+"[15;"+(n+1)+"~":i.key=V.ESC+"[15~";break;case 117:n?i.key=V.ESC+"[17;"+(n+1)+"~":i.key=V.ESC+"[17~";break;case 118:n?i.key=V.ESC+"[18;"+(n+1)+"~":i.key=V.ESC+"[18~";break;case 119:n?i.key=V.ESC+"[19;"+(n+1)+"~":i.key=V.ESC+"[19~";break;case 120:n?i.key=V.ESC+"[20;"+(n+1)+"~":i.key=V.ESC+"[20~";break;case 121:n?i.key=V.ESC+"[21;"+(n+1)+"~":i.key=V.ESC+"[21~";break;case 122:n?i.key=V.ESC+"[23;"+(n+1)+"~":i.key=V.ESC+"[23~";break;case 123:n?i.key=V.ESC+"[24;"+(n+1)+"~":i.key=V.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=V.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=V.DEL:e.keyCode===219?i.key=V.ESC:e.keyCode===220?i.key=V.FS:e.keyCode===221&&(i.key=V.GS);else if((!r||o)&&e.altKey&&!e.metaKey){let s=Moe[e.keyCode]?.[e.shiftKey?1:0];if(s)i.key=V.ESC+s;else if(e.keyCode>=65&&e.keyCode<=90){let a=e.ctrlKey?e.keyCode-64:e.keyCode+32,l=String.fromCharCode(a);e.shiftKey&&(l=l.toUpperCase()),i.key=V.ESC+l}else if(e.keyCode===32)i.key=V.ESC+(e.ctrlKey?V.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let a=e.code.slice(3,4);e.shiftKey||(a=a.toLowerCase()),i.key=V.ESC+a,i.cancel=!0}}else r&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(i.key=V.US),e.key==="@"&&(i.key=V.NUL));break}return i}var cr=0,Aoe=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new B0,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new B0,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((i,n)=>this._getKey(i)-this._getKey(n)),t=0,r=0,o=new Array(this._array.length+this._insertedValues.length);for(let i=0;i<o.length;i++)r>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[r])?(o[i]=e[t],t++):o[i]=this._array[r++];this._array=o,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(cr=this._search(t),cr===-1)||this._getKey(this._array[cr])!==t)return!1;do if(this._array[cr]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(cr),!0;while(++cr<this._array.length&&this._getKey(this._array[cr])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((i,n)=>i-n),t=0,r=new Array(this._array.length-e.length),o=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:r[o++]=this._array[i];this._array=r,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(cr=this._search(e),!(cr<0||cr>=this._array.length)&&this._getKey(this._array[cr])===e))do yield this._array[cr];while(++cr<this._array.length&&this._getKey(this._array[cr])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(cr=this._search(e),!(cr<0||cr>=this._array.length)&&this._getKey(this._array[cr])===e))do t(this._array[cr]);while(++cr<this._array.length&&this._getKey(this._array[cr])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,r=this._array.length-1;for(;r>=t;){let o=t+r>>1,i=this._getKey(this._array[o]);if(i>e)r=o-1;else if(i<e)t=o+1;else{for(;o>0&&this._getKey(this._array[o-1])===e;)o--;return o}}return t}},uP=0,Jz=0,Boe=class extends Ee{constructor(){super(),this._decorations=new Aoe(e=>e?.marker.line),this._onDecorationRegistered=this._register(new J),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new J),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(At(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Noe(e);if(t){let r=t.marker.onDispose(()=>t.dispose()),o=t.onDispose(()=>{o.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),r.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,r){let o=0,i=0;for(let n of this._decorations.getKeyIterator(t))o=n.options.x??0,i=o+(n.options.width??1),e>=o&&e<i&&(!r||(n.options.layer??"bottom")===r)&&(yield n)}forEachDecorationAtCell(e,t,r,o){this._decorations.forEachByKey(t,i=>{uP=i.options.x??0,Jz=uP+(i.options.width??1),e>=uP&&e<Jz&&(!r||(i.options.layer??"bottom")===r)&&o(i)})}},Noe=class extends xl{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new J),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new J),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=Vt.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=Vt.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Loe=1e3,Ioe=class{constructor(e,t=Loe){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,r){this._rowCount=r,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t;let o=performance.now();if(o-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=o,this._innerRefresh();else if(!this._additionalRefreshRequested){let i=o-this._lastRefreshMs,n=this._debounceThresholdMS-i;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},n)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},e6=20,t6=!1,N0=class extends Ee{constructor(e,t,r,o){super(),this._terminal=e,this._coreBrowserService=r,this._renderService=o,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=i.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let n=0;n<this._terminal.rows;n++)this._rowElements[n]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[n]);if(this._topBoundaryFocusListener=n=>this._handleBoundaryFocus(n,0),this._bottomBoundaryFocusListener=n=>this._handleBoundaryFocus(n,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Ioe(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");t6?(this._accessibilityContainer.classList.add("debug"),this._rowContainer.classList.add("debug"),this._debugRootContainer=i.createElement("div"),this._debugRootContainer.classList.add("xterm"),this._debugRootContainer.appendChild(i.createTextNode("------start a11y------")),this._debugRootContainer.appendChild(this._accessibilityContainer),this._debugRootContainer.appendChild(i.createTextNode("------end a11y------")),this._terminal.element.insertAdjacentElement("afterend",this._debugRootContainer)):this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(n=>this._handleResize(n.rows))),this._register(this._terminal.onRender(n=>this._refreshRows(n.start,n.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(n=>this._handleChar(n))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
236
236
  `))),this._register(this._terminal.onA11yTab(n=>this._handleTab(n))),this._register(this._terminal.onKey(n=>this._handleKey(n.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(_e(i,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(At(()=>{t6?this._debugRootContainer.remove():this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<e6+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
237
237
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===e6+1&&(this._liveRegion.textContent+=dP.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let r=this._terminal.buffer,o=r.lines.length.toString();for(let i=e;i<=t;i++){let n=r.lines.get(r.ydisp+i),s=[],a=n?.translateToString(!0,void 0,void 0,s)||"",l=(r.ydisp+i+1).toString(),c=this._rowElements[i];c&&(a.length===0?(c.textContent="\xA0",this._rowColumns.set(c,[0,1])):(c.textContent=a,this._rowColumns.set(c,s)),c.setAttribute("aria-posinset",l),c.setAttribute("aria-setsize",o),this._alignRowWidth(c))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let r=e.target,o=this._rowElements[t===0?1:this._rowElements.length-2],i=r.getAttribute("aria-posinset"),n=t===0?"1":`${this._terminal.buffer.lines.length}`;if(i===n||e.relatedTarget!==o)return;let s,a;if(t===0?(s=r,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(s=this._rowElements.shift(),a=r,this._rowContainer.removeChild(s)),s.removeEventListener("focus",this._topBoundaryFocusListener),a.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let l=this._createAccessibilityTreeNode();this._rowElements.unshift(l),this._rowContainer.insertAdjacentElement("afterbegin",l)}else{let l=this._createAccessibilityTreeNode();this._rowElements.push(l),this._rowContainer.appendChild(l)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},r={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(r.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===r.node&&t.offset>r.offset)&&([t,r]=[r,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let o=this._rowElements.slice(-1)[0];if(r.node.compareDocumentPosition(o)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(r={node:o,offset:o.textContent?.length??0}),!this._rowContainer.contains(r.node))return;let i=({node:a,offset:l})=>{let c=a instanceof Text?a.parentNode:a,u=parseInt(c?.getAttribute("aria-posinset"),10)-1;if(isNaN(u))return console.warn("row is invalid. Race condition?"),null;let p=this._rowColumns.get(c);if(!p)return console.warn("columns is null. Race condition?"),null;let f=l<p.length?p[l]:p.slice(-1)[0]+1;return f>=this._terminal.cols&&(++u,f=0),{row:u,column:f}},n=i(t),s=i(r);if(!(!n||!s)){if(n.row>s.row||n.row===s.row&&n.column>=s.column)throw new Error("invalid range");this._terminal.select(n.column,n.row,(s.row-n.row)*this._terminal.cols-n.column+s.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform="";let t=e.getBoundingClientRect().width,r=this._rowColumns.get(e)?.slice(-1)?.[0];if(!r)return;let o=r*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${o/t})`}};N0=er([ne(1,YP),ne(2,ua),ne(3,pa)],N0);var GP=class extends Ee{constructor(e,t,r,o,i){super(),this._element=e,this._mouseService=t,this._renderService=r,this._bufferService=o,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new J),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new J),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(At(()=>{ou(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(_e(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(_e(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(_e(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(_e(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let r=e.composedPath();for(let o=0;o<r.length;o++){let i=r[o];if(i.classList.contains("xterm"))break;if(i.classList.contains("xterm-hover"))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized){this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1;return}this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(o=>{o?.forEach(i=>{i.link.dispose&&i.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let r=!1;for(let[o,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(o)&&(r=this._checkLinkProviderResult(o,e,r)):i.provideLinks(e.y,n=>{if(this._isMouseOut)return;let s=n?.map(a=>({link:a}));this._activeProviderReplies?.set(o,s),r=this._checkLinkProviderResult(o,e,r),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let r=new Set;for(let o=0;o<t.size;o++){let i=t.get(o);if(i)for(let n=0;n<i.length;n++){let s=i[n],a=s.link.range.start.y<e?0:s.link.range.start.x,l=s.link.range.end.y>e?this._bufferService.cols:s.link.range.end.x;for(let c=a;c<=l;c++){if(r.has(c)){i.splice(n--,1);break}r.add(c)}}}}_checkLinkProviderResult(e,t,r){if(!this._activeProviderReplies)return r;let o=this._activeProviderReplies.get(e),i=!1;for(let n=0;n<e;n++)(!this._activeProviderReplies.has(n)||this._activeProviderReplies.get(n))&&(i=!0);if(!i&&o){let n=o.find(s=>this._linkAtPosition(s.link,t));n&&(r=!0,this._handleNewLink(n))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!r)for(let n=0;n<this._activeProviderReplies.size;n++){let s=this._activeProviderReplies.get(n)?.find(a=>this._linkAtPosition(a.link,t));if(s){r=!0,this._handleNewLink(s);break}}return r}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&zoe(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,ou(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:r=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==r&&(this._currentLink.state.decorations.pointerCursor=r,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",r))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:r=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==r&&(this._currentLink.state.decorations.underline=r,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,r))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(r=>{if(!this._currentLink)return;let o=r.start===0?0:r.start+1+this._bufferService.buffer.ydisp,i=this._bufferService.buffer.ydisp+1+r.end;if(this._currentLink.link.range.start.y>=o&&this._currentLink.link.range.end.y<=i&&(this._clearCurrentLink(o,i),this._lastMouseEvent)){let n=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);n&&this._askForLink(n,!1)}})))}_linkHover(e,t,r){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(r,t.text)}_fireUnderlineEvent(e,t){let r=e.range,o=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(r.start.x-1,r.start.y-o-1,r.end.x,r.end.y-o-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,r){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(r,t.text)}_linkAtPosition(e,t){let r=e.range.start.y*this._bufferService.cols+e.range.start.x,o=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return r<=i&&i<=o}_positionFromMouseEvent(e,t,r){let o=r.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(o)return{x:o[0],y:o[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,r,o,i){return{x1:e,y1:t,x2:r,y2:o,cols:this._bufferService.cols,fg:i}}};GP=er([ne(1,XP),ne(2,pa),ne(3,ko),ne(4,h6)],GP);function zoe(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var Foe=class extends Ooe{constructor(e={}){super(e),this._linkifier=this._register(new ef),this.browser=$6,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new ef),this._onCursorMove=this._register(new J),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new J),this.onKey=this._onKey.event,this._onRender=this._register(new J),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new J),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new J),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new J),this.onBell=this._onBell.event,this._onFocus=this._register(new J),this._onBlur=this._register(new J),this._onA11yCharEmitter=this._register(new J),this._onA11yTabEmitter=this._register(new J),this._onWillOpen=this._register(new J),this._setup(),this._decorationService=this._instantiationService.createInstance(Boe),this._instantiationService.setService(_y,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Rre),this._instantiationService.setService(h6,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(hP)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(no.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(no.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(no.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(no.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(At(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let r,o="";switch(t.index){case 256:r="foreground",o="10";break;case 257:r="background",o="11";break;case 258:r="cursor",o="12";break;default:r="ansi",o="4;"+t.index}switch(t.type){case 0:let i=Dt.toColorRGB(r==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[r]);this.coreService.triggerDataEvent(`${V.ESC}]${o};${woe(i)}${H6.ST}`);break;case 1:if(r==="ansi")this._themeService.modifyColors(n=>n.ansi[t.index]=vr.toColor(...t.color));else{let n=r;this._themeService.modifyColors(s=>s[n]=vr.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(N0,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(V.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(V.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let r=Math.min(this.buffer.x,this.cols-1),o=this._renderService.dimensions.css.cell.height,i=t.getWidth(r),n=this._renderService.dimensions.css.cell.width*i,s=this.buffer.y*this._renderService.dimensions.css.cell.height,a=r*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=s+"px",this.textarea.style.width=n+"px",this.textarea.style.height=o+"px",this.textarea.style.lineHeight=o+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(_e(this.element,"copy",t=>{this.hasSelection()&&mee(t,this._selectionService)}));let e=t=>yee(t,this.textarea,this.coreService,this.optionsService);this._register(_e(this.textarea,"paste",e)),this._register(_e(this.element,"paste",e)),j6?this._register(_e(this.element,"mousedown",t=>{t.button===2&&rz(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(_e(this.element,"contextmenu",t=>{rz(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),iR&&this._register(_e(this.element,"auxclick",t=>{t.button===1&&n6(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(_e(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(_e(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(_e(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(_e(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(_e(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(_e(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(_e(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(_e(this.screenElement,"mousemove",i=>this.updateCursorStyle(i))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let r=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",pP.get()),q6||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>r.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Cre,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ua,this._coreBrowserService),this._register(_e(this.textarea,"focus",i=>this._handleTextAreaFocus(i))),this._register(_e(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(LP,this._document,this._helperContainer),this._instantiationService.setService(I0,this._charSizeService),this._themeService=this._instantiationService.createInstance(HP),this._instantiationService.setService(tf,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(D0),this._instantiationService.setService(f6,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(zP,this.rows,this.screenElement)),this._instantiationService.setService(pa,this._renderService),this._register(this._renderService.onRenderedViewportChange(i=>this._onRender.fire(i))),this.onResize(i=>this._renderService.resize(i.cols,i.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(AP,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(IP),this._instantiationService.setService(XP,this._mouseService);let o=this._linkifier.value=this._register(this._instantiationService.createInstance(GP,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(MP,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(i=>{super.scrollLines(i,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(FP,this.element,this.screenElement,o)),this._instantiationService.setService(wee,this._selectionService),this._register(this._selectionService.onRequestScrollLines(i=>this.scrollLines(i.amount,i.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(i=>this._renderService.handleSelectionChanged(i.start,i.end,i.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(i=>{this.textarea.value=i,this.textarea.focus(),this.textarea.select()})),this._register(no.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(DP,this.screenElement)),this._register(_e(this.element,"mousedown",i=>this._selectionService.handleMouseDown(i))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(N0,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",i=>this._handleScreenReaderModeOptionChange(i))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(M0,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",i=>{!this._overviewRulerRenderer&&i&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(M0,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(NP,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function r(n){let s=e._mouseService.getMouseReportCoords(n,e.screenElement);if(!s)return!1;let a,l;switch(n.overrideType||n.type){case"mousemove":l=32,n.buttons===void 0?(a=3,n.button!==void 0&&(a=n.button<3?n.button:3)):a=n.buttons&1?0:n.buttons&4?1:n.buttons&2?2:3;break;case"mouseup":l=0,a=n.button<3?n.button:3;break;case"mousedown":l=1,a=n.button<3?n.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(n)===!1)return!1;let c=n.deltaY;if(c===0||e.coreMouseService.consumeWheelEvent(n,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;l=c<0?0:1,a=4;break;default:return!1}return l===void 0||a===void 0||a>4?!1:e.coreMouseService.triggerMouseEvent({col:s.col,row:s.row,x:s.x,y:s.y,button:a,action:l,ctrl:n.ctrlKey,alt:n.altKey,shift:n.shiftKey})}let o={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:n=>(r(n),n.buttons||(this._document.removeEventListener("mouseup",o.mouseup),o.mousedrag&&this._document.removeEventListener("mousemove",o.mousedrag)),this.cancel(n)),wheel:n=>(r(n),this.cancel(n,!0)),mousedrag:n=>{n.buttons&&r(n)},mousemove:n=>{n.buttons||r(n)}};this._register(this.coreMouseService.onProtocolChange(n=>{n?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(n)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),n&8?o.mousemove||(t.addEventListener("mousemove",i.mousemove),o.mousemove=i.mousemove):(t.removeEventListener("mousemove",o.mousemove),o.mousemove=null),n&16?o.wheel||(t.addEventListener("wheel",i.wheel,{passive:!1}),o.wheel=i.wheel):(t.removeEventListener("wheel",o.wheel),o.wheel=null),n&2?o.mouseup||(o.mouseup=i.mouseup):(this._document.removeEventListener("mouseup",o.mouseup),o.mouseup=null),n&4?o.mousedrag||(o.mousedrag=i.mousedrag):(this._document.removeEventListener("mousemove",o.mousedrag),o.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(_e(t,"mousedown",n=>{if(n.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(n)))return r(n),o.mouseup&&this._document.addEventListener("mouseup",o.mouseup),o.mousedrag&&this._document.addEventListener("mousemove",o.mousedrag),this.cancel(n)})),this._register(_e(t,"wheel",n=>{if(!o.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(n)===!1)return!1;if(!this.buffer.hasScrollback){if(n.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(n,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(n,!0);let s=V.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(n.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(s,!0),this.cancel(n,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){i6(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,r){this._selectionService.setSelection(e,t,r)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let r=Doe(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),r.type===3||r.type===2){let o=this.rows-1;return this.scrollLines(r.type===2?-o:o),this.cancel(e,!0)}if(r.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(r.cancel&&this.cancel(e,!0),!r.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((r.key===V.ETX||r.key===V.CR)&&(this.textarea.value=""),this._onKey.fire({key:r.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(r.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let r=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?r:r&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Hoe(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),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 e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(gr));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains("focus")?this.coreService.triggerDataEvent(V.ESC+"[I"):this.coreService.triggerDataEvent(V.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let t=this._renderService.dimensions.css.canvas.width.toFixed(0),r=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${V.ESC}[4;${r};${t}t`);break;case 1:let o=this._renderService.dimensions.css.cell.width.toFixed(0),i=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${V.ESC}[6;${i};${o}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function Hoe(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var Uoe=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let r={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(r),t.dispose=()=>this._wrappedAddonDispose(r),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let r=0;r<this._addons.length;r++)if(this._addons[r]===e){t=r;break}if(t===-1)throw new Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},$oe=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Zi)}translateToString(e,t,r){return this._line.translateToString(e,t,r)}},r6=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,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(e){let t=this._buffer.lines.get(e);if(t)return new $oe(t)}getNullCell(){return new Zi}},joe=class extends Ee{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new J),this.onBufferChange=this._onBufferChange.event,this._normal=new r6(this._core.buffers.normal,"normal"),this._alternate=new r6(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 new 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)}},Woe=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,r=>t(r.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(r,o)=>t(r,o.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},Voe=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},qoe=["cols","rows"],ns=0,rF=class extends Ee{constructor(e){super(),this._core=this._register(new Foe(e)),this._addonManager=this._register(new Uoe),this._publicOptions={...this._core.options};let t=o=>this._core.options[o],r=(o,i)=>{this._checkReadonlyOptions(o),this._core.options[o]=i};for(let o in this._core.options){let i={get:t.bind(this,o),set:r.bind(this,o)};Object.defineProperty(this._publicOptions,o,i)}}_checkReadonlyOptions(e){if(qoe.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new Woe(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new Voe(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new joe(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,r){this._verifyIntegers(e,t,r),this._core.select(e,t,r)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
238
- `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return pP.get()},set promptLabel(e){pP.set(e)},get tooMuchOutput(){return dP.get()},set tooMuchOutput(e){dP.set(e)}}}_verifyIntegers(...e){for(ns of e)if(ns===1/0||isNaN(ns)||ns%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(ns of e)if(ns&&(ns===1/0||isNaN(ns)||ns%1!==0||ns<0))throw new Error("This API only accepts positive integers")}};function oF(e){let t=new rF({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', Consolas, monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4"}}),r=new Q4;return t.loadAddon(r),t.loadAddon(new J4((o,i)=>{window.open(i,"_blank","noopener")})),t.open(e),r.fit(),{term:t,fitAddon:r,dispose:()=>t.dispose()}}function iF(e,t,r,o){if(e.type!=="keydown"||!e.ctrlKey||e.shiftKey||e.altKey)return!0;let i=e.key.toLowerCase();return i==="c"&&t.hasSelection()?(e.preventDefault(),r.writeText(t.getSelection()),!1):i==="v"?(e.preventDefault(),r.readText().then(o),!1):!0}function nF(e,t,r,o,i){let n=oF(e);n.term.onData(c=>r(t,c)),n.term.attachCustomKeyEventHandler(c=>iF(c,n.term,navigator.clipboard,u=>n.term.paste(u)));let s=o(t,c=>n.term.write(c)),a=new ResizeObserver(()=>{n.fitAddon.fit(),i(t,n.term.cols,n.term.rows)});return a.observe(e),{handle:n,cleanup:()=>{a.disconnect(),s(),n.dispose()}}}function sF(e,t,r,o,i,n){let s=(0,Ty.useRef)(null);(0,Ty.useEffect)(()=>{let a=e.current;if(!a)return;let{handle:l,cleanup:c}=nF(a,t,o,i,n);return s.current=l,()=>{c(),s.current=null}},[e,t,i,o,n]),(0,Ty.useEffect)(()=>{let a=s.current;if(!r||!a)return;let l=setTimeout(()=>{a.fitAddon.fit(),a.term.focus(),n(t,a.term.cols,a.term.rows)},50);return()=>clearTimeout(l)},[r,t,n])}var cF=b(C(),1);function lF({sessionId:e,visible:t,onOutput:r,sendInput:o,sendResize:i}){let n=(0,aF.useRef)(null);return sF(n,e,t,o,r,i),(0,cF.jsx)(X,{ref:n,sx:{position:"absolute",inset:"0 0 0 8px",visibility:t?"visible":"hidden",pointerEvents:t?"auto":"none"}})}var su=b(C(),1);function uF({sessions:e,activeId:t,initialized:r,onOutput:o,sendInput:i,sendResize:n}){let s=t!==null&&e.some(a=>a.id===t)&&!r.has(t);return(0,su.jsxs)(X,{sx:{flex:1,position:"relative",bgcolor:"background.default"},children:[e.map(a=>(0,su.jsx)(lF,{sessionId:a.id,visible:a.id===t,onOutput:o,sendInput:i,sendResize:n},a.id)),s&&(0,su.jsx)(Z4,{}),e.length===0&&(0,su.jsx)(X,{sx:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:(0,su.jsx)(G,{variant:"body2",color:"text.disabled",children:"Create a session to get started"})})]})}var pF=b(C(),1),dF=fe((0,pF.jsx)("path",{d:"m22.7 19-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4"}),"Build");var Qi=b(C(),1);function fF({message:e}){return e.role==="tool"?(0,Qi.jsx)(Koe,{tool:e.tool,target:e.target}):(0,Qi.jsx)(Goe,{role:e.role,text:e.text})}function Koe({tool:e,target:t}){return(0,Qi.jsxs)(X,{sx:{display:"flex",alignItems:"center",gap:1,py:.5,pl:1},children:[(0,Qi.jsx)(dF,{sx:{fontSize:14,color:"text.disabled"}}),(0,Qi.jsxs)(G,{variant:"caption",sx:{color:"text.secondary",fontFamily:"monospace"},children:[(0,Qi.jsx)(X,{component:"span",sx:{color:"warning.main"},children:e}),t&&(0,Qi.jsxs)(X,{component:"span",children:[" ",t]})]})]})}function Goe({role:e,text:t}){let r=e==="user",o=r?"info.main":"success.main";return(0,Qi.jsxs)(X,{sx:{mb:1.5,pl:1.5,py:1,pr:1,borderLeft:2,borderColor:o,borderTopRightRadius:1,borderBottomRightRadius:1,bgcolor:r?"action.hover":"transparent"},children:[(0,Qi.jsx)(G,{variant:"caption",sx:{color:o,fontWeight:600,display:"block",mb:.5},children:r?"User":"Assistant"}),(0,Qi.jsx)(G,{variant:"body2",sx:{color:"text.primary",whiteSpace:"pre-wrap",overflowWrap:"anywhere",lineHeight:1.6},children:t})]})}var cs=b(C(),1);function Yoe(e){let t=new Map;return e.map(r=>{let o=r.role==="tool"?`tool:${r.tool}:${r.target}`:`${r.role}:${r.text.slice(0,40)}`,i=t.get(o)??0;return t.set(o,i+1),{...r,key:`${o}#${i}`}})}function mF({messages:e,loading:t}){return t?(0,cs.jsxs)(X,{sx:hF,children:[(0,cs.jsx)(Dr,{size:20}),(0,cs.jsx)(G,{variant:"caption",color:"text.disabled",children:"Loading transcript\u2026"})]}):e.length===0?(0,cs.jsx)(X,{sx:hF,children:(0,cs.jsx)(G,{variant:"body2",color:"text.disabled",children:"No transcript available"})}):(0,cs.jsx)(X,{sx:{position:"absolute",inset:0,overflowY:"auto",p:2},children:(0,cs.jsx)(X,{sx:{maxWidth:820,mx:"auto"},children:Yoe(e).map(r=>(0,cs.jsx)(fF,{message:r},r.key))})})}var hF={position:"absolute",inset:0,display:"flex",flexDirection:"column",gap:1.5,alignItems:"center",justifyContent:"center"};var nR=b(C(),1);function yF({sessionId:e,transcript:t}){let r=t?.sessionId===e;return(0,nR.jsx)(X,{sx:{flex:1,position:"relative",bgcolor:"background.default"},children:(0,nR.jsx)(mF,{messages:r?t?.messages??[]:[],loading:!r})})}var sR=b(C(),1);function gF({viewingTranscriptSessionId:e,transcript:t,...r}){return e!==null?(0,sR.jsx)(yF,{sessionId:e,transcript:t}):(0,sR.jsx)(uF,{...r})}var wy=b(C(),1);function vF({socket:e}){let[t,r]=(0,$0.useState)("active"),{requestHistory:o,clearTranscript:i}=e,n=(0,$0.useCallback)(s=>{s==="history"?o():i(),r(s)},[o,i]);return(0,wy.jsxs)(X,{sx:{display:"flex",width:"100%",height:"100%"},children:[(0,wy.jsx)(Y4,{socket:e,tab:t,onTabChange:n}),(0,wy.jsx)(gF,{sessions:e.sessions,activeId:e.activeId,initialized:e.initialized,onOutput:e.onOutput,sendInput:e.sendInput,sendResize:e.sendResize,viewingTranscriptSessionId:e.viewingTranscriptSessionId,transcript:e.transcript})]})}var Ko=b(C(),1);function Xoe(){return(0,Ko.jsx)(hp,{maxWidth:"md",sx:{py:3,px:2},children:(0,Ko.jsx)(i4,{})})}function bF({socket:e}){return(0,Ko.jsxs)(Hc,{children:[(0,Ko.jsx)(jo,{path:"sessions",element:(0,Ko.jsx)(X,{sx:{display:"flex",width:"100%",height:"calc(100vh - 48px)"},children:(0,Ko.jsx)(vF,{socket:e})})}),(0,Ko.jsx)(jo,{path:"backlog/*",element:(0,Ko.jsx)(Xoe,{})}),(0,Ko.jsx)(jo,{path:"news",element:(0,Ko.jsx)(l4,{})}),(0,Ko.jsx)(jo,{path:"*",element:(0,Ko.jsx)(fC,{to:"/sessions",replace:!0})})]})}var j0=b(N(),1),Zoe=5e3;function _F(e){let[t,r]=(0,j0.useState)(null);return(0,j0.useEffect)(()=>{if(!e){r(null);return}let o=!1,i=async()=>{try{let a=await(await fetch(`/api/git-status?cwd=${encodeURIComponent(e)}`)).json();o||r(a??null)}catch{o||r(null)}};i();let n=setInterval(i,Zoe);return()=>{o=!0,clearInterval(n)}},[e]),t}var us=b(C(),1),Qoe={display:"flex",alignItems:"center",gap:1,ml:2,fontFamily:"monospace",fontSize:13,cursor:"default"},Joe={maxHeight:360,overflow:"auto",fontFamily:"monospace",fontSize:12},eie={tooltip:{sx:{maxWidth:"none"}}},SF=[{key:"new",label:"New",prefix:"+",color:"success.main"},{key:"modified",label:"Modified",prefix:"~",color:"warning.main"},{key:"deleted",label:"Deleted",prefix:"-",color:"error.main"}];function tie({counts:e}){return(0,us.jsx)(X,{sx:Joe,children:SF.filter(t=>e[t.key].length>0).map(t=>(0,us.jsxs)(X,{sx:{mb:.5,"&:last-child":{mb:0}},children:[(0,us.jsxs)(X,{sx:{color:t.color,fontWeight:700},children:[t.label," (",e[t.key].length,")"]}),e[t.key].map(r=>(0,us.jsx)(X,{sx:{pl:1,whiteSpace:"nowrap"},children:r},r))]},t.key))})}function xF({cwd:e}){let t=_F(e),r=t?SF.map(o=>({...o,count:t[o.key].length})).filter(o=>o.count>0):[];return!t||r.length===0?null:(0,us.jsx)($n,{title:(0,us.jsx)(tie,{counts:t}),slotProps:eie,children:(0,us.jsx)(X,{sx:Qoe,children:r.map(o=>(0,us.jsxs)(X,{component:"span",sx:{color:o.color},children:[o.prefix,o.count]},o.key))})})}var of=b(C(),1),rie=["/sessions","/backlog","/news"];function TF(){let e=Po(),t=zr(),r=rie.findIndex(i=>e.pathname.startsWith(i)),o=i=>{e.pathname!==i&&t(i)};return(0,of.jsxs)(Lh,{value:r===-1?0:r,textColor:"inherit",indicatorColor:"secondary",children:[(0,of.jsx)(Na,{label:"Sessions",onClick:()=>o("/sessions")}),(0,of.jsx)(Na,{label:"Backlog",onClick:()=>o("/backlog")}),(0,of.jsx)(Na,{label:"News",onClick:()=>o("/news")})]})}var CF=b(N(),1);var aR=b(C(),1);function wF(e){return(0,aR.jsx)(Wu,{viewBox:"-3 -3 30 30",...e,children:(0,aR.jsx)("path",{d:"M23.15 2.587L18.21.21a1.494 1.494 0 0 0-1.705.29l-9.46 8.63-4.12-3.128a.999.999 0 0 0-1.276.057L.327 7.261A1 1 0 0 0 .326 8.74L3.899 12 .326 15.26a1 1 0 0 0 .001 1.479L1.65 17.94a.999.999 0 0 0 1.276.057l4.12-3.128 9.46 8.63a1.492 1.492 0 0 0 1.704.29l4.942-2.377A1.5 1.5 0 0 0 24 20.06V3.939a1.5 1.5 0 0 0-.85-1.352zm-5.146 14.861L10.826 12l7.178-5.448v10.896z"})})}var ps=b(C(),1),oie={color:"inherit"};function PF({cwd:e}){let[t,r]=(0,CF.useState)(null);async function o(){try{let i=await fetch(`/api/open-in-code?cwd=${encodeURIComponent(e)}`,{method:"POST"});if(!i.ok){let n=await i.json().catch(()=>null);r(n?.error??"Failed to open VS Code")}}catch{r("Failed to open VS Code")}}return(0,ps.jsxs)(ps.Fragment,{children:[(0,ps.jsx)($n,{title:"Open in VS Code",children:(0,ps.jsx)("span",{children:(0,ps.jsx)(Kt,{sx:oie,disabled:!e,onClick:o,children:(0,ps.jsx)(wF,{})})})}),(0,ps.jsx)(qd,{error:t,onClose:()=>r(null)})]})}var FKe=b(N(),1);var RF=b(C(),1),EF=fe((0,RF.jsx)("path",{d:"M12 1.27a11 11 0 00-3.48 21.46c.55.09.73-.28.73-.55v-1.84c-3.03.64-3.67-1.46-3.67-1.46-.55-1.29-1.28-1.65-1.28-1.65-.92-.65.1-.65.1-.65 1.1 0 1.73 1.1 1.73 1.1.92 1.65 2.57 1.2 3.21.92a2 2 0 01.64-1.47c-2.47-.27-5.04-1.19-5.04-5.5 0-1.1.46-2.1 1.2-2.84a3.76 3.76 0 010-2.93s.91-.28 3.11 1.1c1.8-.49 3.7-.49 5.5 0 2.1-1.38 3.02-1.1 3.02-1.1a3.76 3.76 0 010 2.93c.83.74 1.2 1.74 1.2 2.94 0 4.21-2.57 5.13-5.04 5.4.45.37.82.92.82 2.02v3.03c0 .27.1.64.73.55A11 11 0 0012 1.27"}),"GitHub");var V0=b(N(),1),W0=b(C(),1),iie={color:"inherit"};function kF({cwd:e}){let[t,r]=(0,V0.useState)(null);return(0,V0.useEffect)(()=>{if(!e){r(null);return}let o=!1;return(async()=>{try{let n=await(await fetch(`/api/github-url?cwd=${encodeURIComponent(e)}`)).json();o||r(n?.url??null)}catch{o||r(null)}})(),()=>{o=!0}},[e]),t?(0,W0.jsx)($n,{title:"Open in GitHub",children:(0,W0.jsx)(Kt,{sx:iie,onClick:()=>window.open(t,"_blank"),children:(0,W0.jsx)(EF,{})})}):null}var nf=b(N(),1);var MF=b(C(),1);function OF({inputRef:e,value:t,onChange:r,onKeyDown:o}){return(0,MF.jsx)(fo,{inputRef:e,value:t,onChange:i=>r(i.target.value),onKeyDown:o,placeholder:"Filter repos...",size:"small",fullWidth:!0,slotProps:{input:{sx:{fontSize:12}}},sx:{p:.5}})}var q0=b(N(),1);var AF=b(C(),1);function DF({cwd:e,selected:t,highlighted:r,onHover:o,onSelect:i}){let n=(0,q0.useRef)(null);return(0,q0.useEffect)(()=>{r&&n.current?.scrollIntoView({block:"nearest"})},[r]),(0,AF.jsx)(Da,{ref:n,selected:t,title:e,onClick:i,onMouseEnter:o,sx:{fontSize:12,...r&&{bgcolor:"action.hover"}},children:K0(e)})}var lR=b(C(),1);function BF({repos:e,selected:t,highlight:r,onHighlight:o,onSelect:i}){return(0,lR.jsx)(mc,{dense:!0,children:e.map((n,s)=>(0,lR.jsx)(DF,{cwd:n,selected:n===t,highlighted:s===r,onHover:()=>o(s),onSelect:()=>i(n)},n))})}var G0=b(N(),1);function NF(e,t,r,o){let[i,n]=(0,G0.useState)(0);return(0,G0.useEffect)(()=>{n(0)},[t]),{highlight:i,setHighlight:n,onKeyDown:a=>{let l=e.length;if(a.key==="ArrowDown")a.preventDefault(),l>0&&n(c=>(c+1)%l);else if(a.key==="ArrowUp")a.preventDefault(),l>0&&n(c=>(c-1+l)%l);else if(a.key==="Enter"){a.preventDefault();let c=e[i];c&&(r(c),o())}else a.key==="Escape"&&(a.preventDefault(),o())}}}var Cy=b(C(),1);function K0(e){let t=e.includes("\\")?"\\":"/";return e.split(t).filter(Boolean).pop()??e}var nie={...Kd};function LF({repos:e,selected:t,onSelect:r,close:o}){let[i,n]=(0,nf.useState)(""),s=(0,nf.useRef)(null);(0,nf.useEffect)(()=>{s.current?.focus()},[]);let a=i.trim().toLowerCase(),l=a?e.filter(d=>d.toLowerCase().includes(a)):e,{highlight:c,setHighlight:u,onKeyDown:p}=NF(l,a,r,o);return(0,Cy.jsxs)(vt,{elevation:4,sx:nie,children:[(0,Cy.jsx)(OF,{inputRef:s,value:i,onChange:n,onKeyDown:p}),(0,Cy.jsx)(BF,{repos:l,selected:t,highlight:c,onHighlight:u,onSelect:d=>{r(d),o()}})]})}var cR=b(C(),1);function IF({repos:e,selected:t,onSelect:r}){return(0,cR.jsx)(Gd,{label:t?K0(t):"Select repo...",children:o=>(0,cR.jsx)(LF,{repos:e,selected:t,onSelect:r,close:o})})}var uR={"assist-draft":{label:"draft",args:["draft","--once"],prompt:!0,nav:!0},"assist-bug":{label:"bug",args:["bug","--once"],prompt:!0,nav:!0},"assist-next":{label:"next",args:["next","--once"],prompt:!1,nav:!0},"assist-refine":{label:"refine",args:["refine","--once"],prompt:!0,nav:!1}};function sie(e){return e in uR}function aie(e,t){let r=[...uR[e].args],o=t?.trim();return o&&r.push(o),r}function zF(e,t,r,o,i){if(sie(e)&&t){r(aie(e,i),t);return}o(e)}var pR=Object.entries(uR).map(([e,{label:t,prompt:r,nav:o}])=>({value:e,label:t,prompt:r,nav:o})),FF="Enter prompt...";var UF=b(N(),1);var sf=b(C(),1);function lie(e,t){e.key==="Enter"&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),t.trim()!==""&&e.currentTarget.closest("form")?.requestSubmit())}function HF({value:e,onChange:t,onSubmit:r}){return(0,sf.jsx)(vt,{elevation:4,sx:{...Kd,left:"auto",width:320},children:(0,sf.jsxs)(Ve,{component:"form",direction:"row",spacing:1,sx:{p:1,alignItems:"flex-start"},onSubmit:o=>{o.preventDefault(),r()},children:[(0,sf.jsx)(fo,{value:e,onChange:o=>t(o.target.value),onKeyDown:o=>lie(o,e),placeholder:FF,size:"small",autoFocus:!0,fullWidth:!0,multiline:!0,maxRows:7,slotProps:{input:{sx:{fontSize:13}}}}),(0,sf.jsx)(Le,{type:"submit",variant:"contained",size:"small",sx:{whiteSpace:"nowrap"},children:"Start"})]})})}var dR=b(C(),1);function Y0({disabled:e,onSubmit:t,label:r="prompt",allowEmpty:o=!1}){let[i,n]=(0,UF.useState)("");return(0,dR.jsx)(Gd,{label:r,disabled:e,children:s=>(0,dR.jsx)(HF,{value:i,onChange:n,onSubmit:()=>{!o&&!i.trim()||(t(i),n(""),s())}})})}var au=b(C(),1),cie={textTransform:"none",fontSize:11,fontWeight:600};function $F({onSelect:e,disabled:t=!1,children:r}){return(0,au.jsxs)(au.Fragment,{children:[pR.filter(o=>o.nav&&o.prompt).map(o=>(0,au.jsx)(Y0,{label:o.label,allowEmpty:!0,disabled:t,onSubmit:i=>e(o.value,i)},o.value)),r,pR.filter(o=>o.nav&&!o.prompt).map(o=>(0,au.jsx)(Le,{size:"small",variant:"outlined",disabled:t,onClick:()=>e(o.value),sx:cie,children:o.label},o.value))]})}var X0=b(C(),1);function jF({onCreate:e,onCreateAssist:t}){let{selectedCwd:r}=I_(),o=!r;return(0,X0.jsx)(Ve,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:(0,X0.jsx)($F,{disabled:o,onSelect:(i,n)=>zF(i,r,t,()=>{},n),children:(0,X0.jsx)(Y0,{disabled:o,onSubmit:i=>e(i,r)})})})}var Rn=b(C(),1),uie={minHeight:48},pie={width:240,ml:2};function WF({socket:e,selection:t}){return(0,Rn.jsxs)(Bh,{variant:"dense",sx:uie,children:[(0,Rn.jsx)(TF,{}),(0,Rn.jsx)(X,{sx:pie,children:(0,Rn.jsx)(IF,{repos:t.repos,selected:t.selectedCwd,onSelect:t.setSelectedCwd})}),(0,Rn.jsx)(xF,{cwd:t.selectedCwd}),(0,Rn.jsxs)(X,{sx:{display:"flex",ml:1,mr:2},children:[(0,Rn.jsx)(PF,{cwd:t.selectedCwd}),(0,Rn.jsx)(kF,{cwd:t.selectedCwd})]}),(0,Rn.jsx)(jF,{onCreate:e.createSession,onCreateAssist:e.createAssistSession})]})}var lu=b(N(),1);function VF(e,t){let r=new Set,o=[];for(let i of t)i.cwd&&!r.has(i.cwd)&&(r.add(i.cwd),o.push(i.cwd));return e&&!r.has(e)&&o.unshift(e),o}function qF(e,t){let[r,o]=(0,lu.useState)(e);(0,lu.useEffect)(()=>{e&&!r&&o(e)},[e,r]);let i=(0,lu.useMemo)(()=>VF(e,t),[e,t]);return(0,lu.useMemo)(()=>({repos:i,selectedCwd:r,setSelectedCwd:o}),[i,r])}var Py=b(N(),1);var Ji=b(N(),1);function KF(e){return(t,r)=>e({type:"create",prompt:t||void 0,cwd:r})}function GF(e){return(t,r)=>e({type:"create-assist",assistArgs:t,cwd:r})}function YF(e){return(t,r,o)=>e({type:"resume",sessionId:t,cwd:r,name:o})}function XF(e,t){return r=>{t.delete(r),e({type:"retry",sessionId:r})}}function ZF(e,t,r){return o=>{e({type:"dismiss",sessionId:o}),t.delete(o),r.delete(o)}}function QF(e){return(t,r)=>e({type:"set-autorun",sessionId:t,enabled:r})}function JF(e){return(t,r)=>e({type:"set-autoadvance",sessionId:t,enabled:r})}function eH(e){return(t,r)=>e({type:"input",sessionId:t,data:r})}function tH(e){return(t,r,o)=>e({type:"resize",sessionId:t,cols:r,rows:o})}function rH(e,t){return(r,o)=>{let i=e.get(r);return i&&o(i),t.set(r,o),()=>t.delete(r)}}function oH(e,t,r){let o={createSession:(0,Ji.useMemo)(()=>KF(e),[e]),createAssistSession:(0,Ji.useMemo)(()=>GF(e),[e]),resumeSession:(0,Ji.useMemo)(()=>YF(e),[e]),sendInput:(0,Ji.useMemo)(()=>eH(e),[e]),sendResize:(0,Ji.useMemo)(()=>tH(e),[e]),setAutoRun:(0,Ji.useMemo)(()=>QF(e),[e]),setAutoAdvance:(0,Ji.useMemo)(()=>JF(e),[e])},i=(0,Ji.useMemo)(()=>rH(t.current,r.current),[t,r]),n=(0,Ji.useCallback)(a=>{XF(e,t.current)(a)},[e,t]),s=(0,Ji.useCallback)(a=>{ZF(e,t.current,r.current)(a)},[e,t,r]);return{...o,onOutput:i,retrySession:n,dismissSession:s}}var Go=b(N(),1);var nH=b(N(),1);function iH(e,t){return t===null?e[0]?.id??null:e.some(r=>r.id===t)?t:e[0]?.id??null}function sH(e,t){(0,nH.useEffect)(()=>{t(r=>iH(e,r))},[e,t])}var cu=b(N(),1);function aH(e,t){if(!t.some(o=>e.has(o)))return e;let r=new Set(e);for(let o of t)r.delete(o);return r}function lH(e,t){let r=[];for(let o of t){let i=e.get(o.id);i!==void 0&&i!==o.startedAt&&r.push(o.id)}return r}function cH(){let[e,t]=(0,cu.useState)(new Set),r=(0,cu.useRef)(new Map),o=(0,cu.useCallback)(n=>{t(s=>s.has(n)?s:new Set(s).add(n))},[]),i=(0,cu.useCallback)(n=>{let s=lH(r.current,n);r.current=new Map(n.map(a=>[a.id,a.startedAt])),s.length&&t(a=>aH(a,s))},[]);return{initialized:e,markInitialized:o,syncSessions:i}}var af=b(N(),1);function uH(e,t){switch(e.type){case"sessions":t.setSessions(e.sessions),e.cwd&&t.setCurrentCwd(e.cwd);break;case"created":t.setViewingTranscriptSessionId(null),t.setActiveId(e.sessionId);break;case"history":t.setHistory(e.sessions);break;case"transcript":t.setTranscript({sessionId:e.sessionId,messages:e.messages});break;case"error":t.setError(e.message);break;case"clear":die(e,t);break;case"output":fie(e,t);break}}function die(e,t){let r=e.sessionId;t.buffers.current?.delete(r),t.handlers.current?.get(r)?.("\x1Bc")}function fie(e,t){let r=e.sessionId,o=t.buffers.current?.get(r)??"";t.buffers.current?.set(r,o+e.data),t.handlers.current?.get(r)?.(e.data),t.markInitialized(r)}function pH(e,t={}){let r=location.protocol==="https:"?"wss:":"ws:",o=new WebSocket(`${r}//${location.host}/ws`);return o.onopen=()=>{t.onOpen?.(),o.send(JSON.stringify({type:"history"}))},o.onmessage=i=>{uH(JSON.parse(i.data),e)},o.onclose=()=>t.onClose?.(),o}function dH(e,t,r){let o=!1,i,n=0,s=!1,a=()=>{o||t(pH(e,{onOpen:()=>{s&&r(),s=!1,n=0},onClose:()=>{if(o)return;s=!0;let l=Math.min(300*2**n,2e3);n+=1,i=setTimeout(a,l)}}))};return a(),()=>{o=!0,i&&clearTimeout(i)}}function fH(e){let t=(0,af.useRef)(null),{handleSessions:r,markInitialized:o,buffers:i,handlers:n}=e;(0,af.useEffect)(()=>{let a=()=>{i.current?.clear();let c=n.current;if(c)for(let u of c.values())u("\x1Bc")},l=dH({...e,setSessions:r},c=>{t.current=c},a);return()=>{l(),t.current?.close()}},[r,o,i,n]);let s=(0,af.useCallback)(()=>{let a=t.current;a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify({type:"history"}))},[]);return{wsRef:t,requestHistory:s}}function hH(){let[e,t]=(0,Go.useState)([]),[r,o]=(0,Go.useState)([]),[i,n]=(0,Go.useState)(null),[s,a]=(0,Go.useState)(null),[l,c]=(0,Go.useState)(null),[u,p]=(0,Go.useState)(""),[f,d]=(0,Go.useState)(null),{initialized:h,markInitialized:y,syncSessions:_}=cH(),m=(0,Go.useRef)(new Map),g=(0,Go.useRef)(new Map),v=(0,Go.useCallback)(R=>{_(R),t(R)},[_]),{wsRef:S,requestHistory:T}=fH({handleSessions:v,setHistory:o,setActiveId:n,setTranscript:a,setViewingTranscriptSessionId:c,setCurrentCwd:p,setError:d,markInitialized:y,buffers:m,handlers:g});sH(e,n);let w=(0,Go.useCallback)(()=>d(null),[]);return{sessions:e,history:r,activeId:i,setActiveId:n,transcript:s,viewingTranscriptSessionId:l,setViewingTranscriptSessionId:c,currentCwd:u,error:f,clearError:w,initialized:h,wsRef:S,buffers:m,handlers:g,requestHistory:T}}function mH(){let{sessions:e,history:t,activeId:r,setActiveId:o,transcript:i,viewingTranscriptSessionId:n,setViewingTranscriptSessionId:s,currentCwd:a,error:l,clearError:c,initialized:u,wsRef:p,buffers:f,handlers:d,requestHistory:h}=hH(),y=(0,Py.useCallback)(S=>{let T=p.current;T?.readyState===WebSocket.OPEN&&T.send(JSON.stringify(S))},[p]),_=oH(y,f,d),m=(0,Py.useCallback)(S=>{s(S),y({type:"fetch-transcript",sessionId:S})},[y,s]),g=(0,Py.useCallback)(()=>{s(null)},[s]),v=(0,Py.useCallback)(S=>{s(null),o(S)},[o,s]);return{sessions:e,history:t,activeId:r,setActiveId:o,selectSession:v,transcript:i,viewingTranscriptSessionId:n,viewTranscript:m,clearTranscript:g,currentCwd:a,error:l,clearError:c,initialized:u,..._,requestHistory:h}}var gH=b(N(),1);function yH(e,t,r){if(!e)return;let o=t.find(n=>n.id===e);return o?o.cwd:r.find(n=>n.sessionId===e)?.cwd}function vH(e,t,r,o){let i=yH(e,t,r);(0,gH.useEffect)(()=>{i&&o(i)},[i,o])}var da=b(C(),1),hie={zIndex:e=>e.zIndex.drawer+1},mie={minHeight:48};function _H(){let e=mH(),t=qF(e.currentCwd,e.history);vH(e.activeId,e.sessions,e.history,t.setSelectedCwd);let r=(0,bH.useMemo)(()=>({launchAssist:e.createAssistSession}),[e.createAssistSession]);return(0,da.jsx)(SC.Provider,{value:t,children:(0,da.jsxs)(IC.Provider,{value:r,children:[(0,da.jsx)(gx,{position:"fixed",elevation:1,sx:hie,children:(0,da.jsx)(WF,{socket:e,selection:t})}),(0,da.jsx)(Bh,{variant:"dense",sx:mie}),(0,da.jsx)(bF,{socket:e}),(0,da.jsx)(qd,{error:e.error,onClose:e.clearError})]})})}var SH=b(C(),1),xH=fe((0,SH.jsx)("path",{d:"M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12zM12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6c3.31 0 6 2.69 6 6s-2.69 6-6 6"}),"Brightness4");var TH=b(C(),1),wH=fe((0,TH.jsx)("path",{d:"M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6m0-10c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4"}),"Brightness7");var Z0=b(C(),1);function CH({mode:e,toggle:t}){return(0,Z0.jsx)(Kt,{onClick:t,size:"small",sx:{position:"fixed",top:8,right:16,zIndex:r=>r.zIndex.drawer+2,color:"inherit"},"aria-label":"Toggle light/dark mode",children:e==="dark"?(0,Z0.jsx)(wH,{fontSize:"small"}):(0,Z0.jsx)(xH,{fontSize:"small"})})}var PH=b(N(),1);function RH(){let[e,t]=(0,PH.useState)(()=>{try{return localStorage.getItem("theme-mode")??"dark"}catch{return"dark"}});return{mode:e,toggle:()=>t(o=>{let i=o==="dark"?"light":"dark";try{localStorage.setItem("theme-mode",i)}catch{}return i})}}var Tl=b(C(),1),yie={MuiButtonBase:{styleOverrides:{root:{cursor:"pointer","&.Mui-disabled":{cursor:"default"}}}},MuiLink:{styleOverrides:{root:{cursor:"pointer"}}}};function gie(){let{mode:e,toggle:t}=RH(),r=(0,kH.useMemo)(()=>Ln({palette:{mode:e,...e==="dark"&&{background:{default:"#1e1e1e",paper:"#252526"}}},components:yie}),[e]);return(0,Tl.jsxs)(Ag,{theme:r,children:[(0,Tl.jsx)(hv,{}),(0,Tl.jsxs)(bC,{children:[(0,Tl.jsx)(CH,{mode:e,toggle:t}),(0,Tl.jsx)(_H,{})]})]})}var EH=document.getElementById("app");EH&&(0,OH.createRoot)(EH).render((0,Tl.jsx)(gie,{}));})();
238
+ `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return pP.get()},set promptLabel(e){pP.set(e)},get tooMuchOutput(){return dP.get()},set tooMuchOutput(e){dP.set(e)}}}_verifyIntegers(...e){for(ns of e)if(ns===1/0||isNaN(ns)||ns%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(ns of e)if(ns&&(ns===1/0||isNaN(ns)||ns%1!==0||ns<0))throw new Error("This API only accepts positive integers")}};function oF(e){let t=new rF({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', Consolas, monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4"}}),r=new Q4;return t.loadAddon(r),t.loadAddon(new J4((o,i)=>{window.open(i,"_blank","noopener")})),t.open(e),r.fit(),{term:t,fitAddon:r,dispose:()=>t.dispose()}}function iF(e,t,r,o){if(e.type!=="keydown"||!e.ctrlKey||e.shiftKey||e.altKey)return!0;let i=e.key.toLowerCase();return i==="c"&&t.hasSelection()?(e.preventDefault(),r.writeText(t.getSelection()),!1):i==="v"?(e.preventDefault(),r.readText().then(o),!1):!0}function nF(e,t,r,o,i){let n=oF(e);n.term.onData(c=>r(t,c)),n.term.attachCustomKeyEventHandler(c=>iF(c,n.term,navigator.clipboard,u=>n.term.paste(u)));let s=o(t,c=>n.term.write(c)),a=new ResizeObserver(()=>{n.fitAddon.fit(),i(t,n.term.cols,n.term.rows)});return a.observe(e),{handle:n,cleanup:()=>{a.disconnect(),s(),n.dispose()}}}function sF(e,t,r,o,i,n){let s=(0,Ty.useRef)(null);(0,Ty.useEffect)(()=>{let a=e.current;if(!a)return;let{handle:l,cleanup:c}=nF(a,t,o,i,n);return s.current=l,()=>{c(),s.current=null}},[e,t,i,o,n]),(0,Ty.useEffect)(()=>{let a=s.current;if(!r||!a)return;let l=setTimeout(()=>{a.fitAddon.fit(),a.term.focus(),n(t,a.term.cols,a.term.rows)},50);return()=>clearTimeout(l)},[r,t,n])}var cF=b(C(),1);function lF({sessionId:e,visible:t,onOutput:r,sendInput:o,sendResize:i}){let n=(0,aF.useRef)(null);return sF(n,e,t,o,r,i),(0,cF.jsx)(X,{ref:n,sx:{position:"absolute",inset:"0 0 0 8px",visibility:t?"visible":"hidden",pointerEvents:t?"auto":"none"}})}var su=b(C(),1);function uF({sessions:e,activeId:t,initialized:r,onOutput:o,sendInput:i,sendResize:n}){let s=t!==null&&e.some(a=>a.id===t)&&!r.has(t);return(0,su.jsxs)(X,{sx:{flex:1,position:"relative",bgcolor:"background.default"},children:[e.map(a=>(0,su.jsx)(lF,{sessionId:a.id,visible:a.id===t,onOutput:o,sendInput:i,sendResize:n},a.id)),s&&(0,su.jsx)(Z4,{}),e.length===0&&(0,su.jsx)(X,{sx:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:(0,su.jsx)(G,{variant:"body2",color:"text.disabled",children:"Create a session to get started"})})]})}var pF=b(C(),1),dF=fe((0,pF.jsx)("path",{d:"m22.7 19-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4"}),"Build");var Qi=b(C(),1);function fF({message:e}){return e.role==="tool"?(0,Qi.jsx)(Koe,{tool:e.tool,target:e.target}):(0,Qi.jsx)(Goe,{role:e.role,text:e.text})}function Koe({tool:e,target:t}){return(0,Qi.jsxs)(X,{sx:{display:"flex",alignItems:"center",gap:1,py:.5,pl:1},children:[(0,Qi.jsx)(dF,{sx:{fontSize:14,color:"text.disabled"}}),(0,Qi.jsxs)(G,{variant:"caption",sx:{color:"text.secondary",fontFamily:"monospace"},children:[(0,Qi.jsx)(X,{component:"span",sx:{color:"warning.main"},children:e}),t&&(0,Qi.jsxs)(X,{component:"span",children:[" ",t]})]})]})}function Goe({role:e,text:t}){let r=e==="user",o=r?"info.main":"success.main";return(0,Qi.jsxs)(X,{sx:{mb:1.5,pl:1.5,py:1,pr:1,borderLeft:2,borderColor:o,borderTopRightRadius:1,borderBottomRightRadius:1,bgcolor:r?"action.hover":"transparent"},children:[(0,Qi.jsx)(G,{variant:"caption",sx:{color:o,fontWeight:600,display:"block",mb:.5},children:r?"User":"Assistant"}),(0,Qi.jsx)(G,{variant:"body2",sx:{color:"text.primary",whiteSpace:"pre-wrap",overflowWrap:"anywhere",lineHeight:1.6},children:t})]})}var cs=b(C(),1);function Yoe(e){let t=new Map;return e.map(r=>{let o=r.role==="tool"?`tool:${r.tool}:${r.target}`:`${r.role}:${r.text.slice(0,40)}`,i=t.get(o)??0;return t.set(o,i+1),{...r,key:`${o}#${i}`}})}function mF({messages:e,loading:t}){return t?(0,cs.jsxs)(X,{sx:hF,children:[(0,cs.jsx)(Dr,{size:20}),(0,cs.jsx)(G,{variant:"caption",color:"text.disabled",children:"Loading transcript\u2026"})]}):e.length===0?(0,cs.jsx)(X,{sx:hF,children:(0,cs.jsx)(G,{variant:"body2",color:"text.disabled",children:"No transcript available"})}):(0,cs.jsx)(X,{sx:{position:"absolute",inset:0,overflowY:"auto",p:2},children:(0,cs.jsx)(X,{sx:{maxWidth:820,mx:"auto"},children:Yoe(e).map(r=>(0,cs.jsx)(fF,{message:r},r.key))})})}var hF={position:"absolute",inset:0,display:"flex",flexDirection:"column",gap:1.5,alignItems:"center",justifyContent:"center"};var nR=b(C(),1);function yF({sessionId:e,transcript:t}){let r=t?.sessionId===e;return(0,nR.jsx)(X,{sx:{flex:1,position:"relative",bgcolor:"background.default"},children:(0,nR.jsx)(mF,{messages:r?t?.messages??[]:[],loading:!r})})}var sR=b(C(),1);function gF({viewingTranscriptSessionId:e,transcript:t,...r}){return e!==null?(0,sR.jsx)(yF,{sessionId:e,transcript:t}):(0,sR.jsx)(uF,{...r})}var wy=b(C(),1);function vF({socket:e}){let[t,r]=(0,$0.useState)("active"),{requestHistory:o,clearTranscript:i}=e,n=(0,$0.useCallback)(s=>{s==="history"?o():i(),r(s)},[o,i]);return(0,wy.jsxs)(X,{sx:{display:"flex",width:"100%",height:"100%"},children:[(0,wy.jsx)(Y4,{socket:e,tab:t,onTabChange:n}),(0,wy.jsx)(gF,{sessions:e.sessions,activeId:e.activeId,initialized:e.initialized,onOutput:e.onOutput,sendInput:e.sendInput,sendResize:e.sendResize,viewingTranscriptSessionId:e.viewingTranscriptSessionId,transcript:e.transcript})]})}var Ko=b(C(),1);function Xoe(){return(0,Ko.jsx)(hp,{maxWidth:"md",sx:{py:3,px:2},children:(0,Ko.jsx)(i4,{})})}function bF({socket:e}){return(0,Ko.jsxs)(Hc,{children:[(0,Ko.jsx)(jo,{path:"sessions",element:(0,Ko.jsx)(X,{sx:{display:"flex",width:"100%",height:"calc(100vh - 48px)"},children:(0,Ko.jsx)(vF,{socket:e})})}),(0,Ko.jsx)(jo,{path:"backlog/*",element:(0,Ko.jsx)(Xoe,{})}),(0,Ko.jsx)(jo,{path:"news",element:(0,Ko.jsx)(l4,{})}),(0,Ko.jsx)(jo,{path:"*",element:(0,Ko.jsx)(fC,{to:"/sessions",replace:!0})})]})}var j0=b(N(),1),Zoe=5e3;function _F(e){let[t,r]=(0,j0.useState)(null);return(0,j0.useEffect)(()=>{if(!e){r(null);return}let o=!1,i=async()=>{try{let a=await(await fetch(`/api/git-status?cwd=${encodeURIComponent(e)}`)).json();o||r(a??null)}catch{o||r(null)}};i();let n=setInterval(i,Zoe);return()=>{o=!0,clearInterval(n)}},[e]),t}var us=b(C(),1),Qoe={display:"flex",alignItems:"center",gap:1,ml:2,fontFamily:"monospace",fontSize:13,cursor:"default"},Joe={maxHeight:360,overflow:"auto",fontFamily:"monospace",fontSize:12},eie={tooltip:{sx:{maxWidth:"none"}}},SF=[{key:"new",label:"New",prefix:"+",color:"success.main"},{key:"modified",label:"Modified",prefix:"~",color:"warning.main"},{key:"deleted",label:"Deleted",prefix:"-",color:"error.main"}];function tie({counts:e}){return(0,us.jsx)(X,{sx:Joe,children:SF.filter(t=>e[t.key].length>0).map(t=>(0,us.jsxs)(X,{sx:{mb:.5,"&:last-child":{mb:0}},children:[(0,us.jsxs)(X,{sx:{color:t.color,fontWeight:700},children:[t.label," (",e[t.key].length,")"]}),e[t.key].map(r=>(0,us.jsx)(X,{sx:{pl:1,whiteSpace:"nowrap"},children:r},r))]},t.key))})}function xF({cwd:e}){let t=_F(e),r=t?SF.map(o=>({...o,count:t[o.key].length})).filter(o=>o.count>0):[];return!t||r.length===0?null:(0,us.jsx)($n,{title:(0,us.jsx)(tie,{counts:t}),slotProps:eie,children:(0,us.jsx)(X,{sx:Qoe,children:r.map(o=>(0,us.jsxs)(X,{component:"span",sx:{color:o.color},children:[o.prefix,o.count]},o.key))})})}var of=b(C(),1),rie=["/sessions","/backlog","/news"];function TF(){let e=Po(),t=zr(),r=rie.findIndex(i=>e.pathname.startsWith(i)),o=i=>{e.pathname!==i&&t(i)};return(0,of.jsxs)(Lh,{value:r===-1?0:r,textColor:"inherit",indicatorColor:"secondary",children:[(0,of.jsx)(Na,{label:"Sessions",onClick:()=>o("/sessions")}),(0,of.jsx)(Na,{label:"Backlog",onClick:()=>o("/backlog")}),(0,of.jsx)(Na,{label:"News",onClick:()=>o("/news")})]})}var CF=b(N(),1);var aR=b(C(),1);function wF(e){return(0,aR.jsx)(Wu,{viewBox:"-3 -3 30 30",...e,children:(0,aR.jsx)("path",{d:"M23.15 2.587L18.21.21a1.494 1.494 0 0 0-1.705.29l-9.46 8.63-4.12-3.128a.999.999 0 0 0-1.276.057L.327 7.261A1 1 0 0 0 .326 8.74L3.899 12 .326 15.26a1 1 0 0 0 .001 1.479L1.65 17.94a.999.999 0 0 0 1.276.057l4.12-3.128 9.46 8.63a1.492 1.492 0 0 0 1.704.29l4.942-2.377A1.5 1.5 0 0 0 24 20.06V3.939a1.5 1.5 0 0 0-.85-1.352zm-5.146 14.861L10.826 12l7.178-5.448v10.896z"})})}var ps=b(C(),1),oie={color:"inherit"};function PF({cwd:e}){let[t,r]=(0,CF.useState)(null);async function o(){try{let i=await fetch(`/api/open-in-code?cwd=${encodeURIComponent(e)}`,{method:"POST"});if(!i.ok){let n=await i.json().catch(()=>null);r(n?.error??"Failed to open VS Code")}}catch{r("Failed to open VS Code")}}return(0,ps.jsxs)(ps.Fragment,{children:[(0,ps.jsx)($n,{title:"Open in VS Code",children:(0,ps.jsx)("span",{children:(0,ps.jsx)(Kt,{sx:oie,disabled:!e,onClick:o,children:(0,ps.jsx)(wF,{})})})}),(0,ps.jsx)(qd,{error:t,onClose:()=>r(null)})]})}var FKe=b(N(),1);var RF=b(C(),1),EF=fe((0,RF.jsx)("path",{d:"M12 1.27a11 11 0 00-3.48 21.46c.55.09.73-.28.73-.55v-1.84c-3.03.64-3.67-1.46-3.67-1.46-.55-1.29-1.28-1.65-1.28-1.65-.92-.65.1-.65.1-.65 1.1 0 1.73 1.1 1.73 1.1.92 1.65 2.57 1.2 3.21.92a2 2 0 01.64-1.47c-2.47-.27-5.04-1.19-5.04-5.5 0-1.1.46-2.1 1.2-2.84a3.76 3.76 0 010-2.93s.91-.28 3.11 1.1c1.8-.49 3.7-.49 5.5 0 2.1-1.38 3.02-1.1 3.02-1.1a3.76 3.76 0 010 2.93c.83.74 1.2 1.74 1.2 2.94 0 4.21-2.57 5.13-5.04 5.4.45.37.82.92.82 2.02v3.03c0 .27.1.64.73.55A11 11 0 0012 1.27"}),"GitHub");var V0=b(N(),1),W0=b(C(),1),iie={color:"inherit"};function kF({cwd:e}){let[t,r]=(0,V0.useState)(null);return(0,V0.useEffect)(()=>{if(!e){r(null);return}let o=!1;return(async()=>{try{let n=await(await fetch(`/api/github-url?cwd=${encodeURIComponent(e)}`)).json();o||r(n?.url??null)}catch{o||r(null)}})(),()=>{o=!0}},[e]),t?(0,W0.jsx)($n,{title:"Open in GitHub",children:(0,W0.jsx)(Kt,{sx:iie,onClick:()=>window.open(t,"_blank"),children:(0,W0.jsx)(EF,{})})}):null}var nf=b(N(),1);var MF=b(C(),1);function OF({inputRef:e,value:t,onChange:r,onKeyDown:o}){return(0,MF.jsx)(fo,{inputRef:e,value:t,onChange:i=>r(i.target.value),onKeyDown:o,placeholder:"Filter repos...",size:"small",fullWidth:!0,slotProps:{input:{sx:{fontSize:12}}},sx:{p:.5}})}var q0=b(N(),1);var AF=b(C(),1);function DF({cwd:e,selected:t,highlighted:r,onHover:o,onSelect:i}){let n=(0,q0.useRef)(null);return(0,q0.useEffect)(()=>{r&&n.current?.scrollIntoView({block:"nearest"})},[r]),(0,AF.jsx)(Da,{ref:n,selected:t,title:e,onClick:i,onMouseEnter:o,sx:{fontSize:12,...r&&{bgcolor:"action.hover"}},children:K0(e)})}var lR=b(C(),1);function BF({repos:e,selected:t,highlight:r,onHighlight:o,onSelect:i}){return(0,lR.jsx)(mc,{dense:!0,children:e.map((n,s)=>(0,lR.jsx)(DF,{cwd:n,selected:n===t,highlighted:s===r,onHover:()=>o(s),onSelect:()=>i(n)},n))})}var G0=b(N(),1);function NF(e,t,r,o){let[i,n]=(0,G0.useState)(0);return(0,G0.useEffect)(()=>{n(0)},[t]),{highlight:i,setHighlight:n,onKeyDown:a=>{let l=e.length;if(a.key==="ArrowDown")a.preventDefault(),l>0&&n(c=>(c+1)%l);else if(a.key==="ArrowUp")a.preventDefault(),l>0&&n(c=>(c-1+l)%l);else if(a.key==="Enter"){a.preventDefault();let c=e[i];c&&(r(c),o())}else a.key==="Escape"&&(a.preventDefault(),o())}}}var Cy=b(C(),1);function K0(e){let t=e.includes("\\")?"\\":"/";return e.split(t).filter(Boolean).pop()??e}var nie={...Kd};function LF({repos:e,selected:t,onSelect:r,close:o}){let[i,n]=(0,nf.useState)(""),s=(0,nf.useRef)(null);(0,nf.useEffect)(()=>{s.current?.focus()},[]);let a=i.trim().toLowerCase(),l=a?e.filter(d=>d.toLowerCase().includes(a)):e,{highlight:c,setHighlight:u,onKeyDown:p}=NF(l,a,r,o);return(0,Cy.jsxs)(vt,{elevation:4,sx:nie,children:[(0,Cy.jsx)(OF,{inputRef:s,value:i,onChange:n,onKeyDown:p}),(0,Cy.jsx)(BF,{repos:l,selected:t,highlight:c,onHighlight:u,onSelect:d=>{r(d),o()}})]})}var cR=b(C(),1);function IF({repos:e,selected:t,onSelect:r}){return(0,cR.jsx)(Gd,{label:t?K0(t):"Select repo...",children:o=>(0,cR.jsx)(LF,{repos:e,selected:t,onSelect:r,close:o})})}var uR={"assist-draft":{label:"draft",args:["draft","--once"],prompt:!0,nav:!0},"assist-bug":{label:"bug",args:["bug","--once"],prompt:!0,nav:!0},"assist-next":{label:"next",args:["next","--once"],prompt:!1,nav:!0},"assist-refine":{label:"refine",args:["refine","--once"],prompt:!0,nav:!1}};function sie(e){return e in uR}function aie(e,t){let r=[...uR[e].args],o=t?.trim();return o&&r.push(o),r}function zF(e,t,r,o,i){if(sie(e)&&t){r(aie(e,i),t);return}o(e)}var pR=Object.entries(uR).map(([e,{label:t,prompt:r,nav:o}])=>({value:e,label:t,prompt:r,nav:o})),FF="Enter prompt...";var UF=b(N(),1);var sf=b(C(),1);function lie(e,t){e.key==="Enter"&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),t.trim()!==""&&e.currentTarget.closest("form")?.requestSubmit())}function HF({value:e,onChange:t,onSubmit:r}){return(0,sf.jsx)(vt,{elevation:4,sx:{...Kd,left:"auto",width:320},children:(0,sf.jsxs)(Ve,{component:"form",direction:"row",spacing:1,sx:{p:1,alignItems:"flex-start"},onSubmit:o=>{o.preventDefault(),r()},children:[(0,sf.jsx)(fo,{value:e,onChange:o=>t(o.target.value),onKeyDown:o=>lie(o,e),placeholder:FF,size:"small",autoFocus:!0,fullWidth:!0,multiline:!0,maxRows:7,slotProps:{input:{sx:{fontSize:13}}}}),(0,sf.jsx)(Le,{type:"submit",variant:"contained",size:"small",sx:{whiteSpace:"nowrap"},children:"Start"})]})})}var dR=b(C(),1);function Y0({disabled:e,onSubmit:t,label:r="prompt",allowEmpty:o=!1}){let[i,n]=(0,UF.useState)("");return(0,dR.jsx)(Gd,{label:r,disabled:e,children:s=>(0,dR.jsx)(HF,{value:i,onChange:n,onSubmit:()=>{!o&&!i.trim()||(t(i),n(""),s())}})})}var au=b(C(),1),cie={textTransform:"none",fontSize:11,fontWeight:600};function $F({onSelect:e,disabled:t=!1,children:r}){return(0,au.jsxs)(au.Fragment,{children:[pR.filter(o=>o.nav&&o.prompt).map(o=>(0,au.jsx)(Y0,{label:o.label,allowEmpty:!0,disabled:t,onSubmit:i=>e(o.value,i)},o.value)),r,pR.filter(o=>o.nav&&!o.prompt).map(o=>(0,au.jsx)(Le,{size:"small",variant:"outlined",disabled:t,onClick:()=>e(o.value),sx:cie,children:o.label},o.value))]})}var X0=b(C(),1);function jF({onCreate:e,onCreateAssist:t}){let{selectedCwd:r}=I_(),o=!r;return(0,X0.jsx)(Ve,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:(0,X0.jsx)($F,{disabled:o,onSelect:(i,n)=>zF(i,r,t,()=>{},n),children:(0,X0.jsx)(Y0,{allowEmpty:!0,disabled:o,onSubmit:i=>e(i,r)})})})}var Rn=b(C(),1),uie={minHeight:48},pie={width:240,ml:2};function WF({socket:e,selection:t}){return(0,Rn.jsxs)(Bh,{variant:"dense",sx:uie,children:[(0,Rn.jsx)(TF,{}),(0,Rn.jsx)(X,{sx:pie,children:(0,Rn.jsx)(IF,{repos:t.repos,selected:t.selectedCwd,onSelect:t.setSelectedCwd})}),(0,Rn.jsx)(xF,{cwd:t.selectedCwd}),(0,Rn.jsxs)(X,{sx:{display:"flex",ml:1,mr:2},children:[(0,Rn.jsx)(PF,{cwd:t.selectedCwd}),(0,Rn.jsx)(kF,{cwd:t.selectedCwd})]}),(0,Rn.jsx)(jF,{onCreate:e.createSession,onCreateAssist:e.createAssistSession})]})}var lu=b(N(),1);function VF(e,t){let r=new Set,o=[];for(let i of t)i.cwd&&!r.has(i.cwd)&&(r.add(i.cwd),o.push(i.cwd));return e&&!r.has(e)&&o.unshift(e),o}function qF(e,t){let[r,o]=(0,lu.useState)(e);(0,lu.useEffect)(()=>{e&&!r&&o(e)},[e,r]);let i=(0,lu.useMemo)(()=>VF(e,t),[e,t]);return(0,lu.useMemo)(()=>({repos:i,selectedCwd:r,setSelectedCwd:o}),[i,r])}var Py=b(N(),1);var Ji=b(N(),1);function KF(e){return(t,r)=>e({type:"create",prompt:t||void 0,cwd:r})}function GF(e){return(t,r)=>e({type:"create-assist",assistArgs:t,cwd:r})}function YF(e){return(t,r,o)=>e({type:"resume",sessionId:t,cwd:r,name:o})}function XF(e,t){return r=>{t.delete(r),e({type:"retry",sessionId:r})}}function ZF(e,t,r){return o=>{e({type:"dismiss",sessionId:o}),t.delete(o),r.delete(o)}}function QF(e){return(t,r)=>e({type:"set-autorun",sessionId:t,enabled:r})}function JF(e){return(t,r)=>e({type:"set-autoadvance",sessionId:t,enabled:r})}function eH(e){return(t,r)=>e({type:"input",sessionId:t,data:r})}function tH(e){return(t,r,o)=>e({type:"resize",sessionId:t,cols:r,rows:o})}function rH(e,t){return(r,o)=>{let i=e.get(r);return i&&o(i),t.set(r,o),()=>t.delete(r)}}function oH(e,t,r){let o={createSession:(0,Ji.useMemo)(()=>KF(e),[e]),createAssistSession:(0,Ji.useMemo)(()=>GF(e),[e]),resumeSession:(0,Ji.useMemo)(()=>YF(e),[e]),sendInput:(0,Ji.useMemo)(()=>eH(e),[e]),sendResize:(0,Ji.useMemo)(()=>tH(e),[e]),setAutoRun:(0,Ji.useMemo)(()=>QF(e),[e]),setAutoAdvance:(0,Ji.useMemo)(()=>JF(e),[e])},i=(0,Ji.useMemo)(()=>rH(t.current,r.current),[t,r]),n=(0,Ji.useCallback)(a=>{XF(e,t.current)(a)},[e,t]),s=(0,Ji.useCallback)(a=>{ZF(e,t.current,r.current)(a)},[e,t,r]);return{...o,onOutput:i,retrySession:n,dismissSession:s}}var Go=b(N(),1);var nH=b(N(),1);function iH(e,t){return t===null?e[0]?.id??null:e.some(r=>r.id===t)?t:e[0]?.id??null}function sH(e,t){(0,nH.useEffect)(()=>{t(r=>iH(e,r))},[e,t])}var cu=b(N(),1);function aH(e,t){if(!t.some(o=>e.has(o)))return e;let r=new Set(e);for(let o of t)r.delete(o);return r}function lH(e,t){let r=[];for(let o of t){let i=e.get(o.id);i!==void 0&&i!==o.startedAt&&r.push(o.id)}return r}function cH(){let[e,t]=(0,cu.useState)(new Set),r=(0,cu.useRef)(new Map),o=(0,cu.useCallback)(n=>{t(s=>s.has(n)?s:new Set(s).add(n))},[]),i=(0,cu.useCallback)(n=>{let s=lH(r.current,n);r.current=new Map(n.map(a=>[a.id,a.startedAt])),s.length&&t(a=>aH(a,s))},[]);return{initialized:e,markInitialized:o,syncSessions:i}}var af=b(N(),1);function uH(e,t){switch(e.type){case"sessions":t.setSessions(e.sessions),e.cwd&&t.setCurrentCwd(e.cwd);break;case"created":t.setViewingTranscriptSessionId(null),t.setActiveId(e.sessionId);break;case"history":t.setHistory(e.sessions);break;case"transcript":t.setTranscript({sessionId:e.sessionId,messages:e.messages});break;case"error":t.setError(e.message);break;case"clear":die(e,t);break;case"output":fie(e,t);break}}function die(e,t){let r=e.sessionId;t.buffers.current?.delete(r),t.handlers.current?.get(r)?.("\x1Bc")}function fie(e,t){let r=e.sessionId,o=t.buffers.current?.get(r)??"";t.buffers.current?.set(r,o+e.data),t.handlers.current?.get(r)?.(e.data),t.markInitialized(r)}function pH(e,t={}){let r=location.protocol==="https:"?"wss:":"ws:",o=new WebSocket(`${r}//${location.host}/ws`);return o.onopen=()=>{t.onOpen?.(),o.send(JSON.stringify({type:"history"}))},o.onmessage=i=>{uH(JSON.parse(i.data),e)},o.onclose=()=>t.onClose?.(),o}function dH(e,t,r){let o=!1,i,n=0,s=!1,a=()=>{o||t(pH(e,{onOpen:()=>{s&&r(),s=!1,n=0},onClose:()=>{if(o)return;s=!0;let l=Math.min(300*2**n,2e3);n+=1,i=setTimeout(a,l)}}))};return a(),()=>{o=!0,i&&clearTimeout(i)}}function fH(e){let t=(0,af.useRef)(null),{handleSessions:r,markInitialized:o,buffers:i,handlers:n}=e;(0,af.useEffect)(()=>{let a=()=>{i.current?.clear();let c=n.current;if(c)for(let u of c.values())u("\x1Bc")},l=dH({...e,setSessions:r},c=>{t.current=c},a);return()=>{l(),t.current?.close()}},[r,o,i,n]);let s=(0,af.useCallback)(()=>{let a=t.current;a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify({type:"history"}))},[]);return{wsRef:t,requestHistory:s}}function hH(){let[e,t]=(0,Go.useState)([]),[r,o]=(0,Go.useState)([]),[i,n]=(0,Go.useState)(null),[s,a]=(0,Go.useState)(null),[l,c]=(0,Go.useState)(null),[u,p]=(0,Go.useState)(""),[f,d]=(0,Go.useState)(null),{initialized:h,markInitialized:y,syncSessions:_}=cH(),m=(0,Go.useRef)(new Map),g=(0,Go.useRef)(new Map),v=(0,Go.useCallback)(R=>{_(R),t(R)},[_]),{wsRef:S,requestHistory:T}=fH({handleSessions:v,setHistory:o,setActiveId:n,setTranscript:a,setViewingTranscriptSessionId:c,setCurrentCwd:p,setError:d,markInitialized:y,buffers:m,handlers:g});sH(e,n);let w=(0,Go.useCallback)(()=>d(null),[]);return{sessions:e,history:r,activeId:i,setActiveId:n,transcript:s,viewingTranscriptSessionId:l,setViewingTranscriptSessionId:c,currentCwd:u,error:f,clearError:w,initialized:h,wsRef:S,buffers:m,handlers:g,requestHistory:T}}function mH(){let{sessions:e,history:t,activeId:r,setActiveId:o,transcript:i,viewingTranscriptSessionId:n,setViewingTranscriptSessionId:s,currentCwd:a,error:l,clearError:c,initialized:u,wsRef:p,buffers:f,handlers:d,requestHistory:h}=hH(),y=(0,Py.useCallback)(S=>{let T=p.current;T?.readyState===WebSocket.OPEN&&T.send(JSON.stringify(S))},[p]),_=oH(y,f,d),m=(0,Py.useCallback)(S=>{s(S),y({type:"fetch-transcript",sessionId:S})},[y,s]),g=(0,Py.useCallback)(()=>{s(null)},[s]),v=(0,Py.useCallback)(S=>{s(null),o(S)},[o,s]);return{sessions:e,history:t,activeId:r,setActiveId:o,selectSession:v,transcript:i,viewingTranscriptSessionId:n,viewTranscript:m,clearTranscript:g,currentCwd:a,error:l,clearError:c,initialized:u,..._,requestHistory:h}}var gH=b(N(),1);function yH(e,t,r){if(!e)return;let o=t.find(n=>n.id===e);return o?o.cwd:r.find(n=>n.sessionId===e)?.cwd}function vH(e,t,r,o){let i=yH(e,t,r);(0,gH.useEffect)(()=>{i&&o(i)},[i,o])}var da=b(C(),1),hie={zIndex:e=>e.zIndex.drawer+1},mie={minHeight:48};function _H(){let e=mH(),t=qF(e.currentCwd,e.history);vH(e.activeId,e.sessions,e.history,t.setSelectedCwd);let r=(0,bH.useMemo)(()=>({launchAssist:e.createAssistSession}),[e.createAssistSession]);return(0,da.jsx)(SC.Provider,{value:t,children:(0,da.jsxs)(IC.Provider,{value:r,children:[(0,da.jsx)(gx,{position:"fixed",elevation:1,sx:hie,children:(0,da.jsx)(WF,{socket:e,selection:t})}),(0,da.jsx)(Bh,{variant:"dense",sx:mie}),(0,da.jsx)(bF,{socket:e}),(0,da.jsx)(qd,{error:e.error,onClose:e.clearError})]})})}var SH=b(C(),1),xH=fe((0,SH.jsx)("path",{d:"M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12zM12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6c3.31 0 6 2.69 6 6s-2.69 6-6 6"}),"Brightness4");var TH=b(C(),1),wH=fe((0,TH.jsx)("path",{d:"M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6m0-10c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4"}),"Brightness7");var Z0=b(C(),1);function CH({mode:e,toggle:t}){return(0,Z0.jsx)(Kt,{onClick:t,size:"small",sx:{position:"fixed",top:8,right:16,zIndex:r=>r.zIndex.drawer+2,color:"inherit"},"aria-label":"Toggle light/dark mode",children:e==="dark"?(0,Z0.jsx)(wH,{fontSize:"small"}):(0,Z0.jsx)(xH,{fontSize:"small"})})}var PH=b(N(),1);function RH(){let[e,t]=(0,PH.useState)(()=>{try{return localStorage.getItem("theme-mode")??"dark"}catch{return"dark"}});return{mode:e,toggle:()=>t(o=>{let i=o==="dark"?"light":"dark";try{localStorage.setItem("theme-mode",i)}catch{}return i})}}var Tl=b(C(),1),yie={MuiButtonBase:{styleOverrides:{root:{cursor:"pointer","&.Mui-disabled":{cursor:"default"}}}},MuiLink:{styleOverrides:{root:{cursor:"pointer"}}}};function gie(){let{mode:e,toggle:t}=RH(),r=(0,kH.useMemo)(()=>Ln({palette:{mode:e,...e==="dark"&&{background:{default:"#1e1e1e",paper:"#252526"}}},components:yie}),[e]);return(0,Tl.jsxs)(Ag,{theme:r,children:[(0,Tl.jsx)(hv,{}),(0,Tl.jsxs)(bC,{children:[(0,Tl.jsx)(CH,{mode:e,toggle:t}),(0,Tl.jsx)(_H,{})]})]})}var EH=document.getElementById("app");EH&&(0,OH.createRoot)(EH).render((0,Tl.jsx)(gie,{}));})();
239
239
  /*! Bundled license information:
240
240
 
241
241
  react/cjs/react.production.js:
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import { Command } from "commander";
6
6
  // package.json
7
7
  var package_default = {
8
8
  name: "@staff0rd/assist",
9
- version: "0.284.0",
9
+ version: "0.285.0",
10
10
  type: "module",
11
11
  main: "dist/index.js",
12
12
  bin: {
@@ -275,6 +275,14 @@ var assistConfigSchema = z2.strictObject({
275
275
  screenshot: z2.strictObject({
276
276
  outputDir: z2.string().default("./screenshots")
277
277
  }).default({ outputDir: "./screenshots" }),
278
+ sessions: z2.strictObject({
279
+ // why: Windows .claude/projects root as seen from WSL (e.g. /mnt/c/Users/<user>/.claude/projects); when set its transcripts are discovered and tagged windows-origin
280
+ windowsProjectsRoot: z2.string().optional(),
281
+ // why: host the WSL daemon dials to reach the native Windows daemon over TCP (WSL can't use the Windows named pipe); defaults to 127.0.0.1 (WSL2 mirrored networking). NAT-mode users set the Windows host IP.
282
+ windowsDaemonHost: z2.string().optional(),
283
+ // why: TCP port the native Windows daemon listens on for the WSL bridge; defaults to 51764
284
+ windowsDaemonPort: z2.number().optional()
285
+ }).optional(),
278
286
  backlog: z2.strictObject({
279
287
  databaseUrl: z2.string().optional()
280
288
  }).default({}),
@@ -12069,10 +12077,10 @@ async function getAccessToken(apiKey) {
12069
12077
  }
12070
12078
  });
12071
12079
  if (!response.ok) {
12072
- const errorText = await response.text();
12080
+ const errorText2 = await response.text();
12073
12081
  throw new Error(
12074
12082
  `Failed to get access token: ${response.status} ${response.statusText}
12075
- ${errorText}`
12083
+ ${errorText2}`
12076
12084
  );
12077
12085
  }
12078
12086
  const tokenData = await response.json();
@@ -18100,11 +18108,11 @@ function toSessionInfo({
18100
18108
  }
18101
18109
 
18102
18110
  // src/commands/sessions/daemon/broadcastSessions.ts
18103
- function broadcastSessions(sessions, clients) {
18111
+ function broadcastSessions(sessions, clients, windowsSessions = []) {
18104
18112
  persistLiveSessions(sessions);
18105
18113
  broadcast(clients, {
18106
18114
  type: "sessions",
18107
- sessions: [...sessions.values()].map(toSessionInfo)
18115
+ sessions: [...sessions.values()].map(toSessionInfo).concat(windowsSessions)
18108
18116
  });
18109
18117
  }
18110
18118
 
@@ -18228,9 +18236,10 @@ function replayScrollback(sessions, client) {
18228
18236
  }
18229
18237
 
18230
18238
  // src/commands/sessions/daemon/greetClient.ts
18231
- function greetClient(client, sessions, list4) {
18239
+ function greetClient(client, sessions, list4, windowsProxy) {
18232
18240
  sendTo(client, { type: "sessions", sessions: list4() });
18233
18241
  replayScrollback(sessions, client);
18242
+ windowsProxy.replayScrollback(client);
18234
18243
  }
18235
18244
 
18236
18245
  // src/commands/sessions/daemon/shouldAutoDismiss.ts
@@ -18470,6 +18479,308 @@ function shutdownSessions(sessions) {
18470
18479
  }
18471
18480
  }
18472
18481
 
18482
+ // src/commands/sessions/daemon/connectToWindowsDaemon.ts
18483
+ import * as net2 from "net";
18484
+
18485
+ // src/commands/sessions/daemon/windowsDaemonPort.ts
18486
+ var DEFAULT_PORT = 51764;
18487
+ var DEFAULT_HOST = "127.0.0.1";
18488
+ function windowsDaemonPort() {
18489
+ return loadConfig().sessions?.windowsDaemonPort ?? DEFAULT_PORT;
18490
+ }
18491
+ function windowsDaemonHost() {
18492
+ return loadConfig().sessions?.windowsDaemonHost ?? DEFAULT_HOST;
18493
+ }
18494
+
18495
+ // src/commands/sessions/daemon/connectToWindowsDaemon.ts
18496
+ function connectToWindowsDaemon() {
18497
+ return new Promise((resolve16, reject) => {
18498
+ const socket = net2.connect(windowsDaemonPort(), windowsDaemonHost());
18499
+ socket.once("connect", () => resolve16(socket));
18500
+ socket.once("error", reject);
18501
+ });
18502
+ }
18503
+ async function isWindowsDaemonRunning() {
18504
+ try {
18505
+ (await connectToWindowsDaemon()).destroy();
18506
+ return true;
18507
+ } catch {
18508
+ return false;
18509
+ }
18510
+ }
18511
+
18512
+ // src/commands/sessions/daemon/ensureWindowsDaemonRunning.ts
18513
+ import { spawn as spawn10 } from "child_process";
18514
+ var SPAWN_TIMEOUT_MS2 = 3e4;
18515
+ var RETRY_DELAY_MS2 = 300;
18516
+ async function ensureWindowsDaemonRunning() {
18517
+ if (await isWindowsDaemonRunning()) return;
18518
+ launchWindowsDaemon();
18519
+ await waitForWindowsDaemon();
18520
+ }
18521
+ function launchWindowsDaemon() {
18522
+ const child = spawn10(
18523
+ "cmd.exe",
18524
+ ["/c", "start", "", "assist", "daemon", "run"],
18525
+ { detached: true, stdio: "ignore" }
18526
+ );
18527
+ child.on(
18528
+ "error",
18529
+ (e) => daemonLog(`failed to launch windows daemon: ${e.message}`)
18530
+ );
18531
+ child.unref();
18532
+ }
18533
+ async function waitForWindowsDaemon() {
18534
+ const deadline = Date.now() + SPAWN_TIMEOUT_MS2;
18535
+ while (Date.now() < deadline) {
18536
+ await delay2(RETRY_DELAY_MS2);
18537
+ if (await isWindowsDaemonRunning()) return;
18538
+ }
18539
+ throw new Error(
18540
+ "Windows daemon did not start; is assist installed on the Windows host?"
18541
+ );
18542
+ }
18543
+ function delay2(ms) {
18544
+ return new Promise((resolve16) => setTimeout(resolve16, ms));
18545
+ }
18546
+
18547
+ // src/commands/sessions/daemon/buildHello.ts
18548
+ var ASSIST_VERSION = package_default.version;
18549
+ function buildHello() {
18550
+ return { type: "hello", version: ASSIST_VERSION };
18551
+ }
18552
+ function isHello(msg) {
18553
+ return msg.type === "hello" && typeof msg.version === "string";
18554
+ }
18555
+ function versionsMatch(a, b) {
18556
+ return a === b;
18557
+ }
18558
+
18559
+ // src/commands/sessions/daemon/toWindowsSessionId.ts
18560
+ var PREFIX = "w-";
18561
+ function toWindowsSessionId(id) {
18562
+ return `${PREFIX}${id}`;
18563
+ }
18564
+ function isWindowsSessionId(id) {
18565
+ return id.startsWith(PREFIX);
18566
+ }
18567
+ function stripWindowsSessionId(id) {
18568
+ return id.startsWith(PREFIX) ? id.slice(PREFIX.length) : id;
18569
+ }
18570
+
18571
+ // src/commands/sessions/daemon/WindowsProxyState.ts
18572
+ var MAX_SCROLLBACK2 = 256 * 1024;
18573
+ function createState(broadcast2, onSessionsChanged) {
18574
+ return {
18575
+ windowsSessions: [],
18576
+ scrollback: /* @__PURE__ */ new Map(),
18577
+ pendingCreators: [],
18578
+ broadcast: broadcast2,
18579
+ onSessionsChanged
18580
+ };
18581
+ }
18582
+ function resetState(state) {
18583
+ state.windowsSessions = [];
18584
+ state.scrollback.clear();
18585
+ state.pendingCreators = [];
18586
+ }
18587
+ function replayScrollback2(state, client) {
18588
+ for (const [sessionId, data] of state.scrollback)
18589
+ if (data) sendTo(client, { type: "output", sessionId, data });
18590
+ }
18591
+ function appendScrollback2(state, sessionId, data) {
18592
+ const next3 = (state.scrollback.get(sessionId) ?? "") + data;
18593
+ state.scrollback.set(
18594
+ sessionId,
18595
+ next3.length > MAX_SCROLLBACK2 ? next3.slice(-MAX_SCROLLBACK2) : next3
18596
+ );
18597
+ }
18598
+
18599
+ // src/commands/sessions/daemon/handleInbound.ts
18600
+ function handleInbound(state, line) {
18601
+ let msg;
18602
+ try {
18603
+ msg = JSON.parse(line);
18604
+ } catch {
18605
+ return;
18606
+ }
18607
+ inbound[msg.type]?.(state, msg);
18608
+ }
18609
+ var inbound = {
18610
+ hello: (_state, msg) => handleHello(msg),
18611
+ created: handleCreated,
18612
+ sessions: handleSessions,
18613
+ output: handleOutput,
18614
+ clear: relayWithSessionId,
18615
+ error: (state, msg) => state.broadcast(msg)
18616
+ };
18617
+ function handleHello(msg) {
18618
+ if (isHello(msg) && !versionsMatch(msg.version, ASSIST_VERSION))
18619
+ daemonLog(
18620
+ `windows daemon version mismatch: ${msg.version} (wsl ${ASSIST_VERSION})`
18621
+ );
18622
+ }
18623
+ function handleCreated(state, msg) {
18624
+ const client = state.pendingCreators.shift();
18625
+ if (client) sendTo(client, { type: "created", sessionId: nsId(msg) });
18626
+ }
18627
+ function handleSessions(state, msg) {
18628
+ state.windowsSessions = msg.sessions.map((s) => ({
18629
+ ...s,
18630
+ id: toWindowsSessionId(s.id)
18631
+ }));
18632
+ const live = new Set(state.windowsSessions.map((s) => s.id));
18633
+ for (const id of state.scrollback.keys())
18634
+ if (!live.has(id)) state.scrollback.delete(id);
18635
+ state.onSessionsChanged();
18636
+ }
18637
+ function handleOutput(state, msg) {
18638
+ const sessionId = nsId(msg);
18639
+ const data = msg.data;
18640
+ appendScrollback2(state, sessionId, data);
18641
+ state.broadcast({ type: "output", sessionId, data });
18642
+ }
18643
+ function relayWithSessionId(state, msg) {
18644
+ state.broadcast({ ...msg, sessionId: nsId(msg) });
18645
+ }
18646
+ function nsId(msg) {
18647
+ return toWindowsSessionId(msg.sessionId);
18648
+ }
18649
+
18650
+ // src/commands/sessions/daemon/isWindowsCwd.ts
18651
+ function isWindowsCwd(cwd) {
18652
+ return /^[A-Za-z]:[\\/]/.test(cwd);
18653
+ }
18654
+ function shouldProxyToWindows(cwd) {
18655
+ return detectPlatform() === "wsl" && isWindowsCwd(cwd);
18656
+ }
18657
+
18658
+ // src/commands/sessions/daemon/WindowsConnection.ts
18659
+ import { createInterface as createInterface5 } from "readline";
18660
+ var WindowsConnection = class {
18661
+ constructor(deps2) {
18662
+ this.deps = deps2;
18663
+ }
18664
+ connection = null;
18665
+ socket = null;
18666
+ ensure() {
18667
+ if (this.connection) return this.connection;
18668
+ const connection = this.open();
18669
+ this.connection = connection;
18670
+ connection.catch(() => {
18671
+ if (this.connection === connection) this.connection = null;
18672
+ });
18673
+ return connection;
18674
+ }
18675
+ write(msg) {
18676
+ this.socket?.write(`${JSON.stringify(msg)}
18677
+ `);
18678
+ }
18679
+ trySend(msg) {
18680
+ if (!this.socket?.writable) return false;
18681
+ this.write(msg);
18682
+ return true;
18683
+ }
18684
+ dispose() {
18685
+ this.socket?.destroy();
18686
+ this.reset();
18687
+ }
18688
+ async open() {
18689
+ const socket = await this.deps.connect();
18690
+ this.socket = socket;
18691
+ const lines = createInterface5({ input: socket });
18692
+ lines.on("error", () => {
18693
+ });
18694
+ lines.on("line", (line) => this.deps.onLine(line));
18695
+ socket.on("error", () => {
18696
+ });
18697
+ socket.on("close", () => {
18698
+ this.reset();
18699
+ this.deps.onClose();
18700
+ });
18701
+ this.write(buildHello());
18702
+ return socket;
18703
+ }
18704
+ reset() {
18705
+ this.socket = null;
18706
+ this.connection = null;
18707
+ }
18708
+ };
18709
+
18710
+ // src/commands/sessions/daemon/WindowsProxy.ts
18711
+ var WindowsProxy = class {
18712
+ state;
18713
+ conn;
18714
+ constructor(clients, onSessionsChanged, connect3 = defaultConnect) {
18715
+ this.state = createState(
18716
+ (msg) => broadcast(clients, msg),
18717
+ onSessionsChanged
18718
+ );
18719
+ this.conn = new WindowsConnection({
18720
+ connect: connect3,
18721
+ onLine: (line) => handleInbound(this.state, line),
18722
+ onClose: () => this.handleClose()
18723
+ });
18724
+ }
18725
+ sessions() {
18726
+ return this.state.windowsSessions;
18727
+ }
18728
+ replayScrollback(client) {
18729
+ replayScrollback2(this.state, client);
18730
+ }
18731
+ // Returns true when the message targets Windows: a create/resume in a
18732
+ // windows-origin cwd is forwarded, as is I/O for a namespaced session id.
18733
+ route(client, data) {
18734
+ if (isWindowsCreate(data)) {
18735
+ void this.forwardCreate(client, data);
18736
+ return true;
18737
+ }
18738
+ if (isWindowsIo(data)) {
18739
+ const sessionId = stripWindowsSessionId(data.sessionId);
18740
+ this.conn.trySend({ ...data, sessionId });
18741
+ return true;
18742
+ }
18743
+ return false;
18744
+ }
18745
+ dispose() {
18746
+ this.conn.dispose();
18747
+ }
18748
+ async forwardCreate(client, data) {
18749
+ try {
18750
+ await this.conn.ensure();
18751
+ this.state.pendingCreators.push(client);
18752
+ this.conn.write(data);
18753
+ } catch (e) {
18754
+ sendTo(client, {
18755
+ type: "error",
18756
+ message: `Windows session unavailable: ${errorText(e)}`
18757
+ });
18758
+ }
18759
+ }
18760
+ handleClose() {
18761
+ for (const client of this.state.pendingCreators)
18762
+ sendTo(client, {
18763
+ type: "error",
18764
+ message: "Windows daemon connection closed"
18765
+ });
18766
+ resetState(this.state);
18767
+ this.state.onSessionsChanged();
18768
+ }
18769
+ };
18770
+ function isWindowsCreate(data) {
18771
+ return typeof data.cwd === "string" && shouldProxyToWindows(data.cwd);
18772
+ }
18773
+ function isWindowsIo(data) {
18774
+ return typeof data.sessionId === "string" && isWindowsSessionId(data.sessionId);
18775
+ }
18776
+ async function defaultConnect() {
18777
+ await ensureWindowsDaemonRunning();
18778
+ return connectToWindowsDaemon();
18779
+ }
18780
+ function errorText(e) {
18781
+ return e instanceof Error ? e.message : String(e);
18782
+ }
18783
+
18473
18784
  // src/commands/sessions/daemon/watchClaudeSessionId.ts
18474
18785
  import * as fs27 from "fs";
18475
18786
  import * as path48 from "path";
@@ -18753,10 +19064,12 @@ var SessionManager = class {
18753
19064
  clients = /* @__PURE__ */ new Set();
18754
19065
  nextId = 1;
18755
19066
  shuttingDown = false;
19067
+ // why: dispatch calls windowsProxy.route() to forward windows-origin sessions
19068
+ windowsProxy = new WindowsProxy(this.clients, () => this.notify());
18756
19069
  addClient(client) {
18757
19070
  this.clients.add(client);
18758
19071
  this.onIdleChange?.(this.isIdle());
18759
- greetClient(client, this.sessions, () => this.listSessions());
19072
+ greetClient(client, this.sessions, this.listSessions, this.windowsProxy);
18760
19073
  }
18761
19074
  removeClient(client) {
18762
19075
  this.clients.delete(client);
@@ -18825,22 +19138,24 @@ var SessionManager = class {
18825
19138
  setAutoAdvance(id, enabled) {
18826
19139
  if (setAutoAdvance(this.sessions, id, enabled)) this.notify();
18827
19140
  }
18828
- listSessions() {
18829
- return [...this.sessions.values()].map(toSessionInfo);
18830
- }
19141
+ listSessions = () => {
19142
+ const local = [...this.sessions.values()].map(toSessionInfo);
19143
+ return local.concat(this.windowsProxy.sessions());
19144
+ };
18831
19145
  notify = () => {
18832
19146
  if (this.shuttingDown) return;
18833
- broadcastSessions(this.sessions, this.clients);
19147
+ const windows = this.windowsProxy.sessions();
19148
+ broadcastSessions(this.sessions, this.clients, windows);
18834
19149
  this.onIdleChange?.(this.isIdle());
18835
19150
  };
18836
19151
  };
18837
19152
 
18838
19153
  // src/commands/sessions/daemon/startDaemonServer.ts
18839
19154
  import { unlinkSync as unlinkSync19 } from "fs";
18840
- import * as net2 from "net";
19155
+ import * as net3 from "net";
18841
19156
 
18842
19157
  // src/commands/sessions/daemon/handleConnection.ts
18843
- import { createInterface as createInterface5 } from "readline";
19158
+ import { createInterface as createInterface6 } from "readline";
18844
19159
 
18845
19160
  // src/commands/sessions/shared/parseTranscript.ts
18846
19161
  import * as fs28 from "fs";
@@ -18932,46 +19247,11 @@ function safeParse2(line) {
18932
19247
  }
18933
19248
 
18934
19249
  // src/commands/sessions/daemon/dispatchMessage.ts
18935
- function sendCreated(client, id) {
18936
- sendTo(client, { type: "created", sessionId: id });
18937
- }
18938
- function handleCreate(client, manager, data) {
18939
- sendCreated(
18940
- client,
18941
- manager.spawn(
18942
- data.prompt,
18943
- data.cwd
18944
- )
18945
- );
18946
- }
18947
- function handleCreateRun(client, manager, data) {
18948
- sendCreated(
18949
- client,
18950
- manager.spawnRun(
18951
- data.runName,
18952
- data.runArgs ?? [],
18953
- data.cwd
18954
- )
18955
- );
18956
- }
18957
- function handleCreateAssist(client, manager, data) {
18958
- sendCreated(
18959
- client,
18960
- manager.spawnAssist(
18961
- data.assistArgs ?? [],
18962
- data.cwd
18963
- )
18964
- );
18965
- }
18966
- function handleResume(client, manager, data) {
18967
- sendCreated(
18968
- client,
18969
- manager.resume(
18970
- data.sessionId,
18971
- data.cwd,
18972
- data.name
18973
- )
18974
- );
19250
+ function creator(spawn11) {
19251
+ return (client, m, d) => {
19252
+ if (m.windowsProxy.route(client, d)) return;
19253
+ sendTo(client, { type: "created", sessionId: spawn11(m, d) });
19254
+ };
18975
19255
  }
18976
19256
  function handleHistory(client) {
18977
19257
  discoverSessions().then(
@@ -18989,21 +19269,54 @@ function handleShutdown(client, manager) {
18989
19269
  sendTo(client, { type: "shutting-down" });
18990
19270
  setImmediate(() => process.exit(0));
18991
19271
  }
19272
+ function routed(local) {
19273
+ return (client, m, d) => {
19274
+ if (!m.windowsProxy.route(client, d)) local(client, m, d);
19275
+ };
19276
+ }
18992
19277
  var handlers = {
18993
19278
  ping: (client) => sendTo(client, { type: "pong", pid: process.pid }),
18994
- create: handleCreate,
18995
- "create-run": handleCreateRun,
18996
- "create-assist": handleCreateAssist,
18997
- resume: handleResume,
19279
+ hello: (client) => sendTo(client, buildHello()),
19280
+ create: creator(
19281
+ (m, d) => m.spawn(d.prompt, d.cwd)
19282
+ ),
19283
+ "create-run": creator(
19284
+ (m, d) => m.spawnRun(
19285
+ d.runName,
19286
+ d.runArgs ?? [],
19287
+ d.cwd
19288
+ )
19289
+ ),
19290
+ "create-assist": creator(
19291
+ (m, d) => m.spawnAssist(
19292
+ d.assistArgs ?? [],
19293
+ d.cwd
19294
+ )
19295
+ ),
19296
+ resume: creator(
19297
+ (m, d) => m.resume(
19298
+ d.sessionId,
19299
+ d.cwd,
19300
+ d.name
19301
+ )
19302
+ ),
18998
19303
  history: handleHistory,
18999
19304
  "fetch-transcript": handleFetchTranscript,
19000
19305
  shutdown: handleShutdown,
19001
- input: (_client, m, d) => m.writeToSession(d.sessionId, d.data),
19002
- resize: (_client, m, d) => m.resizeSession(d.sessionId, d.cols, d.rows),
19003
- retry: (_client, m, d) => m.retrySession(d.sessionId),
19004
- dismiss: (_client, m, d) => m.dismissSession(d.sessionId),
19005
- "set-autorun": (_client, m, d) => m.setAutoRun(d.sessionId, d.enabled),
19006
- "set-autoadvance": (_client, m, d) => m.setAutoAdvance(d.sessionId, d.enabled)
19306
+ input: routed(
19307
+ (_client, m, d) => m.writeToSession(d.sessionId, d.data)
19308
+ ),
19309
+ resize: routed(
19310
+ (_client, m, d) => m.resizeSession(d.sessionId, d.cols, d.rows)
19311
+ ),
19312
+ retry: routed((_client, m, d) => m.retrySession(d.sessionId)),
19313
+ dismiss: routed((_client, m, d) => m.dismissSession(d.sessionId)),
19314
+ "set-autorun": routed(
19315
+ (_client, m, d) => m.setAutoRun(d.sessionId, d.enabled)
19316
+ ),
19317
+ "set-autoadvance": routed(
19318
+ (_client, m, d) => m.setAutoAdvance(d.sessionId, d.enabled)
19319
+ )
19007
19320
  };
19008
19321
  function dispatchMessage(client, manager, data) {
19009
19322
  handlers[data.type]?.(client, manager, data);
@@ -19018,7 +19331,7 @@ function handleConnection(socket, manager) {
19018
19331
  }
19019
19332
  };
19020
19333
  manager.addClient(client);
19021
- const lines = createInterface5({ input: socket });
19334
+ const lines = createInterface6({ input: socket });
19022
19335
  lines.on("error", () => {
19023
19336
  });
19024
19337
  lines.on("line", (line) => {
@@ -19095,9 +19408,10 @@ function cleanupOwnedFiles() {
19095
19408
 
19096
19409
  // src/commands/sessions/daemon/startDaemonServer.ts
19097
19410
  function startDaemonServer(manager, checkAutoExit) {
19098
- const server = net2.createServer(
19411
+ const server = net3.createServer(
19099
19412
  (socket) => handleConnection(socket, manager)
19100
19413
  );
19414
+ if (process.platform === "win32") startWindowsBridge(manager);
19101
19415
  let retried = false;
19102
19416
  server.on("error", (e) => {
19103
19417
  if (e.code !== "EADDRINUSE" || retried) {
@@ -19109,6 +19423,17 @@ function startDaemonServer(manager, checkAutoExit) {
19109
19423
  });
19110
19424
  server.listen(daemonPaths.socket, () => onListening(manager, checkAutoExit));
19111
19425
  }
19426
+ function startWindowsBridge(manager) {
19427
+ const port = windowsDaemonPort();
19428
+ const bridge = net3.createServer(
19429
+ (socket) => handleConnection(socket, manager)
19430
+ );
19431
+ bridge.on(
19432
+ "error",
19433
+ (e) => daemonLog(`windows bridge error: ${e.message}`)
19434
+ );
19435
+ bridge.listen(port, () => daemonLog(`windows bridge listening on :${port}`));
19436
+ }
19112
19437
  async function recoverFromAddrInUse(server, manager, checkAutoExit) {
19113
19438
  if (await isDaemonRunning()) {
19114
19439
  daemonLog("another daemon owns the socket; exiting");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staff0rd/assist",
3
- "version": "0.284.0",
3
+ "version": "0.285.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "bin": {