@staff0rd/assist 0.616.2 → 0.616.3

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
@@ -139,7 +139,7 @@ Every command supports `--help` for full detail on its flags and behaviour.
139
139
  - `--announce` - Announce the PR in Slack (`/prs-slack <n> --no-confirm`) at the tail of the chain: the Address Comments session announces once every thread is processed when one was started, otherwise a `/prs-slack` session is started directly. Announces exactly once, and only inside an assist session
140
140
  - `--verbose` - Per-line log output instead of the stacked-spinner UI (automatic in CI)
141
141
  - `assist github commits <org> [--since <date>] [--top <n>] [--json]` - Report commit activity across a GitHub organisation: repos ranked by commits, top committers, and a per-repo author breakdown
142
- - `assist github issue create --title <title> --body <body> [-R <owner>/<repo>] [--type <name>] [--parent <issue>] [--project <number>] [--status <name>] [--label <name>]` - Create a GitHub issue on the current repo (or `-R`'s). There is no What/Why/How template — an issue reports a problem, and the target repo's own issue template is unknowable from here. The title and body are rejected if they reference Claude or an assist backlog item, and in a web session they are previewed for approve/reject first (with inline comments); nothing is created until it is approved. `--type` sets the native issue type after creation, `--parent` files the new issue as a sub-issue of the referenced issue (`owner/repo#number`, a github.com issue URL, or a bare number read against `--repo` or the current repo; a parent in another repository is allowed), `--project` adds the issue to the repo owner's project of that number, `--status` sets that project item's Status, and `--label` applies repo labels (repeat the flag or pass a comma-separated list). All five are resolved before the preview — including the token's `project` OAuth scope, whose remediation is `gh auth refresh -h github.com -s project` — so an unknown name, an unreadable parent, a missing scope, or `--status` without `--project` creates nothing. The preview pane names the repo, type, parent, project, status and labels above the body without adding them to the posted body. Raw `gh issue create` is denied in favour of this command
142
+ - `assist github issue create --title <title> --body <body> [-R <owner>/<repo>] [--type <name>] [--parent <issue>] [--project <number>] [--status <name>] [--label <name>]` - Create a GitHub issue on the current repo (or `-R`'s). There is no What/Why/How template — an issue reports a problem, and the target repo's own issue template is unknowable from here. The title and body are rejected if they reference Claude or an assist backlog item, and in a web session they are previewed for approve/reject first (with inline comments and pasted screenshots, as for `prs raise`, appended under `## Screenshots` on approval); nothing is created until it is approved. `--type` sets the native issue type after creation, `--parent` files the new issue as a sub-issue of the referenced issue (`owner/repo#number`, a github.com issue URL, or a bare number read against `--repo` or the current repo; a parent in another repository is allowed), `--project` adds the issue to the repo owner's project of that number, `--status` sets that project item's Status, and `--label` applies repo labels (repeat the flag or pass a comma-separated list). All five are resolved before the preview — including the token's `project` OAuth scope, whose remediation is `gh auth refresh -h github.com -s project` — so an unknown name, an unreadable parent, a missing scope, or `--status` without `--project` creates nothing. The preview pane names the repo, type, parent, project, status and labels above the body without adding them to the posted body. Raw `gh issue create` is denied in favour of this command
143
143
  - `assist github issue edit <number> [-R <owner>/<repo>] [--fresh]` - Rework an existing GitHub issue's body in the web preview pane. Fetches the issue's current `title`, `body` and `updatedAt` with `gh issue view`, writes the body to a working file under `~/.assist/github-issues/`, and previews it for approve/reject. Approving pushes the pane's markdown back with `gh issue edit --body-file`; nothing is pushed if the issue was updated on GitHub after it was fetched (the working file is named instead, so nobody else's edit is clobbered) or if the preview is rejected. Rejecting writes the pane's markdown — collapses included — to the working file and names it in the output, so the revision is made in that file rather than composed from scratch; a re-run resumes from the working file while the issue has not moved on GitHub, and `--fresh` discards it and re-fetches. Outside a web session there is no pane to edit in, so the command just prints the issue — callers never need to detect the session themselves. Only the body is touched — the title, labels, assignees and state are left alone. Raw `gh issue edit` is denied in favour of this command
144
144
  - `assist github issue comment <number> --body <body> [-R <owner>/<repo>]` - Comment on a GitHub issue on the current repo (or `-R`'s); a body of `-` reads it from stdin. The body is rejected if it references Claude or an assist backlog item, and in a web session it is previewed for approve/reject first (with inline comments); nothing is posted until it is approved. Raw `gh issue comment` is denied in favour of this command
145
145
  - `assist github issue edit-comment <comment-id> --body <body> [-R <owner>/<repo>]` - Replace the body of a comment that is already posted on the current repo (or `-R`'s); a body of `-` reads it from stdin. `<comment-id>` is the numeric comment id — the one in the comment's API url or its `#issuecomment-<id>` anchor — not the issue number. The replacement runs through the same gate as posting one: it is rejected if it references Claude or an assist backlog item, and in a web session it is previewed for approve/reject first (with inline comments); the published comment is untouched until it is approved. Approving sends the whole body as a `PATCH`, so what is there now is overwritten rather than appended to. Raw `gh api` writes to issue endpoints are denied in favour of this command
@@ -427,6 +427,8 @@ Neither flag leaves permanent state on the clone: nothing writes to the clone's
427
427
 
428
428
  Web server changes only need the `assist sessions` process restarted — sessions survive. Daemon/session-core changes need `assist daemon restart`: claude sessions are auto-respawned via `claude --resume` with scrollback starting fresh, while run sessions reappear as not-restored tiles that can be retried.
429
429
 
430
+ A restart kills every managed session's pty, which also kills any background task running inside it. `daemon.log` names each session it kills, and the shutdown records the reason against them in `sessions.json` before the ptys die. On restore, a session the restart caught mid-turn is resumed with a prompt naming the restart instead of the generic one, and a session that was idle only because it was waiting on a background task — a `/watch` loop, say — is woken with the same prompt, naming the task ids that died. An idle session with no background work in flight is left idle, as before.
431
+
430
432
  ## Other config keys
431
433
 
432
434
  - `slack.channel` — the Slack channel (e.g. `#example`) that `assist slack post` and `/slack-post` target when no channel argument is given
@@ -3971,7 +3971,7 @@ ${h.join(`
3971
3971
  `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),jIe&&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,n=this._model.finalSelectionEnd;return!r||!n||!t?!1:this._areCoordsInSelection(t,r,n)}isCellInSelection(e,t){let r=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!r||!n?!1:this._areCoordsInSelection([e,t],r,n)}_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=krr(r,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let n=this._getMouseBufferCoords(e);return n?(this._selectWordAt(n,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=qIe(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,-jMe),jMe),t/=jMe,t/Math.abs(t)+Math.round(t*(J6n-1)))}shouldForceSelection(e){return the?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(),eAn)}_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&&!(the&&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 n=r.lines.get(this._model.selectionEnd[1]);n&&n.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<tAn&&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 n=G6n(r[0]-1,r[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(n,!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 n=0;t>=n;n++){let i=e.loadCell(n,this._workCell).getChars().length;this._workCell.getWidth()===0?r--:i>1&&t!==n&&(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,n=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,o=i.lines.get(e[1]);if(!o)return;let a=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(o,e[0]),l=s,u=e[0]-s,h=0,f=0,d=0,p=0;if(a.charAt(s)===" "){for(;s>0&&a.charAt(s-1)===" ";)s--;for(;l<a.length&&a.charAt(l+1)===" ";)l++}else{let y=e[0],v=e[0];o.getWidth(y)===0&&(h++,y--),o.getWidth(v)===2&&(f++,v++);let b=o.getString(v).length;for(b>1&&(p+=b-1,l+=b-1);y>0&&s>0&&!this._isCharWordSeparator(o.loadCell(y-1,this._workCell));){o.loadCell(y-1,this._workCell);let x=this._workCell.getChars().length;this._workCell.getWidth()===0?(h++,y--):x>1&&(d+=x-1,s-=x-1),s--,y--}for(;v<o.length&&l+1<a.length&&!this._isCharWordSeparator(o.loadCell(v+1,this._workCell));){o.loadCell(v+1,this._workCell);let x=this._workCell.getChars().length;this._workCell.getWidth()===2?(f++,v++):x>1&&(p+=x-1,l+=x-1),l++,v++}}l++;let m=s+u-h+d,g=Math.min(this._bufferService.cols,l-s+h+f-d-p);if(!(!t&&a.slice(s,l).trim()==="")){if(r&&m===0&&o.getCodePoint(0)!==32){let y=i.lines.get(e[1]-1);if(y&&o.isWrapped&&y.getCodePoint(this._bufferService.cols-1)!==32){let v=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(v){let b=this._bufferService.cols-v.start;m-=b,g+=b}}}if(n&&m+g===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let y=i.lines.get(e[1]+1);if(y?.isWrapped&&y.getCodePoint(0)!==32){let v=this._getWordAt([0,e[1]+1],!1,!1,!0);v&&(g+=v.length)}}return{start:m,length:g}}}_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=krr(r,this._bufferService.cols)}};RIe=Ja([vr(3,fh),vr(4,wE),vr(5,$Ie),vr(6,dh),vr(7,gx),vr(8,mx)],RIe);var Err=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={}}},Rrr=class{constructor(){this._color=new Err,this._css=new Err}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()}},dl=Object.freeze((()=>{let e=[Aa.toColor("#2e3436"),Aa.toColor("#cc0000"),Aa.toColor("#4e9a06"),Aa.toColor("#c4a000"),Aa.toColor("#3465a4"),Aa.toColor("#75507b"),Aa.toColor("#06989a"),Aa.toColor("#d3d7cf"),Aa.toColor("#555753"),Aa.toColor("#ef2929"),Aa.toColor("#8ae234"),Aa.toColor("#fce94f"),Aa.toColor("#729fcf"),Aa.toColor("#ad7fa8"),Aa.toColor("#34e2e2"),Aa.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let r=0;r<216;r++){let n=t[r/36%6|0],i=t[r/6%6|0],o=t[r%6];e.push({css:Hs.toCss(n,i,o),rgba:Hs.toRgba(n,i,o)})}for(let r=0;r<24;r++){let n=8+r*10;e.push({css:Hs.toCss(n,n,n),rgba:Hs.toRgba(n,n,n)})}return e})()),vE=Aa.toColor("#ffffff"),bV=Aa.toColor("#000000"),Arr=Aa.toColor("#ffffff"),Prr=bV,dV={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},iAn=vE,AIe=class extends Nn{constructor(e){super(),this._optionsService=e,this._contrastCache=new Rrr,this._halfContrastCache=new Rrr,this._onChangeColors=this._register(new ar),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:vE,background:bV,cursor:Arr,cursorAccent:Prr,selectionForeground:void 0,selectionBackgroundTransparent:dV,selectionBackgroundOpaque:qo.blend(bV,dV),selectionInactiveBackgroundTransparent:dV,selectionInactiveBackgroundOpaque:qo.blend(bV,dV),scrollbarSliderBackground:qo.opacity(vE,.2),scrollbarSliderHoverBackground:qo.opacity(vE,.4),scrollbarSliderActiveBackground:qo.opacity(vE,.5),overviewRulerBorder:vE,ansi:dl.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=ho(e.foreground,vE),t.background=ho(e.background,bV),t.cursor=qo.blend(t.background,ho(e.cursor,Arr)),t.cursorAccent=qo.blend(t.background,ho(e.cursorAccent,Prr)),t.selectionBackgroundTransparent=ho(e.selectionBackground,dV),t.selectionBackgroundOpaque=qo.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=ho(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=qo.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?ho(e.selectionForeground,Crr):void 0,t.selectionForeground===Crr&&(t.selectionForeground=void 0),qo.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=qo.opacity(t.selectionBackgroundTransparent,.3)),qo.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=qo.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=ho(e.scrollbarSliderBackground,qo.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=ho(e.scrollbarSliderHoverBackground,qo.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=ho(e.scrollbarSliderActiveBackground,qo.opacity(t.foreground,.5)),t.overviewRulerBorder=ho(e.overviewRulerBorder,iAn),t.ansi=dl.slice(),t.ansi[0]=ho(e.black,dl[0]),t.ansi[1]=ho(e.red,dl[1]),t.ansi[2]=ho(e.green,dl[2]),t.ansi[3]=ho(e.yellow,dl[3]),t.ansi[4]=ho(e.blue,dl[4]),t.ansi[5]=ho(e.magenta,dl[5]),t.ansi[6]=ho(e.cyan,dl[6]),t.ansi[7]=ho(e.white,dl[7]),t.ansi[8]=ho(e.brightBlack,dl[8]),t.ansi[9]=ho(e.brightRed,dl[9]),t.ansi[10]=ho(e.brightGreen,dl[10]),t.ansi[11]=ho(e.brightYellow,dl[11]),t.ansi[12]=ho(e.brightBlue,dl[12]),t.ansi[13]=ho(e.brightMagenta,dl[13]),t.ansi[14]=ho(e.brightCyan,dl[14]),t.ansi[15]=ho(e.brightWhite,dl[15]),e.extendedAnsi){let r=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let n=0;n<r;n++)t.ansi[n+16]=ho(e.extendedAnsi[n],dl[n+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()}}};AIe=Ja([vr(0,dh)],AIe);function ho(e,t){if(e!==void 0)try{return Aa.toColor(e)}catch{}return t}var oAn=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)}},aAn=class{constructor(){this._services=new oAn,this._services.set(FIe,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let r=k3n(e).sort((o,a)=>o.index-a.index),n=[];for(let o of r){let a=this._services.get(o.id);if(!a)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${o.id._id}.`);n.push(a)}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,...n)}},sAn={trace:0,debug:1,info:2,warn:3,error:4,off:5},lAn="xterm.js: ",PIe=class extends Nn{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),cAn=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=sAn[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?"":lAn)+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)}};PIe=Ja([vr(0,dh)],PIe);var cAn,Lrr=class extends Nn{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new ar),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new ar),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new ar),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 n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let n=this._length-1;n>=e;n--)this._array[this._getCyclicIndex(n+r.length)]=this._array[this._getCyclicIndex(n)];for(let n=0;n<r.length;n++)this._array[this._getCyclicIndex(e+n)]=r[n];if(r.length&&this.onInsertEmitter.fire({index:e,amount:r.length}),this._length+r.length>this._maxLength){let n=this._length+r.length-this._maxLength;this._startIndex+=n,this._length=this._maxLength,this.onTrimEmitter.fire(n)}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 n=e+t+r-this._length;if(n>0)for(this._length+=n;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let n=0;n<t;n++)this.set(e+n+r,this.get(e+n))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},zn=3,Us=Object.freeze(new AV),Fue=0,YMe=2,xV=class Gnr{constructor(t,r,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(t*zn);let i=r||pm.fromCharData([0,tnr,1,0]);for(let o=0;o<t;++o)this.setCell(o,i);this.length=t}get(t){let r=this._data[t*zn+0],n=r&2097151;return[this._data[t*zn+1],r&2097152?this._combined[t]:n?HC(n):"",r>>22,r&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n]}set(t,r){this._data[t*zn+1]=r[0],r[1].length>1?(this._combined[t]=r[1],this._data[t*zn+0]=t|2097152|r[2]<<22):this._data[t*zn+0]=r[1].charCodeAt(0)|r[2]<<22}getWidth(t){return this._data[t*zn+0]>>22}hasWidth(t){return this._data[t*zn+0]&12582912}getFg(t){return this._data[t*zn+1]}getBg(t){return this._data[t*zn+2]}hasContent(t){return this._data[t*zn+0]&4194303}getCodePoint(t){let r=this._data[t*zn+0];return r&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):r&2097151}isCombined(t){return this._data[t*zn+0]&2097152}getString(t){let r=this._data[t*zn+0];return r&2097152?this._combined[t]:r&2097151?HC(r&2097151):""}isProtected(t){return this._data[t*zn+2]&536870912}loadCell(t,r){return Fue=t*zn,r.content=this._data[Fue+0],r.fg=this._data[Fue+1],r.bg=this._data[Fue+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*zn+0]=r.content,this._data[t*zn+1]=r.fg,this._data[t*zn+2]=r.bg}setCellFromCodepoint(t,r,n,i){i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*zn+0]=r|n<<22,this._data[t*zn+1]=i.fg,this._data[t*zn+2]=i.bg}addCodepointToCell(t,r,n){let i=this._data[t*zn+0];i&2097152?this._combined[t]+=HC(r):i&2097151?(this._combined[t]=HC(i&2097151)+HC(r),i&=-2097152,i|=2097152):i=r|1<<22,n&&(i&=-12582913,i|=n<<22),this._data[t*zn+0]=i}insertCells(t,r,n){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,n),r<this.length-t){let i=new pm;for(let o=this.length-t-r-1;o>=0;--o)this.setCell(t+r+o,this.loadCell(t+o,i));for(let o=0;o<r;++o)this.setCell(t+o,n)}else for(let i=t;i<this.length;++i)this.setCell(i,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(t,r,n){if(t%=this.length,r<this.length-t){let i=new pm;for(let o=0;o<this.length-t-r;++o)this.setCell(t+o,this.loadCell(t+r+o,i));for(let o=this.length-r;o<this.length;++o)this.setCell(o,n)}else for(let i=t;i<this.length;++i)this.setCell(i,n);t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,n),this.getWidth(t)===0&&!this.hasContent(t)&&this.setCellFromCodepoint(t,0,1,n)}replaceCells(t,r,n,i=!1){if(i){for(t&&this.getWidth(t-1)===2&&!this.isProtected(t-1)&&this.setCellFromCodepoint(t-1,0,1,n),r<this.length&&this.getWidth(r-1)===2&&!this.isProtected(r)&&this.setCellFromCodepoint(r,0,1,n);t<r&&t<this.length;)this.isProtected(t)||this.setCell(t,n),t++;return}for(t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,n),r<this.length&&this.getWidth(r-1)===2&&this.setCellFromCodepoint(r,0,1,n);t<r&&t<this.length;)this.setCell(t++,n)}resize(t,r){if(t===this.length)return this._data.length*4*YMe<this._data.buffer.byteLength;let n=t*zn;if(t>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let i=new Uint32Array(n);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,n);let i=Object.keys(this._combined);for(let a=0;a<i.length;a++){let s=parseInt(i[a],10);s>=t&&delete this._combined[s]}let o=Object.keys(this._extendedAttrs);for(let a=0;a<o.length;a++){let s=parseInt(o[a],10);s>=t&&delete this._extendedAttrs[s]}}return this.length=t,n*4*YMe<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*YMe<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 n=0;n<this.length;++n)this.isProtected(n)||this.setCell(n,t);return}this._combined={},this._extendedAttrs={};for(let n=0;n<this.length;++n)this.setCell(n,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 Gnr(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*zn+0]&4194303)return t+(this._data[t*zn+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*zn+0]&4194303||this._data[t*zn+2]&50331648)return t+(this._data[t*zn+0]>>22);return 0}copyCellsFrom(t,r,n,i,o){let a=t._data;if(o)for(let l=i-1;l>=0;l--){for(let u=0;u<zn;u++)this._data[(n+l)*zn+u]=a[(r+l)*zn+u];a[(r+l)*zn+2]&268435456&&(this._extendedAttrs[n+l]=t._extendedAttrs[r+l])}else for(let l=0;l<i;l++){for(let u=0;u<zn;u++)this._data[(n+l)*zn+u]=a[(r+l)*zn+u];a[(r+l)*zn+2]&268435456&&(this._extendedAttrs[n+l]=t._extendedAttrs[r+l])}let s=Object.keys(t._combined);for(let l=0;l<s.length;l++){let u=parseInt(s[l],10);u>=r&&(this._combined[u-r+n]=t._combined[u])}}translateToString(t,r,n,i){r=r??0,n=n??this.length,t&&(n=Math.min(n,this.getTrimmedLength())),i&&(i.length=0);let o="";for(;r<n;){let a=this._data[r*zn+0],s=a&2097151,l=a&2097152?this._combined[r]:s?HC(s):WC;if(o+=l,i)for(let u=0;u<l.length;++u)i.push(r);r+=a>>22||1}return i&&i.push(r),o}};function uAn(e,t,r,n,i,o){let a=[];for(let s=0;s<e.length-1;s++){let l=s,u=e.get(++l);if(!u.isWrapped)continue;let h=[e.get(s)];for(;l<e.length&&u.isWrapped;)h.push(u),u=e.get(++l);if(!o&&n>=s&&n<l){s+=h.length-1;continue}let f=0,d=RV(h,f,t),p=1,m=0;for(;p<h.length;){let y=RV(h,p,t),v=y-m,b=r-d,x=Math.min(v,b);h[f].copyCellsFrom(h[p],m,d,x,!1),d+=x,d===r&&(f++,d=0),m+=x,m===y&&(p++,m=0),d===0&&f!==0&&h[f-1].getWidth(r-1)===2&&(h[f].copyCellsFrom(h[f-1],r-1,d++,1,!1),h[f-1].setCell(r-1,i))}h[f].replaceCells(d,r,i);let g=0;for(let y=h.length-1;y>0&&(y>f||h[y].getTrimmedLength()===0);y--)g++;g>0&&(a.push(s+h.length-g),a.push(g)),s+=h.length-1}return a}function hAn(e,t){let r=[],n=0,i=t[n],o=0;for(let a=0;a<e.length;a++)if(i===a){let s=t[++n];e.onDeleteEmitter.fire({index:a-o,amount:s}),a+=s-1,o+=s,i=t[++n]}else r.push(a);return{layout:r,countRemoved:o}}function fAn(e,t){let r=[];for(let n=0;n<t.length;n++)r.push(e.get(t[n]));for(let n=0;n<r.length;n++)e.set(n,r[n]);e.length=t.length}function dAn(e,t,r){let n=[],i=e.map((l,u)=>RV(e,u,t)).reduce((l,u)=>l+u),o=0,a=0,s=0;for(;s<i;){if(i-s<r){n.push(i-s);break}o+=r;let l=RV(e,a,t);o>l&&(o-=l,a++);let u=e[a].getWidth(o-1)===2;u&&o--;let h=u?r-1:r;n.push(h),s+=h}return n}function RV(e,t,r){if(t===e.length-1)return e[t].getTrimmedLength();let n=!e[t].hasContent(r-1)&&e[t].getWidth(r-1)===1,i=e[t+1].getWidth(0)===2;return n&&i?r-1:r}var qnr=class jnr{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=jnr._nextId++,this._onDispose=this.register(new ar),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),SE(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};qnr._nextId=1;var pAn=qnr,ml={},bE=ml.B;ml[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"};ml.A={"#":"\xA3"};ml.B=void 0;ml[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"};ml.C=ml[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};ml.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"};ml.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"};ml.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"};ml.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"};ml.E=ml[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"};ml.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"};ml.H=ml[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};ml["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"};var Mrr=4294967295,Irr=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=Us.clone(),this.savedCharset=bE,this.markers=[],this._nullCell=pm.fromCharData([0,tnr,1,0]),this._whitespaceCell=pm.fromCharData([0,WC,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new rhe,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Lrr(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 Kue),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 Kue),this._whitespaceCell}getBlankLine(e,t){return new xV(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>Mrr?Mrr:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Us);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 Lrr(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let r=this.getNullCell(Us),n=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let a=0;a<this.lines.length;a++)n+=+this.lines.get(a).resize(e,r);let o=0;if(this._rows<t)for(let a=this._rows;a<t;a++)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 xV(e,r)):this.ybase>0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new xV(e,r)));else for(let a=this._rows;a>t;a--)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 a=this.lines.length-i;a>0&&(this.lines.trimStart(a),this.ybase=Math.max(this.ybase-a,0),this.ydisp=Math.max(this.ydisp-a,0),this.savedY=Math.max(this.savedY-a,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),o&&(this.y+=o),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 o=0;o<this.lines.length;o++)n+=+this.lines.get(o).resize(e,r);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),n>.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,n=uAn(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Us),r);if(n.length>0){let i=hAn(this.lines,n);fAn(this.lines,i.layout),this._reflowLargerAdjustViewport(e,t,i.countRemoved)}}_reflowLargerAdjustViewport(e,t,r){let n=this.getNullCell(Us),i=r;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new xV(e,n))):(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,n=this.getNullCell(Us),i=[],o=0;for(let a=this.lines.length-1;a>=0;a--){let s=this.lines.get(a);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let l=[s];for(;s.isWrapped&&a>0;)s=this.lines.get(--a),l.unshift(s);if(!r){let x=this.ybase+this.y;if(x>=a&&x<a+l.length)continue}let u=l[l.length-1].getTrimmedLength(),h=dAn(l,this._cols,e),f=h.length-l.length,d;this.ybase===0&&this.y!==this.lines.length-1?d=Math.max(0,this.y-this.lines.maxLength+f):d=Math.max(0,this.lines.length-this.lines.maxLength+f);let p=[];for(let x=0;x<f;x++){let C=this.getBlankLine(Us,!0);p.push(C)}p.length>0&&(i.push({start:a+l.length+o,newLines:p}),o+=p.length),l.push(...p);let m=h.length-1,g=h[m];g===0&&(m--,g=h[m]);let y=l.length-f-1,v=u;for(;y>=0;){let x=Math.min(v,g);if(l[m]===void 0)break;if(l[m].copyCellsFrom(l[y],v-x,g-x,x,!0),g-=x,g===0&&(m--,g=h[m]),v-=x,v===0){y--;let C=Math.max(y,0);v=RV(l,C,this._cols)}}for(let x=0;x<l.length;x++)h[x]<e&&l[x].setCell(h[x],n);let b=f-d;for(;b-- >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+o)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+f,this.ybase+t-1)}if(i.length>0){let a=[],s=[];for(let g=0;g<this.lines.length;g++)s.push(this.lines.get(g));let l=this.lines.length,u=l-1,h=0,f=i[h];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+o);let d=0;for(let g=Math.min(this.lines.maxLength-1,l+o-1);g>=0;g--)if(f&&f.start>u+d){for(let y=f.newLines.length-1;y>=0;y--)this.lines.set(g--,f.newLines[y]);g++,a.push({index:u+1,amount:f.newLines.length}),d+=f.newLines.length,f=i[++h]}else this.lines.set(g,s[u--]);let p=0;for(let g=a.length-1;g>=0;g--)a[g].index+=p,this.lines.onInsertEmitter.fire(a[g]),p+=a[g].amount;let m=Math.max(0,l+o-this.lines.maxLength);m>0&&this.lines.onTrimEmitter.fire(m)}}translateBufferLineToString(e,t,r=0,n){let i=this.lines.get(e);return i?i.translateToString(t,r,n):""}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 pAn(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)}},mAn=class extends Nn{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new ar),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 Irr(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Irr(!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)}},Ynr=2,Knr=1,LIe=class extends Nn{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new ar),this.onResize=this._onResize.event,this._onScroll=this._register(new ar),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Ynr),this.rows=Math.max(e.rawOptions.rows||0,Knr),this.buffers=this._register(new mAn(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,n=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:r,rowsChanged:n})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let r=this.buffer,n;n=this._cachedBlankLine,(!n||n.length!==this.cols||n.getFg(0)!==e.fg||n.getBg(0)!==e.bg)&&(n=r.getBlankLine(e,t),this._cachedBlankLine=n),n.isWrapped=t;let i=r.ybase+r.scrollTop,o=r.ybase+r.scrollBottom;if(r.scrollTop===0){let a=r.lines.isFull;o===r.lines.length-1?a?r.lines.recycle().copyFrom(n):r.lines.push(n.clone()):r.lines.splice(o+1,0,n.clone()),a?this.isUserScrolling&&(r.ydisp=Math.max(r.ydisp-1,0)):(r.ybase++,this.isUserScrolling||r.ydisp++)}else{let a=o-i+1;r.lines.shiftElements(i+1,a-1,-1),r.lines.set(o,n.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 n=r.ydisp;r.ydisp=Math.max(Math.min(r.ydisp+e,r.ybase),0),n!==r.ydisp&&(t||this._onScroll.fire(r.ydisp))}};LIe=Ja([vr(0,dh)],LIe);var aO={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:the,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},gAn=["normal","bold","100","200","300","400","500","600","700","800","900"],yAn=class extends Nn{constructor(e){super(),this._onOptionChange=this._register(new ar),this.onOptionChange=this._onOptionChange.event;let t={...aO};for(let r in e)if(r in t)try{let n=e[r];t[r]=this._sanitizeAndValidateOption(r,n)}catch(n){console.error(n)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(jo(()=>{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 aO))throw new Error(`No option with key "${r}"`);return this.rawOptions[r]},t=(r,n)=>{if(!(r in aO))throw new Error(`No option with key "${r}"`);n=this._sanitizeAndValidateOption(r,n),this.rawOptions[r]!==n&&(this.rawOptions[r]=n,this._onOptionChange.fire(r))};for(let r in this.rawOptions){let n={get:e.bind(this,r),set:t.bind(this,r)};Object.defineProperty(this.options,r,n)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=aO[e]),!vAn(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=aO[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=gAn.includes(t)?t:aO[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 vAn(e){return e==="block"||e==="underline"||e==="bar"}function TV(e,t=5){if(typeof e!="object")return e;let r=Array.isArray(e)?[]:{};for(let n in e)r[n]=t<=1?e[n]:e[n]&&TV(e[n],t-1);return r}var Drr=Object.freeze({insertMode:!1}),Orr=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),MIe=class extends Nn{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 ar),this.onData=this._onData.event,this._onUserInput=this._register(new ar),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new ar),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new ar),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=TV(Drr),this.decPrivateModes=TV(Orr)}reset(){this.modes=TV(Drr),this.decPrivateModes=TV(Orr)}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(n=>n.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))}};MIe=Ja([vr(0,fh),vr(1,anr),vr(2,dh)],MIe);var Nrr={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 KMe(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 XMe=String.fromCharCode,Brr={DEFAULT:e=>{let t=[KMe(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${XMe(t[0])}${XMe(t[1])}${XMe(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${KMe(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${KMe(e,!0)};${e.x};${e.y}${t}`}},IIe=class extends Nn{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 ar),this.onProtocolChange=this._onProtocolChange.event;for(let n of Object.keys(Nrr))this.addProtocol(n,Nrr[n]);for(let n of Object.keys(Brr))this.addEncoding(n,Brr[n]);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 n=t/r,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=n+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)}};IIe=Ja([vr(0,fh),vr(1,wE),vr(2,dh)],IIe);var ZMe=[[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]],bAn=[[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]],pl;function xAn(e,t){let r=0,n=t.length-1,i;if(e<t[0][0]||e>t[n][1])return!1;for(;n>=r;)if(i=r+n>>1,e>t[i][1])r=i+1;else if(e<t[i][0])n=i-1;else return!0;return!1}var TAn=class{constructor(){if(this.version="6",!pl){pl=new Uint8Array(65536),pl.fill(1),pl[0]=0,pl.fill(0,1,32),pl.fill(0,127,160),pl.fill(2,4352,4448),pl[9001]=2,pl[9002]=2,pl.fill(2,11904,42192),pl[12351]=1,pl.fill(2,44032,55204),pl.fill(2,63744,64256),pl.fill(2,65040,65050),pl.fill(2,65072,65136),pl.fill(2,65280,65377),pl.fill(2,65504,65511);for(let e=0;e<ZMe.length;++e)pl.fill(0,ZMe[e][0],ZMe[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?pl[e]:xAn(e,bAn)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let r=this.wcwidth(e),n=r===0&&t!==0;if(n){let i=xE.extractWidth(t);i===0?n=!1:i>r&&(r=i)}return xE.createPropertyValue(0,r,n)}},xE=class Yue{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ar,this.onChange=this._onChange.event;let t=new TAn;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,n=!1){return(t&16777215)<<3|(r&3)<<1|(n?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,n=0,i=t.length;for(let o=0;o<i;++o){let a=t.charCodeAt(o);if(55296<=a&&a<=56319){if(++o>=i)return r+this.wcwidth(a);let u=t.charCodeAt(o);56320<=u&&u<=57343?a=(a-55296)*1024+u-56320+65536:r+=this.wcwidth(u)}let s=this.charProperties(a,n),l=Yue.extractWidth(s);Yue.extractShouldJoin(s)&&(l-=Yue.extractWidth(n)),r+=l,n=s}return r}charProperties(t,r){return this._activeProvider.charProperties(t,r)}},SAn=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 Frr(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 pV=2147483647,CAn=256,Xnr=class DIe{constructor(t=32,r=32){if(this.maxLength=t,this.maxSubParamsLength=r,r>CAn)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 DIe;if(!t.length)return r;for(let n=Array.isArray(t[0])?1:0;n<t.length;++n){let i=t[n];if(Array.isArray(i))for(let o=0;o<i.length;++o)r.addSubParam(i[o]);else r.addParam(i)}return r}clone(){let t=new DIe(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 n=this._subParamsIdx[r]>>8,i=this._subParamsIdx[r]&255;i-n>0&&t.push(Array.prototype.slice.call(this._subParams,n,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>pV?pV: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>pV?pV: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,n=this._subParamsIdx[t]&255;return n-r>0?this._subParams.subarray(r,n):null}getSubParamsAll(){let t={};for(let r=0;r<this.length;++r){let n=this._subParamsIdx[r]>>8,i=this._subParamsIdx[r]&255;i-n>0&&(t[r]=this._subParams.slice(n,i))}return t}addDigit(t){let r;if(this._rejectDigits||!(r=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,i=n[r-1];n[r-1]=~i?Math.min(i*10+t,pV):t}},mV=[],wAn=class{constructor(){this._state=0,this._active=mV,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 n=r.indexOf(t);n!==-1&&r.splice(n,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=mV}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=mV,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||mV,!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",ihe(e,t,r));else for(let n=this._active.length-1;n>=0;n--)this._active[n].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 n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-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,n=this._active.length-1,i=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,r=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&r===!1){for(;n>=0&&(r=this._active[n].end(e),r!==!0);n--)if(r instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,r;n--}for(;n>=0;n--)if(r=this._active[n].end(!1),r instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,r}this._active=mV,this._id=-1,this._state=0}}},Od=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+=ihe(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}},gV=[],_An=class{constructor(){this._handlers=Object.create(null),this._active=gV,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=gV}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let r=this._handlers[e];return r.push(t),{dispose:()=>{let n=r.indexOf(t);n!==-1&&r.splice(n,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=gV,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||gV,!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",ihe(e,t,r));else for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,t,r)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let r=!1,n=this._active.length-1,i=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,r=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&r===!1){for(;n>=0&&(r=this._active[n].unhook(e),r!==!0);n--)if(r instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,r;n--}for(;n>=0;n--)if(r=this._active[n].unhook(!1),r instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,r}this._active=gV,this._ident=0}},SV=new Xnr;SV.addParam(0);var $rr=class{constructor(e){this._handler=e,this._data="",this._params=SV,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():SV,this._data="",this._hitLimit=!1}put(e,t,r){this._hitLimit||(this._data+=ihe(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=SV,this._data="",this._hitLimit=!1,r));return this._params=SV,this._data="",this._hitLimit=!1,t}},kAn=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,r,n){this.table[t<<8|e]=r<<4|n}addMany(e,t,r,n){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=r<<4|n}},dm=160,EAn=(function(){let e=new kAn(4095),t=Array.apply(null,Array(256)).map((s,l)=>l),r=(s,l)=>t.slice(s,l),n=r(32,127),i=r(0,24);i.push(25),i.push.apply(i,r(28,32));let o=r(0,14),a;e.setDefault(1,0),e.addMany(n,0,2,0);for(a in o)e.addMany([24,26,153,154],a,3,0),e.addMany(r(128,144),a,3,0),e.addMany(r(144,152),a,3,0),e.add(156,a,0,0),e.add(27,a,11,1),e.add(157,a,4,8),e.addMany([152,158,159],a,0,7),e.add(155,a,11,3),e.add(144,a,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(n,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(n,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(n,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(dm,0,2,0),e.add(dm,8,5,8),e.add(dm,6,0,6),e.add(dm,11,0,11),e.add(dm,13,13,13),e})(),RAn=class extends Nn{constructor(e=EAn){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 Xnr,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,r,n)=>{},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(jo(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new wAn),this._dcsParser=this._register(new _An),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 o=e.intermediates.charCodeAt(i);if(32>o||o>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");r<<=8,r|=o}}if(e.final.length!==1)throw new Error("final must be a single byte");let n=e.final.charCodeAt(0);if(t[0]>n||n>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return r<<=8,r|=n,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 n=this._escHandlers[r];return n.push(t),{dispose:()=>{let i=n.indexOf(t);i!==-1&&n.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 n=this._csiHandlers[r];return n.push(t),{dispose:()=>{let i=n.indexOf(t);i!==-1&&n.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,n,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=r,this._parseStack.transition=n,this._parseStack.chunkPos=i}parse(e,t,r){let n=0,i=0,o=0,a;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o=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 s=this._parseStack.handlers,l=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(r===!1&&l>-1){for(;l>=0&&(a=s[l](this._params),a!==!0);l--)if(a instanceof Promise)return this._parseStack.handlerPos=l,a}this._parseStack.handlers=[];break;case 4:if(r===!1&&l>-1){for(;l>=0&&(a=s[l](),a!==!0);l--)if(a instanceof Promise)return this._parseStack.handlerPos=l,a}this._parseStack.handlers=[];break;case 6:if(n=e[this._parseStack.chunkPos],a=this._dcsParser.unhook(n!==24&&n!==26,r),a)return a;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(n=e[this._parseStack.chunkPos],a=this._oscParser.end(n!==24&&n!==26,r),a)return a;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let s=o;s<t;++s){switch(n=e[s],i=this._transitions.table[this.currentState<<8|(n<160?n:dm)],i>>4){case 2:for(let d=s+1;;++d){if(d>=t||(n=e[d])<32||n>126&&n<dm){this._printHandler(e,s,d),s=d-1;break}if(++d>=t||(n=e[d])<32||n>126&&n<dm){this._printHandler(e,s,d),s=d-1;break}if(++d>=t||(n=e[d])<32||n>126&&n<dm){this._printHandler(e,s,d),s=d-1;break}if(++d>=t||(n=e[d])<32||n>126&&n<dm){this._printHandler(e,s,d),s=d-1;break}}break;case 3:this._executeHandlers[n]?this._executeHandlers[n]():this._executeHandlerFb(n),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:s,code:n,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let l=this._csiHandlers[this._collect<<8|n],u=l?l.length-1:-1;for(;u>=0&&(a=l[u](this._params),a!==!0);u--)if(a instanceof Promise)return this._preserveStack(3,l,u,i,s),a;u<0&&this._csiHandlerFb(this._collect<<8|n,this._params),this.precedingJoinState=0;break;case 8:do switch(n){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(n-48)}while(++s<t&&(n=e[s])>47&&n<60);s--;break;case 9:this._collect<<=8,this._collect|=n;break;case 10:let h=this._escHandlers[this._collect<<8|n],f=h?h.length-1:-1;for(;f>=0&&(a=h[f](),a!==!0);f--)if(a instanceof Promise)return this._preserveStack(4,h,f,i,s),a;f<0&&this._escHandlerFb(this._collect<<8|n),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|n,this._params);break;case 13:for(let d=s+1;;++d)if(d>=t||(n=e[d])===24||n===26||n===27||n>127&&n<dm){this._dcsParser.put(e,s,d),s=d-1;break}break;case 14:if(a=this._dcsParser.unhook(n!==24&&n!==26),a)return this._preserveStack(6,[],0,i,s),a;n===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 d=s+1;;d++)if(d>=t||(n=e[d])<32||n>127&&n<dm){this._oscParser.put(e,s,d),s=d-1;break}break;case 6:if(a=this._oscParser.end(n!==24&&n!==26),a)return this._preserveStack(5,[],0,i,s),a;n===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=i&15}}},AAn=/^([\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})$/,PAn=/^[\da-f]+$/;function zrr(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf("rgb:")===0){t=t.slice(4);let r=AAn.exec(t);if(r){let n=r[1]?15:r[4]?255:r[7]?4095:65535;return[Math.round(parseInt(r[1]||r[4]||r[7]||r[10],16)/n*255),Math.round(parseInt(r[2]||r[5]||r[8]||r[11],16)/n*255),Math.round(parseInt(r[3]||r[6]||r[9]||r[12],16)/n*255)]}}else if(t.indexOf("#")===0&&(t=t.slice(1),PAn.exec(t)&&[3,6,9,12].includes(t.length))){let r=t.length/3,n=[0,0,0];for(let i=0;i<3;++i){let o=parseInt(t.slice(r*i,r*i+r),16);n[i]=r===1?o<<4:r===2?o:r===3?o>>4:o>>8}return n}}function QMe(e,t){let r=e.toString(16),n=r.length<2?"0"+r:r;switch(t){case 4:return r[0];case 8:return n;case 12:return(n+n).slice(0,3);default:return n+n}}function LAn(e,t=16){let[r,n,i]=e;return`rgb:${QMe(r,t)}/${QMe(n,t)}/${QMe(i,t)}`}var MAn={"(":0,")":1,"*":2,"+":3,"-":1,".":2},UC=131072,Urr=10;function Hrr(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 Wrr=5e3,Vrr=0,IAn=class extends Nn{constructor(e,t,r,n,i,o,a,s,l=new RAn){super(),this._bufferService=e,this._charsetService=t,this._coreService=r,this._logService=n,this._optionsService=i,this._oscLinkService=o,this._coreMouseService=a,this._unicodeService=s,this._parser=l,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new w3n,this._utf8Decoder=new _3n,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Us.clone(),this._eraseAttrDataInternal=Us.clone(),this._onRequestBell=this._register(new ar),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new ar),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new ar),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new ar),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new ar),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new ar),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new ar),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new ar),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new ar),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new ar),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new ar),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new ar),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new ar),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 OIe(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(u=>this._activeBuffer=u.activeBuffer)),this._parser.setCsiHandlerFallback((u,h)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(u),params:h.toArray()})}),this._parser.setEscHandlerFallback(u=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(u)})}),this._parser.setExecuteHandlerFallback(u=>{this._logService.debug("Unknown EXECUTE code: ",{code:u})}),this._parser.setOscHandlerFallback((u,h,f)=>{this._logService.debug("Unknown OSC code: ",{identifier:u,action:h,data:f})}),this._parser.setDcsHandlerFallback((u,h,f)=>{h==="HOOK"&&(f=f.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(u),action:h,payload:f})}),this._parser.setPrintHandler((u,h,f)=>this.print(u,h,f)),this._parser.registerCsiHandler({final:"@"},u=>this.insertChars(u)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},u=>this.scrollLeft(u)),this._parser.registerCsiHandler({final:"A"},u=>this.cursorUp(u)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},u=>this.scrollRight(u)),this._parser.registerCsiHandler({final:"B"},u=>this.cursorDown(u)),this._parser.registerCsiHandler({final:"C"},u=>this.cursorForward(u)),this._parser.registerCsiHandler({final:"D"},u=>this.cursorBackward(u)),this._parser.registerCsiHandler({final:"E"},u=>this.cursorNextLine(u)),this._parser.registerCsiHandler({final:"F"},u=>this.cursorPrecedingLine(u)),this._parser.registerCsiHandler({final:"G"},u=>this.cursorCharAbsolute(u)),this._parser.registerCsiHandler({final:"H"},u=>this.cursorPosition(u)),this._parser.registerCsiHandler({final:"I"},u=>this.cursorForwardTab(u)),this._parser.registerCsiHandler({final:"J"},u=>this.eraseInDisplay(u,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},u=>this.eraseInDisplay(u,!0)),this._parser.registerCsiHandler({final:"K"},u=>this.eraseInLine(u,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},u=>this.eraseInLine(u,!0)),this._parser.registerCsiHandler({final:"L"},u=>this.insertLines(u)),this._parser.registerCsiHandler({final:"M"},u=>this.deleteLines(u)),this._parser.registerCsiHandler({final:"P"},u=>this.deleteChars(u)),this._parser.registerCsiHandler({final:"S"},u=>this.scrollUp(u)),this._parser.registerCsiHandler({final:"T"},u=>this.scrollDown(u)),this._parser.registerCsiHandler({final:"X"},u=>this.eraseChars(u)),this._parser.registerCsiHandler({final:"Z"},u=>this.cursorBackwardTab(u)),this._parser.registerCsiHandler({final:"`"},u=>this.charPosAbsolute(u)),this._parser.registerCsiHandler({final:"a"},u=>this.hPositionRelative(u)),this._parser.registerCsiHandler({final:"b"},u=>this.repeatPrecedingCharacter(u)),this._parser.registerCsiHandler({final:"c"},u=>this.sendDeviceAttributesPrimary(u)),this._parser.registerCsiHandler({prefix:">",final:"c"},u=>this.sendDeviceAttributesSecondary(u)),this._parser.registerCsiHandler({final:"d"},u=>this.linePosAbsolute(u)),this._parser.registerCsiHandler({final:"e"},u=>this.vPositionRelative(u)),this._parser.registerCsiHandler({final:"f"},u=>this.hVPosition(u)),this._parser.registerCsiHandler({final:"g"},u=>this.tabClear(u)),this._parser.registerCsiHandler({final:"h"},u=>this.setMode(u)),this._parser.registerCsiHandler({prefix:"?",final:"h"},u=>this.setModePrivate(u)),this._parser.registerCsiHandler({final:"l"},u=>this.resetMode(u)),this._parser.registerCsiHandler({prefix:"?",final:"l"},u=>this.resetModePrivate(u)),this._parser.registerCsiHandler({final:"m"},u=>this.charAttributes(u)),this._parser.registerCsiHandler({final:"n"},u=>this.deviceStatus(u)),this._parser.registerCsiHandler({prefix:"?",final:"n"},u=>this.deviceStatusPrivate(u)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},u=>this.softReset(u)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},u=>this.setCursorStyle(u)),this._parser.registerCsiHandler({final:"r"},u=>this.setScrollRegion(u)),this._parser.registerCsiHandler({final:"s"},u=>this.saveCursor(u)),this._parser.registerCsiHandler({final:"t"},u=>this.windowOptions(u)),this._parser.registerCsiHandler({final:"u"},u=>this.restoreCursor(u)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},u=>this.insertColumns(u)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},u=>this.deleteColumns(u)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},u=>this.selectProtected(u)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},u=>this.requestMode(u,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},u=>this.requestMode(u,!1)),this._parser.setExecuteHandler(Ft.BEL,()=>this.bell()),this._parser.setExecuteHandler(Ft.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(Ft.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(Ft.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(Ft.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(Ft.BS,()=>this.backspace()),this._parser.setExecuteHandler(Ft.HT,()=>this.tab()),this._parser.setExecuteHandler(Ft.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(Ft.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(que.IND,()=>this.index()),this._parser.setExecuteHandler(que.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(que.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Od(u=>(this.setTitle(u),this.setIconName(u),!0))),this._parser.registerOscHandler(1,new Od(u=>this.setIconName(u))),this._parser.registerOscHandler(2,new Od(u=>this.setTitle(u))),this._parser.registerOscHandler(4,new Od(u=>this.setOrReportIndexedColor(u))),this._parser.registerOscHandler(8,new Od(u=>this.setHyperlink(u))),this._parser.registerOscHandler(10,new Od(u=>this.setOrReportFgColor(u))),this._parser.registerOscHandler(11,new Od(u=>this.setOrReportBgColor(u))),this._parser.registerOscHandler(12,new Od(u=>this.setOrReportCursorColor(u))),this._parser.registerOscHandler(104,new Od(u=>this.restoreIndexedColor(u))),this._parser.registerOscHandler(110,new Od(u=>this.restoreFgColor(u))),this._parser.registerOscHandler(111,new Od(u=>this.restoreBgColor(u))),this._parser.registerOscHandler(112,new Od(u=>this.restoreCursorColor(u))),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 u in ml)this._parser.registerEscHandler({intermediates:"(",final:u},()=>this.selectCharset("("+u)),this._parser.registerEscHandler({intermediates:")",final:u},()=>this.selectCharset(")"+u)),this._parser.registerEscHandler({intermediates:"*",final:u},()=>this.selectCharset("*"+u)),this._parser.registerEscHandler({intermediates:"+",final:u},()=>this.selectCharset("+"+u)),this._parser.registerEscHandler({intermediates:"-",final:u},()=>this.selectCharset("-"+u)),this._parser.registerEscHandler({intermediates:".",final:u},()=>this.selectCharset("."+u)),this._parser.registerEscHandler({intermediates:"/",final:u},()=>this.selectCharset("/"+u));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(u=>(this._logService.error("Parsing error: ",u),u)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new $rr((u,h)=>this.requestStatusString(u,h)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,r,n){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=r,this._parseStack.position=n}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,r)=>setTimeout(()=>r("#SLOW_TIMEOUT"),Wrr))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Wrr} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let r,n=this._activeBuffer.x,i=this._activeBuffer.y,o=0,a=this._parseStack.paused;if(a){if(r=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(r),r;n=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>UC&&(o=this._parseStack.position+UC)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,u=>String.fromCharCode(u)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(u=>u.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<UC&&(this._parseBuffer=new Uint32Array(Math.min(e.length,UC))),a||this._dirtyRowTracker.clearRange(),e.length>UC)for(let u=o;u<e.length;u+=UC){let h=u+UC<e.length?u+UC:e.length,f=typeof e=="string"?this._stringDecoder.decode(e.substring(u,h),this._parseBuffer):this._utf8Decoder.decode(e.subarray(u,h),this._parseBuffer);if(r=this._parser.parse(this._parseBuffer,f))return this._preserveStack(n,i,f,u),this._logSlowResolvingAsync(r),r}else if(!a){let u=typeof e=="string"?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(r=this._parser.parse(this._parseBuffer,u))return this._preserveStack(n,i,u,0),this._logSlowResolvingAsync(r),r}(this._activeBuffer.x!==n||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=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(s,this._bufferService.rows-1)})}print(e,t,r){let n,i,o=this._charsetService.charset,a=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,l=this._coreService.decPrivateModes.wraparound,u=this._coreService.modes.insertMode,h=this._curAttrData,f=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&r-t>0&&f.getWidth(this._activeBuffer.x-1)===2&&f.setCellFromCodepoint(this._activeBuffer.x-1,0,1,h);let d=this._parser.precedingJoinState;for(let p=t;p<r;++p){if(n=e[p],n<127&&o){let v=o[String.fromCharCode(n)];v&&(n=v.charCodeAt(0))}let m=this._unicodeService.charProperties(n,d);i=xE.extractWidth(m);let g=xE.extractShouldJoin(m),y=g?xE.extractWidth(d):0;if(d=m,a&&this._onA11yChar.fire(HC(n)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-y>s){if(l){let v=f,b=this._activeBuffer.x-y;for(this._activeBuffer.x=y,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),f=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),y>0&&f instanceof xV&&f.copyCellsFrom(v,b,0,y,!1);b<s;)v.setCellFromCodepoint(b++,0,1,h)}else if(this._activeBuffer.x=s-1,i===2)continue}if(g&&this._activeBuffer.x){let v=f.getWidth(this._activeBuffer.x-1)?1:2;f.addCodepointToCell(this._activeBuffer.x-v,n,i);for(let b=i-y;--b>=0;)f.setCellFromCodepoint(this._activeBuffer.x++,0,0,h);continue}if(u&&(f.insertCells(this._activeBuffer.x,i-y,this._activeBuffer.getNullCell(h)),f.getWidth(s-1)===2&&f.setCellFromCodepoint(s-1,0,1,h)),f.setCellFromCodepoint(this._activeBuffer.x++,n,i,h),i>0)for(;--i;)f.setCellFromCodepoint(this._activeBuffer.x++,0,0,h)}this._parser.precedingJoinState=d,this._activeBuffer.x<s&&r-t>0&&f.getWidth(this._activeBuffer.x)===0&&!f.hasContent(this._activeBuffer.x)&&f.setCellFromCodepoint(this._activeBuffer.x,0,1,h),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,r=>Hrr(r.params[0],this._optionsService.rawOptions.windowOptions)?t(r):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new $rr(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Od(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,n=!1,i=!1){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);o.replaceCells(t,r,this._activeBuffer.getNullCell(this._eraseAttrData()),i),n&&(o.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 n=this._activeBuffer.lines.length-this._bufferService.rows;n>0&&(this._activeBuffer.lines.trimStart(n),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-n,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-n,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,n=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-n+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,n;for(n=this._bufferService.rows-1-this._activeBuffer.scrollBottom,n=this._bufferService.rows-1+this._activeBuffer.ybase-n;t--;)this._activeBuffer.lines.splice(r,1),this._activeBuffer.lines.splice(n,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(Us));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 n=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.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 n=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.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 n=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.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 n=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.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,n=xE.extractWidth(t),i=this._activeBuffer.x-n,o=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),a=new Uint32Array(o.length*r),s=0;for(let u=0;u<o.length;){let h=o.codePointAt(u)||0;a[s++]=h,u+=h>65535?2:1}let l=s;for(let u=1;u<r;++u)a.copyWithin(l,0,s),l+=s;return this.print(a,0,l),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(Ft.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(Ft.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(Ft.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(Ft.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(Ft.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,bE),this._charsetService.setgCharset(1,bE),this._charsetService.setgCharset(2,bE),this._charsetService.setgCharset(3,bE);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){(g=>(g[g.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",g[g.SET=1]="SET",g[g.RESET=2]="RESET",g[g.PERMANENTLY_SET=3]="PERMANENTLY_SET",g[g.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(r={}));let n=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:o}=this._coreMouseService,a=this._coreService,{buffers:s,cols:l}=this._bufferService,{active:u,alt:h}=s,f=this._optionsService.rawOptions,d=(g,y)=>(a.triggerDataEvent(`${Ft.ESC}[${t?"":"?"}${g};${y}$y`),!0),p=g=>g?1:2,m=e.params[0];return t?m===2?d(m,4):m===4?d(m,p(a.modes.insertMode)):m===12?d(m,3):m===20?d(m,p(f.convertEol)):d(m,0):m===1?d(m,p(n.applicationCursorKeys)):m===3?d(m,f.windowOptions.setWinLines?l===80?2:l===132?1:0:0):m===6?d(m,p(n.origin)):m===7?d(m,p(n.wraparound)):m===8?d(m,3):m===9?d(m,p(i==="X10")):m===12?d(m,p(f.cursorBlink)):m===25?d(m,p(!a.isCursorHidden)):m===45?d(m,p(n.reverseWraparound)):m===66?d(m,p(n.applicationKeypad)):m===67?d(m,4):m===1e3?d(m,p(i==="VT200")):m===1002?d(m,p(i==="DRAG")):m===1003?d(m,p(i==="ANY")):m===1004?d(m,p(n.sendFocus)):m===1005?d(m,4):m===1006?d(m,p(o==="SGR")):m===1015?d(m,4):m===1016?d(m,p(o==="SGR_PIXELS")):m===1048?d(m,1):m===47||m===1047||m===1049?d(m,p(u===h)):m===2004?d(m,p(n.bracketedPasteMode)):m===2026?d(m,p(n.synchronizedOutput)):d(m,0)}_updateAttrColor(e,t,r,n,i){return t===2?(e|=50331648,e&=-16777216,e|=AV.fromColorRGB([r,n,i])):t===5&&(e&=-50331904,e|=33554432|r&255),e}_extractColor(e,t,r){let n=[0,0,-1,0,0,0],i=0,o=0;do{if(n[o+i]=e.params[t+o],e.hasSubParams(t+o)){let a=e.getSubParams(t+o),s=0;do n[1]===5&&(i=1),n[o+s+1+i]=a[s];while(++s<a.length&&s+o+1+i<n.length);break}if(n[1]===5&&o+i>=2||n[1]===2&&o+i>=5)break;n[1]&&(i=1)}while(++o+t<e.length&&o+i<n.length);for(let a=2;a<n.length;++a)n[a]===-1&&(n[a]=0);switch(n[0]){case 38:r.fg=this._updateAttrColor(r.fg,n[1],n[3],n[4],n[5]);break;case 48:r.bg=this._updateAttrColor(r.bg,n[1],n[3],n[4],n[5]);break;case 58:r.extended=r.extended.clone(),r.extended.underlineColor=this._updateAttrColor(r.extended.underlineColor,n[1],n[3],n[4],n[5])}return o}_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=Us.fg,e.bg=Us.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,n=this._curAttrData;for(let i=0;i<t;i++)r=e.params[i],r>=30&&r<=37?(n.fg&=-50331904,n.fg|=16777216|r-30):r>=40&&r<=47?(n.bg&=-50331904,n.bg|=16777216|r-40):r>=90&&r<=97?(n.fg&=-50331904,n.fg|=16777216|r-90|8):r>=100&&r<=107?(n.bg&=-50331904,n.bg|=16777216|r-100|8):r===0?this._processSGR0(n):r===1?n.fg|=134217728:r===3?n.bg|=67108864:r===4?(n.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,n)):r===5?n.fg|=536870912:r===7?n.fg|=67108864:r===8?n.fg|=1073741824:r===9?n.fg|=2147483648:r===2?n.bg|=134217728:r===21?this._processUnderline(2,n):r===22?(n.fg&=-134217729,n.bg&=-134217729):r===23?n.bg&=-67108865:r===24?(n.fg&=-268435457,this._processUnderline(0,n)):r===25?n.fg&=-536870913:r===27?n.fg&=-67108865:r===28?n.fg&=-1073741825:r===29?n.fg&=2147483647:r===39?(n.fg&=-67108864,n.fg|=Us.fg&16777215):r===49?(n.bg&=-67108864,n.bg|=Us.bg&16777215):r===38||r===48||r===58?i+=this._extractColor(e,i,n):r===53?n.bg|=1073741824:r===55?n.bg&=-1073741825:r===59?(n.extended=n.extended.clone(),n.extended.underlineColor=-1,n.updateExtended()):r===100?(n.fg&=-67108864,n.fg|=Us.fg&16777215,n.bg&=-67108864,n.bg|=Us.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",r);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${Ft.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${Ft.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(`${Ft.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=Us.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(!Hrr(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(`${Ft.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Urr&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Urr&&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 n=r.shift(),i=r.shift();if(/^\d+$/.exec(n)){let o=parseInt(n);if(Grr(o))if(i==="?")t.push({type:0,index:o});else{let a=zrr(i);a&&t.push({type:1,index:o,color:a})}}}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(),n=e.slice(t+1);return n?this._createHyperlink(r,n):r.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let r=e.split(":"),n,i=r.findIndex(o=>o.startsWith("id="));return i!==-1&&(n=r[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:n,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 n=0;n<r.length&&!(t>=this._specialColors.length);++n,++t)if(r[n]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let i=zrr(r[n]);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 n=0;n<r.length;++n)if(/^\d+$/.exec(r[n])){let i=parseInt(r[n]);Grr(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,bE),!0}selectCharset(e){return e.length!==2?(this.selectDefaultCharset(),!0):(e[0]==="/"||this._charsetService.setgCharset(MAn[e[0]],ml[e[1]]||bE),!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=Us.clone(),this._eraseAttrDataInternal=Us.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 pm;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,n=this._activeBuffer.lines.get(r);n&&(n.fill(e),n.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let r=a=>(this._coreService.triggerDataEvent(`${Ft.ESC}${a}${Ft.ESC}\\`),!0),n=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${n.scrollTop+1};${n.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)}},OIe=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&&(Vrr=e,e=t,t=Vrr),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};OIe=Ja([vr(0,fh)],OIe);function Grr(e){return 0<=e&&e<256}var DAn=5e7,qrr=12,OAn=50,NAn=class extends Nn{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 ar),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 n=this._callbacks.shift();n&&n()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>DAn)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 n=this._writeBuffer[this._bufferOffset],i=this._action(n,t);if(i){let a=s=>performance.now()-r>=qrr?setTimeout(()=>this._innerWrite(0,s)):this._innerWrite(r,s);i.catch(s=>(queueMicrotask(()=>{throw s}),Promise.resolve(!1))).then(a);return}let o=this._callbacks[this._bufferOffset];if(o&&o(),this._bufferOffset++,this._pendingData-=n.length,performance.now()-r>=qrr)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>OAn&&(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()}},NIe=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 s=t.addMarker(t.ybase+t.y),l={data:e,id:this._nextId++,lines:[s]};return s.onDispose(()=>this._removeMarkerFromLink(l,s)),this._dataByLinkId.set(l.id,l),l.id}let r=e,n=this._getEntryIdKey(r),i=this._entriesWithId.get(n);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let o=t.addMarker(t.ybase+t.y),a={id:this._nextId++,key:this._getEntryIdKey(r),data:r,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(a,o)),this._entriesWithId.set(a.key,a),this._dataByLinkId.set(a.id,a),a.id}addLineToLink(e,t){let r=this._dataByLinkId.get(e);if(r&&r.lines.every(n=>n.line!==t)){let n=this._bufferService.buffer.addMarker(t);r.lines.push(n),n.onDispose(()=>this._removeMarkerFromLink(r,n))}}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)))}};NIe=Ja([vr(0,fh)],NIe);var jrr=!1,BAn=class extends Nn{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new lO),this._onBinary=this._register(new ar),this.onBinary=this._onBinary.event,this._onData=this._register(new ar),this.onData=this._onData.event,this._onLineFeed=this._register(new ar),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new ar),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new ar),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new ar),this._instantiationService=new aAn,this.optionsService=this._register(new yAn(e)),this._instantiationService.setService(dh,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(LIe)),this._instantiationService.setService(fh,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(PIe)),this._instantiationService.setService(anr,this._logService),this.coreService=this._register(this._instantiationService.createInstance(MIe)),this._instantiationService.setService(wE,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(IIe)),this._instantiationService.setService(onr,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(xE)),this._instantiationService.setService(A3n,this.unicodeService),this._charsetService=this._instantiationService.createInstance(SAn),this._instantiationService.setService(R3n,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(NIe),this._instantiationService.setService(snr,this._oscLinkService),this._inputHandler=this._register(new IAn(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Wc.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Wc.forward(this._bufferService.onResize,this._onResize)),this._register(Wc.forward(this.coreService.onData,this._onData)),this._register(Wc.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 NAn((t,r)=>this._inputHandler.parse(t,r))),this._register(Wc.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new ar),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&&!jrr&&(this._logService.warn("writeSync is unreliable and will be removed soon."),jrr=!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,Ynr),t=Math.max(t,Knr),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(Frr.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Frr(this._bufferService),!1))),this._windowsWrappingHeuristics.value=jo(()=>{for(let t of e)t.dispose()})}}},FAn={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 $An(e,t,r,n){let i={type:0,cancel:!1,key:void 0},o=(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=Ft.ESC+"OA":i.key=Ft.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?i.key=Ft.ESC+"OD":i.key=Ft.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?i.key=Ft.ESC+"OC":i.key=Ft.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?i.key=Ft.ESC+"OB":i.key=Ft.ESC+"[B");break;case 8:i.key=e.ctrlKey?"\b":Ft.DEL,e.altKey&&(i.key=Ft.ESC+i.key);break;case 9:if(e.shiftKey){i.key=Ft.ESC+"[Z";break}i.key=Ft.HT,i.cancel=!0;break;case 13:i.key=e.altKey?Ft.ESC+Ft.CR:Ft.CR,i.cancel=!0;break;case 27:i.key=Ft.ESC,e.altKey&&(i.key=Ft.ESC+Ft.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;o?i.key=Ft.ESC+"[1;"+(o+1)+"D":t?i.key=Ft.ESC+"OD":i.key=Ft.ESC+"[D";break;case 39:if(e.metaKey)break;o?i.key=Ft.ESC+"[1;"+(o+1)+"C":t?i.key=Ft.ESC+"OC":i.key=Ft.ESC+"[C";break;case 38:if(e.metaKey)break;o?i.key=Ft.ESC+"[1;"+(o+1)+"A":t?i.key=Ft.ESC+"OA":i.key=Ft.ESC+"[A";break;case 40:if(e.metaKey)break;o?i.key=Ft.ESC+"[1;"+(o+1)+"B":t?i.key=Ft.ESC+"OB":i.key=Ft.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=Ft.ESC+"[2~");break;case 46:o?i.key=Ft.ESC+"[3;"+(o+1)+"~":i.key=Ft.ESC+"[3~";break;case 36:o?i.key=Ft.ESC+"[1;"+(o+1)+"H":t?i.key=Ft.ESC+"OH":i.key=Ft.ESC+"[H";break;case 35:o?i.key=Ft.ESC+"[1;"+(o+1)+"F":t?i.key=Ft.ESC+"OF":i.key=Ft.ESC+"[F";break;case 33:e.shiftKey?i.type=2:e.ctrlKey?i.key=Ft.ESC+"[5;"+(o+1)+"~":i.key=Ft.ESC+"[5~";break;case 34:e.shiftKey?i.type=3:e.ctrlKey?i.key=Ft.ESC+"[6;"+(o+1)+"~":i.key=Ft.ESC+"[6~";break;case 112:o?i.key=Ft.ESC+"[1;"+(o+1)+"P":i.key=Ft.ESC+"OP";break;case 113:o?i.key=Ft.ESC+"[1;"+(o+1)+"Q":i.key=Ft.ESC+"OQ";break;case 114:o?i.key=Ft.ESC+"[1;"+(o+1)+"R":i.key=Ft.ESC+"OR";break;case 115:o?i.key=Ft.ESC+"[1;"+(o+1)+"S":i.key=Ft.ESC+"OS";break;case 116:o?i.key=Ft.ESC+"[15;"+(o+1)+"~":i.key=Ft.ESC+"[15~";break;case 117:o?i.key=Ft.ESC+"[17;"+(o+1)+"~":i.key=Ft.ESC+"[17~";break;case 118:o?i.key=Ft.ESC+"[18;"+(o+1)+"~":i.key=Ft.ESC+"[18~";break;case 119:o?i.key=Ft.ESC+"[19;"+(o+1)+"~":i.key=Ft.ESC+"[19~";break;case 120:o?i.key=Ft.ESC+"[20;"+(o+1)+"~":i.key=Ft.ESC+"[20~";break;case 121:o?i.key=Ft.ESC+"[21;"+(o+1)+"~":i.key=Ft.ESC+"[21~";break;case 122:o?i.key=Ft.ESC+"[23;"+(o+1)+"~":i.key=Ft.ESC+"[23~";break;case 123:o?i.key=Ft.ESC+"[24;"+(o+1)+"~":i.key=Ft.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=Ft.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=Ft.DEL:e.keyCode===219?i.key=Ft.ESC:e.keyCode===220?i.key=Ft.FS:e.keyCode===221&&(i.key=Ft.GS);else if((!r||n)&&e.altKey&&!e.metaKey){let a=FAn[e.keyCode]?.[e.shiftKey?1:0];if(a)i.key=Ft.ESC+a;else if(e.keyCode>=65&&e.keyCode<=90){let s=e.ctrlKey?e.keyCode-64:e.keyCode+32,l=String.fromCharCode(s);e.shiftKey&&(l=l.toUpperCase()),i.key=Ft.ESC+l}else if(e.keyCode===32)i.key=Ft.ESC+(e.ctrlKey?Ft.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let s=e.code.slice(3,4);e.shiftKey||(s=s.toLowerCase()),i.key=Ft.ESC+s,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=Ft.US),e.key==="@"&&(i.key=Ft.NUL));break}return i}var ms=0,zAn=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new rhe,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new rhe,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,o)=>this._getKey(i)-this._getKey(o)),t=0,r=0,n=new Array(this._array.length+this._insertedValues.length);for(let i=0;i<n.length;i++)r>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[r])?(n[i]=e[t],t++):n[i]=this._array[r++];this._array=n,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||(ms=this._search(t),ms===-1)||this._getKey(this._array[ms])!==t)return!1;do if(this._array[ms]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(ms),!0;while(++ms<this._array.length&&this._getKey(this._array[ms])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((i,o)=>i-o),t=0,r=new Array(this._array.length-e.length),n=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:r[n++]=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&&(ms=this._search(e),!(ms<0||ms>=this._array.length)&&this._getKey(this._array[ms])===e))do yield this._array[ms];while(++ms<this._array.length&&this._getKey(this._array[ms])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(ms=this._search(e),!(ms<0||ms>=this._array.length)&&this._getKey(this._array[ms])===e))do t(this._array[ms]);while(++ms<this._array.length&&this._getKey(this._array[ms])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,r=this._array.length-1;for(;r>=t;){let n=t+r>>1,i=this._getKey(this._array[n]);if(i>e)r=n-1;else if(i<e)t=n+1;else{for(;n>0&&this._getKey(this._array[n-1])===e;)n--;return n}}return t}},JMe=0,Yrr=0,UAn=class extends Nn{constructor(){super(),this._decorations=new zAn(e=>e?.marker.line),this._onDecorationRegistered=this._register(new ar),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new ar),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(jo(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new HAn(e);if(t){let r=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.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 n=0,i=0;for(let o of this._decorations.getKeyIterator(t))n=o.options.x??0,i=n+(o.options.width??1),e>=n&&e<i&&(!r||(o.options.layer??"bottom")===r)&&(yield o)}forEachDecorationAtCell(e,t,r,n){this._decorations.forEachByKey(t,i=>{JMe=i.options.x??0,Yrr=JMe+(i.options.width??1),e>=JMe&&e<Yrr&&(!r||(i.options.layer??"bottom")===r)&&n(i)})}},HAn=class extends VC{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new ar),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new ar),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=Aa.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=Aa.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},WAn=1e3,VAn=class{constructor(e,t=WAn){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 n=performance.now();if(n-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=n,this._innerRefresh();else if(!this._additionalRefreshRequested){let i=n-this._lastRefreshMs,o=this._debounceThresholdMS-i;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},o)}}_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)}},Krr=20,Xrr=!1,nhe=class extends Nn{constructor(e,t,r,n){super(),this._terminal=e,this._coreBrowserService=r,this._renderService=n,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 o=0;o<this._terminal.rows;o++)this._rowElements[o]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[o]);if(this._topBoundaryFocusListener=o=>this._handleBoundaryFocus(o,0),this._bottomBoundaryFocusListener=o=>this._handleBoundaryFocus(o,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 VAn(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");Xrr?(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(o=>this._handleResize(o.rows))),this._register(this._terminal.onRender(o=>this._refreshRows(o.start,o.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(o=>this._handleChar(o))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
3972
3972
  `))),this._register(this._terminal.onA11yTab(o=>this._handleTab(o))),this._register(this._terminal.onKey(o=>this._handleKey(o.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(bn(i,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(jo(()=>{Xrr?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<Krr+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
3973
3973
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===Krr+1&&(this._liveRegion.textContent+=tIe.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,n=r.lines.length.toString();for(let i=e;i<=t;i++){let o=r.lines.get(r.ydisp+i),a=[],s=o?.translateToString(!0,void 0,void 0,a)||"",l=(r.ydisp+i+1).toString(),u=this._rowElements[i];u&&(s.length===0?(u.textContent="\xA0",this._rowColumns.set(u,[0,1])):(u.textContent=s,this._rowColumns.set(u,a)),u.setAttribute("aria-posinset",l),u.setAttribute("aria-setsize",n),this._alignRowWidth(u))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let r=e.target,n=this._rowElements[t===0?1:this._rowElements.length-2],i=r.getAttribute("aria-posinset"),o=t===0?"1":`${this._terminal.buffer.lines.length}`;if(i===o||e.relatedTarget!==n)return;let a,s;if(t===0?(a=r,s=this._rowElements.pop(),this._rowContainer.removeChild(s)):(a=this._rowElements.shift(),s=r,this._rowContainer.removeChild(a)),a.removeEventListener("focus",this._topBoundaryFocusListener),s.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 n=this._rowElements.slice(-1)[0];if(r.node.compareDocumentPosition(n)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(r={node:n,offset:n.textContent?.length??0}),!this._rowContainer.contains(r.node))return;let i=({node:s,offset:l})=>{let u=s instanceof Text?s.parentNode:s,h=parseInt(u?.getAttribute("aria-posinset"),10)-1;if(isNaN(h))return console.warn("row is invalid. Race condition?"),null;let f=this._rowColumns.get(u);if(!f)return console.warn("columns is null. Race condition?"),null;let d=l<f.length?f[l]:f.slice(-1)[0]+1;return d>=this._terminal.cols&&(++h,d=0),{row:h,column:d}},o=i(t),a=i(r);if(!(!o||!a)){if(o.row>a.row||o.row===a.row&&o.column>=a.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(a.row-o.row)*this._terminal.cols-o.column+a.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 n=r*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${n/t})`}};nhe=Ja([vr(1,FIe),vr(2,mx),vr(3,gx)],nhe);var BIe=class extends Nn{constructor(e,t,r,n,i){super(),this._element=e,this._mouseService=t,this._renderService=r,this._bufferService=n,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new ar),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new ar),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(jo(()=>{SE(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(bn(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(bn(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(bn(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(bn(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 n=0;n<r.length;n++){let i=r[n];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(n=>{n?.forEach(i=>{i.link.dispose&&i.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let r=!1;for(let[n,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(n)&&(r=this._checkLinkProviderResult(n,e,r)):i.provideLinks(e.y,o=>{if(this._isMouseOut)return;let a=o?.map(s=>({link:s}));this._activeProviderReplies?.set(n,a),r=this._checkLinkProviderResult(n,e,r),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let r=new Set;for(let n=0;n<t.size;n++){let i=t.get(n);if(i)for(let o=0;o<i.length;o++){let a=i[o],s=a.link.range.start.y<e?0:a.link.range.start.x,l=a.link.range.end.y>e?this._bufferService.cols:a.link.range.end.x;for(let u=s;u<=l;u++){if(r.has(u)){i.splice(o--,1);break}r.add(u)}}}}_checkLinkProviderResult(e,t,r){if(!this._activeProviderReplies)return r;let n=this._activeProviderReplies.get(e),i=!1;for(let o=0;o<e;o++)(!this._activeProviderReplies.has(o)||this._activeProviderReplies.get(o))&&(i=!0);if(!i&&n){let o=n.find(a=>this._linkAtPosition(a.link,t));o&&(r=!0,this._handleNewLink(o))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!r)for(let o=0;o<this._activeProviderReplies.size;o++){let a=this._activeProviderReplies.get(o)?.find(s=>this._linkAtPosition(s.link,t));if(a){r=!0,this._handleNewLink(a);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&&GAn(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,SE(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 n=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>=n&&this._currentLink.link.range.end.y<=i&&(this._clearCurrentLink(n,i),this._lastMouseEvent)){let o=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);o&&this._askForLink(o,!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,n=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(r.start.x-1,r.start.y-n-1,r.end.x,r.end.y-n-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,n=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return r<=i&&i<=n}_positionFromMouseEvent(e,t,r){let n=r.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(n)return{x:n[0],y:n[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,r,n,i){return{x1:e,y1:t,x2:r,y2:n,cols:this._bufferService.cols,fg:i}}};BIe=Ja([vr(1,$Ie),vr(2,gx),vr(3,fh),vr(4,cnr)],BIe);function GAn(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 qAn=class extends BAn{constructor(e={}){super(e),this._linkifier=this._register(new lO),this.browser=Bnr,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new lO),this._onCursorMove=this._register(new ar),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new ar),this.onKey=this._onKey.event,this._onRender=this._register(new ar),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new ar),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new ar),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new ar),this.onBell=this._onBell.event,this._onFocus=this._register(new ar),this._onBlur=this._register(new ar),this._onA11yCharEmitter=this._register(new ar),this._onA11yTabEmitter=this._register(new ar),this._onWillOpen=this._register(new ar),this._setup(),this._decorationService=this._instantiationService.createInstance(UAn),this._instantiationService.setService(PV,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(D6n),this._instantiationService.setService(cnr,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(nIe)),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(Wc.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Wc.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Wc.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Wc.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(jo(()=>{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,n="";switch(t.index){case 256:r="foreground",n="10";break;case 257:r="background",n="11";break;case 258:r="cursor",n="12";break;default:r="ansi",n="4;"+t.index}switch(t.type){case 0:let i=qo.toColorRGB(r==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[r]);this.coreService.triggerDataEvent(`${Ft.ESC}]${n};${LAn(i)}${Onr.ST}`);break;case 1:if(r==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=Hs.toColor(...t.color));else{let o=r;this._themeService.modifyColors(a=>a[o]=Hs.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(nhe,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(Ft.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(Ft.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),n=this._renderService.dimensions.css.cell.height,i=t.getWidth(r),o=this._renderService.dimensions.css.cell.width*i,a=this.buffer.y*this._renderService.dimensions.css.cell.height,s=r*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+"px",this.textarea.style.top=a+"px",this.textarea.style.width=o+"px",this.textarea.style.height=n+"px",this.textarea.style.lineHeight=n+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(bn(this.element,"copy",t=>{this.hasSelection()&&S3n(t,this._selectionService)}));let e=t=>C3n(t,this.textarea,this.coreService,this.optionsService);this._register(bn(this.textarea,"paste",e)),this._register(bn(this.element,"paste",e)),Fnr?this._register(bn(this.element,"mousedown",t=>{t.button===2&&Ztr(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(bn(this.element,"contextmenu",t=>{Ztr(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),jIe&&this._register(bn(this.element,"auxclick",t=>{t.button===1&&enr(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(bn(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(bn(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(bn(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(bn(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(bn(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(bn(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(bn(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(bn(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",eIe.get()),Unr||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(M6n,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(mx,this._coreBrowserService),this._register(bn(this.textarea,"focus",i=>this._handleTextAreaFocus(i))),this._register(bn(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(_Ie,this._document,this._helperContainer),this._instantiationService.setService(ohe,this._charSizeService),this._themeService=this._instantiationService.createInstance(AIe),this._instantiationService.setService(cO,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(ehe),this._instantiationService.setService(lnr,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(EIe,this.rows,this.screenElement)),this._instantiationService.setService(gx,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(SIe,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(kIe),this._instantiationService.setService($Ie,this._mouseService);let n=this._linkifier.value=this._register(this._instantiationService.createInstance(BIe,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(xIe,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(RIe,this.element,this.screenElement,n)),this._instantiationService.setService(L3n,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(Wc.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(TIe,this.screenElement)),this._register(bn(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(nhe,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",i=>this._handleScreenReaderModeOptionChange(i))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Jue,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",i=>{!this._overviewRulerRenderer&&i&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Jue,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(wIe,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function r(o){let a=e._mouseService.getMouseReportCoords(o,e.screenElement);if(!a)return!1;let s,l;switch(o.overrideType||o.type){case"mousemove":l=32,o.buttons===void 0?(s=3,o.button!==void 0&&(s=o.button<3?o.button:3)):s=o.buttons&1?0:o.buttons&4?1:o.buttons&2?2:3;break;case"mouseup":l=0,s=o.button<3?o.button:3;break;case"mousedown":l=1,s=o.button<3?o.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(o)===!1)return!1;let u=o.deltaY;if(u===0||e.coreMouseService.consumeWheelEvent(o,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;l=u<0?0:1,s=4;break;default:return!1}return l===void 0||s===void 0||s>4?!1:e.coreMouseService.triggerMouseEvent({col:a.col,row:a.row,x:a.x,y:a.y,button:s,action:l,ctrl:o.ctrlKey,alt:o.altKey,shift:o.shiftKey})}let n={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:o=>(r(o),o.buttons||(this._document.removeEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.removeEventListener("mousemove",n.mousedrag)),this.cancel(o)),wheel:o=>(r(o),this.cancel(o,!0)),mousedrag:o=>{o.buttons&&r(o)},mousemove:o=>{o.buttons||r(o)}};this._register(this.coreMouseService.onProtocolChange(o=>{o?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(o)),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()),o&8?n.mousemove||(t.addEventListener("mousemove",i.mousemove),n.mousemove=i.mousemove):(t.removeEventListener("mousemove",n.mousemove),n.mousemove=null),o&16?n.wheel||(t.addEventListener("wheel",i.wheel,{passive:!1}),n.wheel=i.wheel):(t.removeEventListener("wheel",n.wheel),n.wheel=null),o&2?n.mouseup||(n.mouseup=i.mouseup):(this._document.removeEventListener("mouseup",n.mouseup),n.mouseup=null),o&4?n.mousedrag||(n.mousedrag=i.mousedrag):(this._document.removeEventListener("mousemove",n.mousedrag),n.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(bn(t,"mousedown",o=>{if(o.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(o)))return r(o),n.mouseup&&this._document.addEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.addEventListener("mousemove",n.mousedrag),this.cancel(o)})),this._register(bn(t,"wheel",o=>{if(!n.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(o)===!1)return!1;if(!this.buffer.hasScrollback){if(o.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(o,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(o,!0);let a=Ft.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(o.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(a,!0),this.cancel(o,!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){Jrr(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=$An(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),r.type===3||r.type===2){let n=this.rows-1;return this.scrollLines(r.type===2?-n:n),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===Ft.ETX||r.key===Ft.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)&&(jAn(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(Us));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(Ft.ESC+"[I"):this.coreService.triggerDataEvent(Ft.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(`${Ft.ESC}[4;${r};${t}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),i=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${Ft.ESC}[6;${i};${n}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function jAn(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var YAn=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)}},KAn=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 pm)}translateToString(e,t,r){return this._line.translateToString(e,t,r)}},Zrr=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 KAn(t)}getNullCell(){return new pm}},XAn=class extends Nn{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ar),this.onBufferChange=this._onBufferChange.event,this._normal=new Zrr(this._core.buffers.normal,"normal"),this._alternate=new Zrr(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)}},ZAn=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,n)=>t(r,n.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)}},QAn=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}},JAn=["cols","rows"],jy=0,Znr=class extends Nn{constructor(e){super(),this._core=this._register(new qAn(e)),this._addonManager=this._register(new YAn),this._publicOptions={...this._core.options};let t=n=>this._core.options[n],r=(n,i)=>{this._checkReadonlyOptions(n),this._core.options[n]=i};for(let n in this._core.options){let i={get:t.bind(this,n),set:r.bind(this,n)};Object.defineProperty(this._publicOptions,n,i)}}_checkReadonlyOptions(e){if(JAn.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 ZAn(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new QAn(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 XAn(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
3974
- `,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 eIe.get()},set promptLabel(e){eIe.set(e)},get tooMuchOutput(){return tIe.get()},set tooMuchOutput(e){tIe.set(e)}}}_verifyIntegers(...e){for(jy of e)if(jy===1/0||isNaN(jy)||jy%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(jy of e)if(jy&&(jy===1/0||isNaN(jy)||jy%1!==0||jy<0))throw new Error("This API only accepts positive integers")}};var YIe=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\^<>`]*[^\s"':,.!?{}|\\^~[\]`()<>]/;function ePn(e){try{return!!new URL(e).host}catch{return!1}}function Jnr(e,t){let r=e(t),n=e(t+1);return!!r&&!!n&&(n.isWrapped||r.isFull)}function tPn(e,t){let r=[];for(let n=t;n-t<64;n++){let i=e(n);if(!i||(r.push(i.text),!Jnr(e,n)))break}return r}function Qnr(e,t,r){let n=t;for(let i of e){if(r<i.length)return{x:r+1,y:n+1};r-=i.length,n++}}function rPn(e,t,r){let n=r[0],i=Qnr(e,t,r.index),o=Qnr(e,t,r.index+n.length-1);if(!(!ePn(n)||!i||!o))return{text:n,range:{start:i,end:o}}}function nPn(e,t,r){let n=new RegExp(r.source,`${r.flags||""}g`);return[...e.join("").matchAll(n)].flatMap(o=>rPn(e,t,o)??[])}function eir(e,t,r=YIe){if(!e(t-1))return[];let n=t-1;for(;n>0&&Jnr(e,n-1);)n--;return nPn(tPn(e,n),n,r)}function tir(e,t){let r=n=>{let i=e.buffer.active.getLine(n);if(!i)return;let o=e.cols,a=i.getCell(o-1);return{text:i.translateToString(!0,0,o),isWrapped:i.isWrapped,isFull:!!a&&a.getChars()!==""&&a.getChars()!==" "}};return{provideLinks(n,i){let o=eir(r,n,YIe);i(o.map(a=>({range:a.range,text:a.text,activate:t})))}}}function rir(e){let t=new Znr({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', Consolas, monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4"},linkHandler:{activate:(o,a)=>{window.open(a,"_blank")}}}),r=new Aer;t.loadAddon(r);let n=t.registerLinkProvider(tir(t,(o,a)=>{window.open(a,"_blank")}));t.open(e);let i;try{i=new Ytr,i.onContextLoss(()=>{i?.dispose(),i=void 0}),t.loadAddon(i)}catch{i=void 0}return r.fit(),{term:t,fitAddon:r,dispose:()=>{n.dispose(),i?.dispose(),t.dispose()}}}function nir(e,t,r,n){if(e.type!=="keydown"||!(e.ctrlKey||e.metaKey)||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(n),!1):!0}function uhe(e){return e.type==="keydown"&&(e.ctrlKey||e.metaKey)&&!e.shiftKey&&!e.altKey&&e.key.toLowerCase()==="p"}function iir(e,t,r,n,i){let o=rir(e);o.term.onData(u=>r(t,u)),o.term.attachCustomKeyEventHandler(u=>uhe(u)?!1:nir(u,o.term,navigator.clipboard,h=>o.term.paste(h)));let a=n(t,u=>o.term.write(u)),s=new ResizeObserver(()=>{yue(e)&&(o.fitAddon.fit(),i(t,o.term.cols,o.term.rows))});return s.observe(e),{handle:o,cleanup:()=>{s.disconnect(),a(),o.dispose()}}}function oir(e,t,r,n,i,o){let a=(0,IV.useRef)(null);(0,IV.useEffect)(()=>{let s=e.current;if(!s)return;let{handle:l,cleanup:u}=iir(s,t,n,i,o);return a.current=l,()=>{u(),a.current=null}},[e,t,i,n,o]),(0,IV.useEffect)(()=>{let s=a.current;if(!r||!s)return;let l=setTimeout(()=>{yue(e.current)&&(s.fitAddon.fit(),s.term.focus(),o(t,s.term.cols,s.term.rows))},50);return()=>clearTimeout(l)},[e,r,t,o])}var lir=$(V(),1);function sir({sessionId:e,visible:t,onOutput:r,sendInput:n,sendResize:i}){let o=(0,air.useRef)(null);return oir(o,e,t,n,r,i),(0,lir.jsx)(Ie,{ref:o,sx:{position:"absolute",inset:"0 0 0 8px",visibility:t?"visible":"hidden",pointerEvents:t?"auto":"none"}})}var _E=$(V(),1);function cir({sessions:e,activeId:t,activeLoading:r,onOutput:n,sendInput:i,sendResize:o}){return(0,_E.jsxs)(Ie,{sx:{flex:1,position:"relative",bgcolor:"background.default"},children:[e.map(a=>(0,_E.jsx)(sir,{sessionId:a.id,visible:a.id===t,onOutput:n,sendInput:i,sendResize:o},a.id)),r&&(0,_E.jsx)(Rer,{}),e.length===0&&(0,_E.jsx)(Ie,{sx:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:(0,_E.jsx)(tt,{variant:"body2",color:"text.disabled",children:"Create a session to get started"})})]})}var hir=$(V(),1);function uir({sessions:e,activeId:t,initialized:r,onOutput:n,sendInput:i,sendResize:o}){let a=e.find(l=>l.id===t),s=a!==void 0&&yse(a,r);return(0,hir.jsx)(cir,{sessions:e,activeId:t,activeLoading:s,onOutput:n,sendInput:i,sendResize:o})}var hO=$(V(),1),iPn={position:"relative",display:"flex",flex:1,minWidth:0,minHeight:0};function fir({activeSession:e,sendPrDecision:t,showLastMessage:r,...n}){return(0,hO.jsxs)(Ie,{sx:iPn,children:[(0,hO.jsx)(xer,{session:e,sendPrDecision:t,sendInput:n.sendInput,children:(0,hO.jsx)(uir,{...n})}),r&&e!==void 0&&(0,hO.jsx)(ker,{message:e.lastUserMessage})]})}var dir=$(V(),1),pir=Tt((0,dir.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 mm=$(V(),1);function mir({message:e}){return e.role==="tool"?(0,mm.jsx)(oPn,{tool:e.tool,target:e.target}):(0,mm.jsx)(aPn,{role:e.role,text:e.text})}function oPn({tool:e,target:t}){return(0,mm.jsxs)(Ie,{sx:{display:"flex",alignItems:"center",gap:1,py:.5,pl:1},children:[(0,mm.jsx)(pir,{sx:{fontSize:14,color:"text.disabled"}}),(0,mm.jsxs)(tt,{variant:"caption",sx:{color:"text.secondary",fontFamily:"monospace"},children:[(0,mm.jsx)(Ie,{component:"span",sx:{color:"warning.main"},children:e}),t&&(0,mm.jsxs)(Ie,{component:"span",children:[" ",t]})]})]})}function aPn({role:e,text:t}){let r=e==="user",n=r?"info.main":"success.main";return(0,mm.jsxs)(Ie,{sx:{mb:1.5,pl:1.5,py:1,pr:1,borderLeft:2,borderColor:n,borderTopRightRadius:1,borderBottomRightRadius:1,bgcolor:r?"action.hover":"transparent"},children:[(0,mm.jsx)(tt,{variant:"caption",sx:{color:n,fontWeight:600,display:"block",mb:.5},children:r?"User":"Assistant"}),(0,mm.jsx)(tt,{variant:"body2",sx:{color:"text.primary",whiteSpace:"pre-wrap",overflowWrap:"anywhere",lineHeight:1.6},children:t})]})}var Zy=$(V(),1);function sPn(e){let t=new Map;return e.map(r=>{let n=r.role==="tool"?`tool:${r.tool}:${r.target}`:`${r.role}:${r.text.slice(0,40)}`,i=t.get(n)??0;return t.set(n,i+1),{...r,key:`${n}#${i}`}})}function yir({messages:e,loading:t}){return t?(0,Zy.jsxs)(Ie,{sx:gir,children:[(0,Zy.jsx)(no,{size:20}),(0,Zy.jsx)(tt,{variant:"caption",color:"text.disabled",children:"Loading transcript\u2026"})]}):e.length===0?(0,Zy.jsx)(Ie,{sx:gir,children:(0,Zy.jsx)(tt,{variant:"body2",color:"text.disabled",children:"No transcript available"})}):(0,Zy.jsx)(Ie,{sx:{position:"absolute",inset:0,overflowY:"auto",p:2},children:(0,Zy.jsx)(Ie,{sx:{maxWidth:820,mx:"auto"},children:sPn(e).map(r=>(0,Zy.jsx)(mir,{message:r},r.key))})})}var gir={position:"absolute",inset:0,display:"flex",flexDirection:"column",gap:1.5,alignItems:"center",justifyContent:"center"};var KIe=$(V(),1);function vir({sessionId:e,transcript:t}){let r=t?.sessionId===e;return(0,KIe.jsx)(Ie,{sx:{flex:1,position:"relative",bgcolor:"background.default"},children:(0,KIe.jsx)(yir,{messages:r?t?.messages??[]:[],loading:!r})})}var GC=$(V(),1),lPn={flex:1,minHeight:0,display:"flex",flexDirection:"column"},cPn={flexShrink:0};function bir({viewingTranscriptSessionId:e,transcript:t,sendPrDecision:r,lifecycle:n,...i}){let o=df();if(e!==null)return(0,GC.jsx)(vir,{sessionId:e,transcript:t});let a=i.sessions.find(s=>s.id===i.activeId);return(0,GC.jsxs)(Ie,{sx:lPn,children:[o&&a!==void 0&&(0,GC.jsx)(Ie,{sx:cPn,children:(0,GC.jsx)(pQt,{session:a,lifecycle:n})}),(0,GC.jsx)(vQt,{sessionId:i.activeId,sessions:i.sessions,sendInput:i.sendInput,children:(0,GC.jsx)(fir,{...i,activeSession:a,sendPrDecision:r,showLastMessage:o})})]})}var Sir=$(V(),1);function Tir({socket:e}){let t=(0,xir.useMemo)(()=>({onRetry:e.retrySession,onRestart:e.restartSession,onDismiss:e.dismissSession,onSetAutoRun:e.setAutoRun,onSetAutoAdvance:e.setAutoAdvance}),[e.retrySession,e.restartSession,e.dismissSession,e.setAutoRun,e.setAutoAdvance]);return(0,Sir.jsx)(bir,{lifecycle:t,sessions:e.sessions,activeId:e.activeId,initialized:e.initialized,onOutput:e.onOutput,sendInput:e.sendInput,sendResize:e.sendResize,viewingTranscriptSessionId:e.viewingTranscriptSessionId,transcript:e.transcript,sendPrDecision:e.sendPrDecision})}function XIe(e,t,r){if(e==null)return;let n=Math.max(0,e-r),i=Math.max(0,t-n)/t;if(!(i<.05))return i}function hhe(e,t){let r=Math.max(0,e-t),n=Math.floor(r/86400),i=Math.floor(r%86400/3600),o=Math.floor(r%3600/60);return n>0?`${n}d ${i}h`:i>0?`${i}h ${o}m`:`${o}m`}function uPn(e,t,r,n){let i=XIe(t,r,n);if(i!=null)return e/i}function qC(e,t,r,n){let i=uPn(e,t,r,n);return i==null?"ok":i>100?"over":i>75?"warn":"ok"}var kE={five_hour:{label:"5h",seconds:18e3},seven_day:{label:"7d",seconds:604800,tint:{light:"rgba(0, 0, 0, 0.1)",dark:"rgba(255, 255, 255, 0.1)"}}};var hPn={ok:"success.main",warn:"warning.main",over:"error.main"};function jC(e){return hPn[e]}var NV=$(V(),1),fPn={ok:"success",warn:"warning",over:"error"};function Cir({percentage:e,level:t}){return(0,NV.jsxs)(Ie,{sx:{display:"flex",alignItems:"center",gap:1},children:[(0,NV.jsx)(L9,{variant:"determinate",value:Math.min(100,e),color:fPn[t],sx:{flexGrow:1,height:8,borderRadius:1}}),(0,NV.jsxs)(Ie,{sx:{minWidth:40,textAlign:"right",color:jC(t)},children:[Math.round(e),"%"]})]})}function wir(e){return e.avgContextPct==null?"\u2014":`${Math.round(e.avgContextPct)}%`}var dPn=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});function ZIe(e){return dPn.format(e)}var fhe=$(V(),1);function _ir({peak:e}){return(0,fhe.jsx)(Xn,{align:"right",sx:{whiteSpace:"nowrap"},children:(0,fhe.jsx)(Mn,{title:`Cycle started ${ZIe(new Date(e.createdAt))}`,children:(0,fhe.jsx)("span",{children:ZIe(new Date(e.resetsAt*1e3))})})})}var Eir=$(V(),1);function kir(){return(0,Eir.jsx)(An,{label:"reset",size:"small",color:"warning",variant:"outlined",title:"Quota reset mid-cycle \u2014 this is the peak reached before the reset.",sx:{ml:1}})}function Rir(e){return!e.tokensUp&&!e.tokensDown?"\u2014":`\u2191 ${l6(e.tokensUp)} \u2193 ${l6(e.tokensDown)}`}var Dg=$(V(),1);function Air({peak:e,now:t}){let{label:r,seconds:n,tint:i}=kE[e.window],o=qC(e.usedPercentage,e.resetsAt,n,t);return(0,Dg.jsxs)(Lm,{sx:a=>({backgroundColor:i?a.palette.mode==="dark"?i.dark:i.light:void 0}),children:[(0,Dg.jsxs)(Xn,{children:[r,e.resetDetected&&(0,Dg.jsx)(kir,{})]}),(0,Dg.jsx)(Xn,{sx:{minWidth:160},children:(0,Dg.jsx)(Cir,{percentage:e.usedPercentage,level:o})}),(0,Dg.jsx)(Xn,{align:"right",sx:{whiteSpace:"nowrap"},children:wir(e)}),(0,Dg.jsx)(Xn,{align:"right",sx:{whiteSpace:"nowrap"},children:e.phaseCount??0}),(0,Dg.jsx)(Xn,{align:"right",sx:{whiteSpace:"nowrap"},children:Rir(e)}),(0,Dg.jsx)(_ir,{peak:e})]})}var dhe=$(_e(),1);function fO(e){let[t,r]=(0,dhe.useState)(()=>Math.floor(Date.now()/1e3));return(0,dhe.useEffect)(()=>{let n=setInterval(()=>r(Math.floor(Date.now()/1e3)),e);return()=>clearInterval(n)},[e]),t}var Jl=$(V(),1);function Pir({peaks:e}){let t=fO(3e4);return(0,Jl.jsx)(eN,{component:ti,children:(0,Jl.jsxs)(jw,{size:"small",children:[(0,Jl.jsx)(tN,{sx:{"& th":{whiteSpace:"nowrap"}},children:(0,Jl.jsxs)(Lm,{children:[(0,Jl.jsx)(Xn,{children:"Window"}),(0,Jl.jsx)(Xn,{children:"Peak usage"}),(0,Jl.jsx)(Xn,{align:"right",children:(0,Jl.jsx)(Mn,{title:"Mean context-window usage across all readings in this rate-limit cycle \u2014 distinct from the Peak usage quota above.",children:(0,Jl.jsx)("span",{children:"Avg context"})})}),(0,Jl.jsx)(Xn,{align:"right",children:(0,Jl.jsx)(Mn,{title:"Number of phase readings behind the average.",children:(0,Jl.jsx)("span",{children:"Phases"})})}),(0,Jl.jsx)(Xn,{align:"right",children:"Tokens spent"}),(0,Jl.jsx)(Xn,{align:"right",children:"Cycle reset"})]})}),(0,Jl.jsx)(Yw,{children:e.map(r=>(0,Jl.jsx)(Air,{peak:r,now:t},`${r.window}-${r.resetsAt}-${r.segment}`))})]})})}var dO=$(_e(),1);function Lir(e,t){let r=(0,dO.useRef)(null),[n,i]=(0,dO.useState)();return(0,dO.useLayoutEffect)(()=>{e===t&&r.current&&i(r.current.offsetHeight)},[e,t]),{ref:r,height:n}}var YC=$(V(),1);function Mir({rows:e,total:t,page:r,pageSize:n,onPageChange:i}){let{ref:o,height:a}=Lir(e.length,n);return(0,YC.jsxs)(YC.Fragment,{children:[(0,YC.jsx)(Ie,{ref:o,sx:{minHeight:a},children:(0,YC.jsx)(Pir,{peaks:e})}),(0,YC.jsx)(Spe,{component:"div",count:t,page:r,rowsPerPage:n,rowsPerPageOptions:[n],onPageChange:(s,l)=>i(l)})]})}var QIe=$(V(),1),pPn=[{value:"all",label:"All"},{value:"five_hour",label:kE.five_hour.label},{value:"seven_day",label:kE.seven_day.label}];function Iir({window:e,onChange:t}){return(0,QIe.jsx)(np,{size:"small",exclusive:!0,value:e,onChange:(r,n)=>n&&t(n),"aria-label":"Filter peaks by rate-limit window",children:pPn.map(r=>(0,QIe.jsx)(cc,{value:r.value,children:r.label},r.value))})}var BV=$(_e(),1);var KC=$(_e(),1);async function Dir(e,t,r){let n=new URLSearchParams({page:String(e),pageSize:String(t)});r!=="all"&&n.set("window",r);let i=await fetch(`/api/usage/history?${n}`);if(!i.ok)throw new Error(`Failed to load usage history (HTTP ${i.status}).`);return i.json()}function Oir(e,t,r){let[n,i]=(0,KC.useState)([]),[o,a]=(0,KC.useState)(0),[s,l]=(0,KC.useState)(!1),[u,h]=(0,KC.useState)(!1),[f,d]=(0,KC.useState)(null);return(0,KC.useEffect)(()=>{let p=!1;return h(!0),Dir(e,t,r).then(m=>{p||(i(m.rows),a(m.total),l(!0),h(!1))},m=>{p||(d(m instanceof Error?m:new Error(String(m))),h(!1))}),()=>{p=!0}},[e,t,r]),{rows:n,total:o,loaded:s,fetching:u,error:f}}var JIe=30;function Nir(){let[e,t]=(0,BV.useState)(0),[r,n]=(0,BV.useState)("all"),i=Oir(e,JIe,r),{total:o}=i;return(0,BV.useEffect)(()=>{if(o===0)return;let s=Math.ceil(o/JIe)-1;e>s&&t(s)},[e,o]),{...i,page:e,setPage:t,window:r,selectWindow:s=>{n(s),t(0)},pageSize:JIe}}var XC=$(V(),1);function Bir(){let e=Nir(),{window:t,total:r,error:n}=e;if(n)throw n;return(0,XC.jsxs)(nm,{loading:!e.loaded,title:"Usage history",isEmpty:r===0&&t==="all",emptyMessage:"No usage peaks recorded yet.",children:[(0,XC.jsx)(Iir,{window:t,onChange:e.selectWindow}),(0,XC.jsx)(Ie,{sx:{height:4,my:1},children:e.fetching&&(0,XC.jsx)(L9,{})}),t!=="all"&&r===0?(0,XC.jsxs)(tt,{color:"text.secondary",align:"center",sx:{py:6},children:["No ",kE[t].label," usage peaks recorded yet."]}):(0,XC.jsx)(Mir,{rows:e.rows,total:r,page:e.page,pageSize:e.pageSize,onPageChange:e.setPage})]})}var Yo=$(V(),1);function mPn({socket:e}){return(0,Yo.jsx)(C9,{maxWidth:"md",sx:{py:3,px:2},children:(0,Yo.jsx)(pFt,{socket:e})})}function Fir({socket:e}){return(0,Yo.jsx)(S_,{children:(0,Yo.jsxs)(_l,{element:(0,Yo.jsx)(RUt,{socket:e}),children:[(0,Yo.jsx)(_l,{path:"sessions",element:(0,Yo.jsx)(Tir,{socket:e})}),(0,Yo.jsx)(_l,{path:"backlog/*",element:(0,Yo.jsx)(mPn,{socket:e})}),(0,Yo.jsx)(_l,{path:"news",element:(0,Yo.jsx)(ZZt,{})}),(0,Yo.jsx)(_l,{path:"usage",element:(0,Yo.jsx)(Bir,{})}),(0,Yo.jsx)(_l,{path:"backups",element:(0,Yo.jsx)(OUt,{})}),(0,Yo.jsx)(_l,{path:"config",element:(0,Yo.jsx)(yWt,{})}),(0,Yo.jsx)(_l,{path:"diff",element:(0,Yo.jsx)(xZt,{sessions:e.sessions,sendInput:e.sendInput})}),(0,Yo.jsx)(_l,{path:"file",element:(0,Yo.jsx)(jZt,{})}),(0,Yo.jsx)(_l,{path:"*",element:(0,Yo.jsx)(P0e,{to:"/sessions",replace:!0})})]})})}var xhe=$(_e(),1);var bhe=$(_e(),1);function $ir(e,t,r){if(!e)return"Select a repo to search files.";if(r.error)return"Couldn't search files in this repo.";if(!(r.files.length>0||r.loading))return t?"No matching files.":"No files in this repo."}var ZC=$(V(),1),gPn={display:"flex",gap:1,alignItems:"center",minWidth:0},yPn={display:"flex",gap:1,alignItems:"baseline",minWidth:0,overflow:"hidden"},vPn={fontFamily:"monospace",fontSize:13,whiteSpace:"nowrap"},bPn={fontFamily:"monospace",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function xPn(e){let t=e.lastIndexOf("/");return t===-1?{dir:"",basename:e}:{dir:e.slice(0,t),basename:e.slice(t+1)}}function zir({files:e,highlight:t,onHighlight:r,onSelect:n}){return(0,ZC.jsx)(Ch,{dense:!0,sx:{py:0},children:e.map((i,o)=>{let{dir:a,basename:s}=xPn(i);return(0,ZC.jsxs)(ui,{selected:o===t,onMouseEnter:()=>r(o),onClick:()=>n(i),sx:gPn,children:[(0,ZC.jsx)(WD,{path:i}),(0,ZC.jsxs)(Ie,{sx:yPn,children:[(0,ZC.jsx)(tt,{component:"span",sx:vPn,children:s}),(0,ZC.jsx)(tt,{component:"span",color:"text.secondary",sx:bPn,children:a})]})]},i)})})}var phe=$(V(),1),TPn={maxHeight:420,overflowY:"auto"},SPn={px:2,py:2,fontSize:13};function Uir({message:e,files:t,highlight:r,onHighlight:n,onSelect:i}){return(0,phe.jsx)(Ie,{sx:TPn,children:e?(0,phe.jsx)(tt,{color:"text.secondary",sx:SPn,children:e}):(0,phe.jsx)(zir,{files:t,highlight:r,onHighlight:n,onSelect:i})})}var Hir=$(V(),1);function mhe({inputRef:e,value:t,onChange:r,onKeyDown:n,placeholder:i,autoFocus:o}){return(0,Hir.jsx)(Jo,{autoFocus:o,inputRef:e,value:t,onChange:a=>r(a.target.value),onKeyDown:n,placeholder:i,size:"small",fullWidth:!0,slotProps:{input:{sx:{fontSize:12}}},sx:{p:.5}})}var ghe=$(_e(),1),Wir={files:[],loading:!1,error:!1};function Vir(e,t){let[r,n]=(0,ghe.useState)(Wir);return(0,ghe.useEffect)(()=>{if(!e){n(Wir);return}let i=!1;return n(a=>({...a,loading:!0})),(async()=>{try{let a=await fetch(`/api/files?cwd=${encodeURIComponent(e)}&q=${encodeURIComponent(t)}`);if(!a.ok)throw new Error(`HTTP ${a.status}`);let s=await a.json();if(i)return;n({files:Array.isArray(s.files)?s.files:[],loading:!1,error:!1})}catch{i||n({files:[],loading:!1,error:!0})}})(),()=>{i=!0}},[e,t]),r}var yhe=$(_e(),1);function vhe(e,t,r,n){let[i,o]=(0,yhe.useState)(0);return(0,yhe.useEffect)(()=>{o(0)},[t]),{highlight:i,setHighlight:o,onKeyDown:s=>{let l=e.length;if(s.key==="ArrowDown")s.preventDefault(),l>0&&o(u=>(u+1)%l);else if(s.key==="ArrowUp")s.preventDefault(),l>0&&o(u=>(u-1+l)%l);else if(s.key==="Enter"){s.preventDefault();let u=e[i];u&&(r(u),n())}else s.key==="Escape"&&(s.preventDefault(),n())}}}var FV=$(V(),1),CPn={mt:6,alignSelf:"flex-start"};function Gir({onClose:e}){let{worktreeCwd:t}=Oa(),[r,n]=(0,bhe.useState)(""),i=Vir(t,r),o=ao(),a=(0,bhe.useRef)(null),s=d=>o(`/file?${new URLSearchParams(t?{path:d,cwd:t}:{path:d})}`),{highlight:l,setHighlight:u,onKeyDown:h}=vhe(i.files,r,s,e),f=d=>{s(d),e()};return(0,FV.jsxs)(Th,{open:!0,onClose:e,maxWidth:"sm",fullWidth:!0,slotProps:{paper:{sx:CPn},transition:{onEntered:()=>a.current?.focus()}},children:[(0,FV.jsx)(mhe,{autoFocus:!0,inputRef:a,value:r,onChange:n,onKeyDown:h,placeholder:"Search files by name..."}),(0,FV.jsx)(Uir,{message:$ir(t,r,i),files:i.files,highlight:l,onHighlight:u,onSelect:f})]})}var jir=$(_e(),1);var qir=!0;function Yir(e){(0,jir.useEffect)(()=>{let t=r=>{uhe(r)&&(r.preventDefault(),e())};return globalThis.addEventListener("keydown",t,qir),()=>globalThis.removeEventListener("keydown",t,qir)},[e])}var Xir=$(V(),1);function Kir(){let[e,t]=(0,xhe.useState)(!1);return Yir((0,xhe.useCallback)(()=>t(!0),[])),e?(0,Xir.jsx)(Gir,{onClose:()=>t(!1)}):null}var The=$(V(),1);function Zir({notice:e,onClose:t,onView:r}){let n=e?.sessionId??null;return(0,The.jsx)(Yc,{open:e!==null,autoHideDuration:6e3,onClose:t,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:(0,The.jsx)(Xo,{severity:"success",variant:"filled",onClose:t,action:n!==null?(0,The.jsx)(xr,{color:"inherit",size:"small",onClick:()=>r(n),children:"View"}):void 0,children:e?.message})})}var She=$(V(),1);function Qir({reconnecting:e}){return(0,She.jsx)(Yc,{open:e,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:(0,She.jsx)(Xo,{severity:"info",variant:"filled",icon:(0,She.jsx)(no,{size:16,color:"inherit"}),children:"Reconnecting\u2026"})})}var yx=$(V(),1);function Jir({socket:e,onViewLaunchedSession:t}){return(0,yx.jsxs)(yx.Fragment,{children:[(0,yx.jsx)(Kir,{}),(0,yx.jsx)(Qir,{reconnecting:e.reconnecting}),(0,yx.jsx)(pf,{error:e.error,onClose:e.clearError}),(0,yx.jsx)(Zir,{notice:e.success,onClose:e.clearSuccess,onView:t})]})}var pO=$(V(),1),wPn=["/sessions","/backlog","/news"];function eor(){let e=Cs(),t=ao(),r=wPn.findIndex(i=>e.pathname.startsWith(i)),n=i=>{e.pathname!==i&&t(i)};return(0,pO.jsxs)(nN,{value:r===-1?0:r,textColor:"inherit",indicatorColor:"secondary",children:[(0,pO.jsx)(Vx,{label:"Sessions",onClick:()=>n("/sessions")}),(0,pO.jsx)(Vx,{label:"Backlog",onClick:()=>n("/backlog")}),(0,pO.jsx)(Vx,{label:"News",onClick:()=>n("/news")})]})}var whe=$(_e(),1),Che=$(V(),1),_Pn={color:"inherit"};function tor({cwd:e}){let[t,r]=(0,whe.useState)(null);return(0,whe.useEffect)(()=>{if(!e){r(null);return}let n=!1;return(async()=>{try{let o=await(await fetch(`/api/github-url?cwd=${encodeURIComponent(e)}`)).json();n||r(o?.url??null)}catch{n||r(null)}})(),()=>{n=!0}},[e]),t?(0,Che.jsx)(Mn,{title:"Open in GitHub",children:(0,Che.jsx)(gr,{sx:_Pn,onClick:()=>window.open(t,"_blank"),children:(0,Che.jsx)(Use,{})})}):null}var nor=$(_e(),1);var _he=$(V(),1);function ror({window:e,windowSeconds:t,fallbackLabel:r,now:n}){let i=e?.used_percentage;if(i==null)return null;let o=qC(i,e?.resets_at,t,n),a=e?.resets_at!=null?hhe(e.resets_at,n):r;return(0,_he.jsxs)(Ie,{component:"span",children:[(0,_he.jsxs)(Ie,{component:"span",sx:{color:jC(o)},children:[Math.round(i),"%"]})," ",(0,_he.jsxs)(Ie,{component:"span",sx:{color:"text.secondary"},children:["(",a,")"]})]})}var QC=$(V(),1);function ior({rateLimits:e}){let t=fO(3e4),r=[{window:e.five_hour,windowSeconds:18e3,fallbackLabel:"5h"},{window:e.seven_day,windowSeconds:604800,fallbackLabel:"7d"}].filter(n=>n.window?.used_percentage!=null);return(0,QC.jsx)(QC.Fragment,{children:r.map((n,i)=>(0,QC.jsxs)(nor.Fragment,{children:[i>0?(0,QC.jsx)(Ie,{component:"span",sx:{color:"text.secondary",mr:.5},children:","}):null,(0,QC.jsx)(ror,{window:n.window,windowSeconds:n.windowSeconds,fallbackLabel:n.fallbackLabel,now:t})]},n.fallbackLabel))})}function kPn(e){if(e==="over")return{level:"warn",boundary:100};if(e==="warn")return{level:"ok",boundary:75}}function EPn(e){if(e==="ok")return{level:"warn",boundary:75};if(e==="warn")return{level:"over",boundary:100}}function RPn(e,t,r,n){if(e>=t)return;let i=e/t;return Math.round(r-n*(1-i))}function sor(e,t,r,n){if(t==null)return{kind:"unprojectable"};let i=XIe(t,r,n);if(i==null)return{kind:"unprojectable"};let o=qC(e,t,r,n),a=kPn(o),s=EPn(o);return{kind:"projected",recovery:a&&{level:a.level,pct:a.boundary*i,at:RPn(e,a.boundary,t,r)},worse:s&&{level:s.level,pct:s.boundary*i}}}function lor(e,t){return e.at==null?"not before reset":`${e.level==="ok"?"green":"under"} in ${hhe(e.at,t)}`}var Og=$(V(),1);function eDe({direction:e,threshold:t}){let r=e==="back",n={display:"inline-flex",gap:.5,minWidth:"6ch",justifyContent:r?"flex-end":"flex-start"};if(!t)return(0,Og.jsx)(Ie,{component:"span",sx:n});let i=(0,Og.jsx)(Ie,{component:"span",sx:{opacity:.6},children:r?"\u2190":"\u2192"}),o=(0,Og.jsxs)(Ie,{component:"span",sx:{color:jC(t.level)},children:[Math.round(t.pct),"%"]});return(0,Og.jsx)(Ie,{component:"span",sx:n,children:r?(0,Og.jsxs)(Og.Fragment,{children:[o,i]}):(0,Og.jsxs)(Og.Fragment,{children:[i,o]})})}var JC=$(V(),1);function cor({label:e,pct:t,resetsAt:r,windowSeconds:n,now:i}){let o=qC(t,r,n,i),a=sor(t,r,n,i),s=a.kind==="projected"?a:void 0;return(0,JC.jsxs)(Ie,{sx:{display:"flex",alignItems:"baseline",gap:.75},children:[(0,JC.jsx)(Ie,{component:"span",sx:{minWidth:"2ch"},children:e}),(0,JC.jsx)(eDe,{direction:"back",threshold:s?.recovery}),(0,JC.jsxs)(Ie,{component:"span",sx:{minWidth:"4ch",textAlign:"right",color:jC(o)},children:[Math.round(t),"%"]}),(0,JC.jsx)(eDe,{direction:"forward",threshold:s?.worse}),(0,JC.jsx)(Ie,{component:"span",sx:{opacity:.6},children:s?s.recovery&&lor(s.recovery,i):"no projection yet"})]})}function uor(e){return[{label:"5h",window:e.five_hour,windowSeconds:18e3},{label:"7d",window:e.seven_day,windowSeconds:604800}].flatMap(t=>t.window?.used_percentage==null?[]:[{label:t.label,pct:t.window.used_percentage,resetsAt:t.window.resets_at,windowSeconds:t.windowSeconds}])}var $V=$(V(),1),tDe="Claude account usage (5h / 7d windows) \u2014 view history";function hor({rateLimits:e}){let t=fO(3e4);return(0,$V.jsxs)(Ie,{sx:{fontFamily:"monospace",fontSize:12},children:[uor(e).map(r=>(0,$V.jsx)(cor,{label:r.label,pct:r.pct,resetsAt:r.resetsAt,windowSeconds:r.windowSeconds,now:t},r.label)),(0,$V.jsx)(Ie,{sx:{mt:.5,opacity:.6},children:tDe})]})}var zV=$(V(),1),APn={display:"flex",alignItems:"center",ml:2,fontFamily:"monospace",fontSize:13};function PPn(e){return e?.five_hour?.used_percentage!=null||e?.seven_day?.used_percentage!=null}function dor({rateLimits:e}){let t=PPn(e);return(0,zV.jsx)(Mn,{title:t?(0,zV.jsx)(hor,{rateLimits:e}):tDe,children:(0,zV.jsx)(Qo,{component:Bm,to:"/usage",underline:"hover",color:"inherit",sx:APn,children:t?(0,zV.jsx)(ior,{rateLimits:e}):"Usage"})})}var por=$(V(),1),mor=Tt((0,por.jsx)("path",{d:"M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4z"}),"Refresh");var bx=$(_e(),1);var mO={target:"both",label:"Restart daemon",message:"This restarts the sessions daemon and the web server, then reloads the page once the server is back."};function gor(e){return fetch(`/api/restart?target=${e}`,{method:"POST"})}var vx=$(_e(),1);var LPn="/api/session-layout";async function MPn(){try{return(await fetch(LPn,{cache:"no-store"})).ok}catch{return!1}}async function yor(e){let t=0;for(;!e();){if(t=await MPn()?t+1:0,t>=2)return!e();await new Promise(r=>setTimeout(r,300))}return!1}function IPn(){return{sawDisconnect:!1,waiting:!1,abandoned:!0}}function vor(e,t,r){let n=(0,vx.useRef)(IPn()),i=(0,vx.useRef)(r);i.current=r,(0,vx.useEffect)(()=>{let s=n.current;if(!(!e||s.abandoned)){if(t){s.sawDisconnect=!0;return}!s.sawDisconnect||s.waiting||(s.waiting=!0,yor(()=>s.abandoned).then(l=>{l&&i.current()}))}},[e,t]);let o=(0,vx.useCallback)(()=>{n.current.abandoned=!0},[]),a=(0,vx.useCallback)(()=>{n.current.abandoned=!0,n.current={sawDisconnect:!1,waiting:!1,abandoned:!1}},[]);return(0,vx.useEffect)(()=>o,[o]),{arm:a,abandon:o}}var DPn=15e3;function gO(e,t,r){let[n,i]=(0,bx.useState)(!1),[o,a]=(0,bx.useState)(null),s=(0,bx.useRef)(void 0),{arm:l,abandon:u}=vor(n,t,()=>{clearTimeout(s.current),r?.(),globalThis.location.reload()});(0,bx.useEffect)(()=>()=>clearTimeout(s.current),[]);let h=(0,bx.useCallback)(async()=>{i(!0),l(),s.current=setTimeout(()=>{u(),i(!1),a("Web server did not come back")},DPn);try{if(!(await gor(e)).ok)throw new Error("restart failed")}catch{u(),clearTimeout(s.current),i(!1),a("Failed to restart web server")}},[e,l,u]);return{pending:n,error:o,clearError:()=>a(null),restart:h}}var Ng=$(V(),1),OPn={color:"inherit",mr:1.5};function bor({reconnecting:e}){let{pending:t,error:r,clearError:n,restart:i}=gO("webserver",e);return(0,Ng.jsxs)(Ng.Fragment,{children:[(0,Ng.jsx)(Mn,{title:"Restart web server",children:(0,Ng.jsx)("span",{children:(0,Ng.jsx)(gr,{sx:OPn,disabled:t,onClick:i,children:t?(0,Ng.jsx)(no,{size:24}):(0,Ng.jsx)(mor,{})})})}),(0,Ng.jsx)(pf,{error:r,onClose:n})]})}var yO=$(_e(),1);var khe=$(_e(),1);var Ehe=$(V(),1);function xor({cwd:e,selected:t,highlighted:r,onHover:n,onSelect:i}){let o=(0,khe.useRef)(null);return(0,khe.useEffect)(()=>{r&&o.current?.scrollIntoView({block:"nearest"})},[r]),(0,Ehe.jsxs)(ui,{ref:o,selected:t,title:e,onClick:i,onMouseEnter:n,sx:{fontSize:12,display:"flex",justifyContent:"space-between",gap:1,...r&&{bgcolor:"action.hover"}},children:[UV(e),YS(e)&&(0,Ehe.jsx)(US,{})]})}var rDe=$(V(),1);function Tor({repos:e,selected:t,highlight:r,onHighlight:n,onSelect:i}){return(0,rDe.jsx)(Ch,{dense:!0,children:e.map((o,a)=>(0,rDe.jsx)(xor,{cwd:o,selected:o===t,highlighted:a===r,onHover:()=>n(a),onSelect:()=>i(o)},o))})}var HV=$(V(),1);function UV(e){let t=e.includes("\\")?"\\":"/";return e.split(t).filter(Boolean).pop()??e}var NPn={...QS};function Sor({repos:e,selected:t,onSelect:r,close:n}){let[i,o]=(0,yO.useState)(""),a=(0,yO.useRef)(null);(0,yO.useEffect)(()=>{a.current?.focus()},[]);let s=i.trim().toLowerCase(),l=s?e.filter(p=>p.toLowerCase().includes(s)):e,{highlight:u,setHighlight:h,onKeyDown:f}=vhe(l,s,r,n);return(0,HV.jsxs)(ti,{elevation:4,sx:NPn,children:[(0,HV.jsx)(mhe,{inputRef:a,value:i,onChange:o,onKeyDown:f,placeholder:"Filter repos..."}),(0,HV.jsx)(Tor,{repos:l,selected:t,highlight:u,onHighlight:h,onSelect:p=>{r(p),n()}})]})}var vO=$(V(),1);function BPn(e){return e?YS(e)?(0,vO.jsxs)("span",{style:{display:"flex",flexGrow:1,alignItems:"center",justifyContent:"space-between",gap:6,minWidth:0},children:[UV(e),(0,vO.jsx)(US,{})]}):UV(e):"Select repo..."}function Cor({repos:e,selected:t,onSelect:r}){return(0,vO.jsx)(My,{label:BPn(t),children:n=>(0,vO.jsx)(Sor,{repos:e,selected:t,onSelect:r,close:n})})}var wor=$(_e(),1);var nDe=$(V(),1);function Rhe({disabled:e,onSubmit:t,label:r="prompt",allowEmpty:n=!1}){let[i,o]=(0,wor.useState)("");return(0,nDe.jsx)(My,{label:r,disabled:e,onDefaultAction:n?()=>t(""):void 0,children:a=>(0,nDe.jsx)(QI,{value:i,onChange:o,onSubmit:()=>{!n&&!i.trim()||(t(i),o(""),a())}})})}var EE=$(V(),1),FPn={textTransform:"none",fontSize:11,fontWeight:600};function _or({onSelect:e,disabled:t=!1,children:r}){return(0,EE.jsxs)(EE.Fragment,{children:[p7e.filter(n=>n.nav&&n.prompt).map(n=>(0,EE.jsx)(Rhe,{label:n.label,allowEmpty:!0,disabled:t,onSubmit:i=>e(n.value,i)},n.value)),r,p7e.filter(n=>n.nav&&!n.prompt).map(n=>(0,EE.jsx)(xr,{size:"small",variant:"outlined",disabled:t,onClick:()=>e(n.value),sx:FPn,children:n.label},n.value))]})}var iDe=$(_e(),1);function kor(e){let t=["claude"];return e.exposeCodexActions&&t.push("codex"),e.exposePiActions&&t.push("pi"),t}var Ahe=$(V(),1),$Pn={"& .MuiFormControlLabel-label":{fontSize:12}};function Eor({choices:e,value:t,onChange:r}){return(0,Ahe.jsx)(mpe,{row:!0,value:t,onChange:n=>r(n.target.value),children:e.map(n=>(0,Ahe.jsx)(Df,{value:n,control:(0,Ahe.jsx)(dpe,{size:"small"}),label:zS(n),sx:$Pn},n))})}var Phe=$(V(),1);function Ror({cwd:e,disabled:t,onCreate:r,onCreateHarness:n}){let i=kor(nse()),[o,a]=(0,iDe.useState)(""),[s,l]=(0,iDe.useState)("claude"),u=h=>{s==="claude"?r(h,e):n(s,h,e)};return(0,Phe.jsx)(My,{label:"prompt",disabled:t,onDefaultAction:()=>u(""),children:h=>(0,Phe.jsx)(QI,{value:o,onChange:a,header:i.length>1?(0,Phe.jsx)(Eor,{choices:i,value:s,onChange:l}):void 0,onSubmit:()=>{u(o),a(""),h()}})})}var RE=$(V(),1);function Aor({cwd:e,disabled:t,onCreate:r,onCreateDesign:n,onCreateHarness:i}){return(0,RE.jsxs)(RE.Fragment,{children:[(0,RE.jsx)(Ror,{cwd:e,disabled:t,onCreate:r,onCreateHarness:i}),(0,RE.jsx)(Rhe,{label:"design",allowEmpty:!0,disabled:t,onSubmit:o=>n(o,e)})]})}var Nor=$(_e(),1);var WV=$(_e(),1);function Lhe(e){let[t,r]=(0,WV.useState)([]),[n,i]=(0,WV.useState)(!0);return(0,WV.useEffect)(()=>{if(!e){r([]),i(!1);return}let o=!1;return i(!0),fetch(`/api/pr-list?cwd=${encodeURIComponent(e)}`).then(a=>a.json()).then(a=>{o||(r(Array.isArray(a?.prs)?a.prs:[]),i(!1))}).catch(()=>{o||(r([]),i(!1))}),()=>{o=!0}},[e]),{prs:t,loading:n}}var Fd=$(V(),1);function Lor({cwd:e,onPick:t}){let{prs:r,loading:n}=Lhe(e);return(0,Fd.jsx)(ti,{elevation:4,sx:{...QS,left:"auto",width:320},children:n?(0,Fd.jsx)(Por,{text:"Loading open PRs\u2026"}):r.length===0?(0,Fd.jsx)(Por,{text:"No open PRs"}):(0,Fd.jsx)(Ch,{dense:!0,disablePadding:!0,children:r.map(i=>(0,Fd.jsx)(zPn,{pr:i,onPick:t},i.number))})})}function zPn({pr:e,onPick:t}){return(0,Fd.jsx)(ui,{onMouseDown:r=>r.preventDefault(),onClick:()=>t(e),sx:{alignItems:"flex-start",py:.75,whiteSpace:"normal"},children:(0,Fd.jsxs)(ir,{spacing:.25,sx:{minWidth:0},children:[(0,Fd.jsx)(tt,{sx:{fontSize:13,lineHeight:1.3,fontWeight:500},children:e.title}),(0,Fd.jsxs)(tt,{sx:{fontSize:11,color:"text.secondary"},children:["#",e.number," \xB7 ",e.author," \xB7 ",w2(e.createdAt)]})]})})}function Por({text:e}){return(0,Fd.jsx)(Ie,{sx:{p:1.5},children:(0,Fd.jsx)(tt,{sx:{fontSize:13,color:"text.secondary"},children:e})})}var Ior=$(V(),1);function Mor({cwd:e,onPick:t}){return(0,Ior.jsx)(Lor,{cwd:e,onPick:t})}var Dor=$(_e(),1);var mu=$(V(),1);function Oor({pr:e,onSelect:t,onCancel:r}){let[n,i]=(0,Dor.useState)(YH);return(0,mu.jsxs)(Th,{open:!0,onClose:r,maxWidth:"xs",fullWidth:!0,children:[(0,mu.jsxs)(ep,{sx:{fontSize:15},children:["Review #",e.number,": ",e.title]}),(0,mu.jsx)(Jd,{sx:{px:0},children:(0,mu.jsxs)(Ch,{children:[Hse.map(({label:o,args:a})=>(0,mu.jsx)(ui,{onClick:()=>t([...a,...Wse(n)]),children:o},o)),(0,mu.jsx)(is,{}),(0,mu.jsx)(Vse,{value:n,onChange:i}),(0,mu.jsx)(is,{}),(0,mu.jsx)(ui,{onClick:()=>t(["review","--checkout-only"]),children:"Checkout"}),(0,mu.jsx)(ui,{onClick:()=>t(["review-pr-comments"]),children:"Address Comments"}),(0,mu.jsx)(ui,{onClick:()=>t(["fix-conflict"]),children:"Fix conflicts (merge)"}),(0,mu.jsx)(ui,{onClick:()=>t(["fix-conflict","--rebase"]),children:"Fix conflicts (rebase)"})]})}),(0,mu.jsx)(Qd,{children:(0,mu.jsx)(xr,{onClick:r,children:"Cancel"})})]})}var ew=$(V(),1);function Bor({cwd:e,disabled:t,onSelect:r}){let{prs:n,loading:i}=Lhe(e),[o,a]=(0,Nor.useState)(null);return i||n.length===0?null:(0,ew.jsxs)(ew.Fragment,{children:[(0,ew.jsx)(My,{label:"prs",disabled:t,children:s=>(0,ew.jsx)(Mor,{cwd:e,onPick:l=>{a(l),s()}})}),o&&(0,ew.jsx)(Oor,{pr:o,onSelect:s=>{r(o,s),a(null)},onCancel:()=>a(null)})]})}var bO=$(V(),1);function For({onStartRun:e,cwd:t}){let r=Xse(t);return!t||r.length===0?null:(0,bO.jsx)(My,{label:"server",children:n=>(0,bO.jsx)(ti,{elevation:4,sx:{...QS,left:"auto",width:200},children:(0,bO.jsx)(Ch,{dense:!0,disablePadding:!0,children:r.map(i=>(0,bO.jsx)(ui,{onMouseDown:o=>o.preventDefault(),onClick:()=>{e(i.name,t),n()},sx:{py:.75},children:(0,bO.jsx)(tt,{sx:{fontSize:13},children:i.name})},i.name))})})})}var AE=$(V(),1);function $or({onCreate:e,onCreateDesign:t,onCreateHarness:r,onCreateAssist:n,onStartRun:i}){let{selectedCwd:o}=Oa(),a=!o;return(0,AE.jsxs)(ir,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:[(0,AE.jsxs)(_or,{disabled:a,onSelect:(s,l)=>q$t(s,o,n,()=>{},l),children:[(0,AE.jsx)(Aor,{cwd:o,disabled:a,onCreate:e,onCreateDesign:t,onCreateHarness:r}),(0,AE.jsx)(Bor,{cwd:o,disabled:a,onSelect:(s,l)=>n([...l,String(s.number)],o,Gse(s))})]}),(0,AE.jsx)(For,{onStartRun:i,cwd:o})]})}var $d=$(V(),1),UPn={minHeight:48,pl:1,pr:14},HPn={width:240,ml:2};function zor({socket:e,selection:t}){let{collapsed:r,onToggleCollapsed:n}=rD();return(0,$d.jsxs)(Kw,{variant:"dense",disableGutters:!0,sx:UPn,children:[r&&(0,$d.jsx)(ole,{collapsed:r,onToggleCollapsed:n}),(0,$d.jsx)(bor,{reconnecting:e.reconnecting}),(0,$d.jsx)(eor,{}),(0,$d.jsx)(Ie,{sx:HPn,children:(0,$d.jsx)(Cor,{repos:t.repos,selected:t.selectedCwd,onSelect:t.setSelectedCwd})}),(0,$d.jsxs)(Ie,{sx:{display:"flex",ml:1,mr:2},children:[(0,$d.jsx)(Yse,{cwd:t.selectedCwd}),(0,$d.jsx)(tor,{cwd:t.selectedCwd})]}),(0,$d.jsx)($or,{onCreate:e.createSession,onCreateDesign:e.createDesignSession,onCreateHarness:e.createHarnessSession,onCreateAssist:e.createAssistSession,onStartRun:e.startRun}),(0,$d.jsx)(dor,{rateLimits:e.rateLimits})]})}var Dhe=$(_e(),1);var Uor=$(V(),1),Hor=Tt((0,Uor.jsx)("path",{d:"m12 16.5 4-4h-3v-9h-2v9H8zm9-13h-6v1.99h6v14.03H3V5.49h6V3.5H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2v-14c0-1.1-.9-2-2-2"}),"SystemUpdateAlt");var Wor=$(V(),1),Vor=Tt((0,Wor.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 Gor=$(V(),1),qor=Tt((0,Gor.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 oDe=$(V(),1);function jor({mode:e}){return e==="dark"?(0,oDe.jsx)(qor,{fontSize:"small"}):(0,oDe.jsx)(Vor,{fontSize:"small"})}var ph=$(V(),1);function Yor({mode:e,onToggleColorMode:t,onRestart:r,onUpdate:n}){return[(0,ph.jsxs)(ui,{onClick:t,children:[(0,ph.jsx)(I9,{children:(0,ph.jsx)(jor,{mode:e})}),(0,ph.jsx)(O9,{children:"Toggle dark mode"})]},"color-mode"),(0,ph.jsx)(is,{},"restart-divider"),(0,ph.jsxs)(ui,{onClick:r,children:[(0,ph.jsx)(I9,{children:(0,ph.jsx)(Dse,{fontSize:"small"})}),(0,ph.jsx)(O9,{children:mO.label})]},"restart"),(0,ph.jsxs)(ui,{onClick:n,children:[(0,ph.jsx)(I9,{children:(0,ph.jsx)(Hor,{fontSize:"small"})}),(0,ph.jsx)(O9,{children:"Update assist"})]},"update")]}var PE=$(V(),1);function Kor({reconnecting:e,onClose:t}){let{pending:r,error:n,clearError:i,restart:o}=gO(mO.target,e);return(0,PE.jsxs)(PE.Fragment,{children:[(0,PE.jsx)(na,{title:mO.label,message:mO.message,confirmLabel:"Restart",busy:r,onConfirm:()=>{o()},onCancel:t}),(0,PE.jsx)(pf,{error:n,onClose:i})]})}var Zor=$(V(),1);function Xor({onConfirm:e,onClose:t}){return(0,Zor.jsx)(na,{title:"Update assist",message:"This starts a new session running 'assist update'. Its output will appear in the terminal.",confirmLabel:"Update",onConfirm:()=>{e(),t()},onCancel:t})}var LE=$(V(),1);function Qor({restarting:e,reconnecting:t,onCloseRestart:r,updating:n,onCloseUpdate:i}){let{launchAssist:o,armUpdateReload:a}=yp();return(0,LE.jsxs)(LE.Fragment,{children:[e&&(0,LE.jsx)(Kor,{reconnecting:t,onClose:r}),n&&(0,LE.jsx)(Xor,{onConfirm:()=>{a(),o(["update"])},onClose:i})]})}var Jor=$(V(),1),ear=Tt((0,Jor.jsx)("path",{d:"M3 18h18v-2H3zm0-5h18v-2H3zm0-7v2h18V6z"}),"Menu");var tar=$(V(),1),rar=Tt((0,tar.jsx)("path",{d:"M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6"}),"Settings");var Mhe=$(V(),1);function nar(){let e=ao();return(0,Mhe.jsx)(Mn,{title:"Config",children:(0,Mhe.jsx)(gr,{size:"small",sx:{color:"inherit"},"aria-label":"Config",onClick:()=>e("/config"),children:(0,Mhe.jsx)(rar,{fontSize:"small"})})})}var aDe=$(V(),1),iar=Tt([(0,aDe.jsx)("path",{d:"M12 5.99 19.53 19H4.47zM12 2 1 21h22z"},"0"),(0,aDe.jsx)("path",{d:"M13 16h-2v2h2zm0-6h-2v5h2z"},"1")],"WarningAmber");var VV="0.616.2";var Ihe=$(_e(),1),sDe=(0,Ihe.createContext)(null);function oar(){return(0,Ihe.useContext)(sDe)}var tw=$(V(),1);function aar(){let e=oar();return VV?(0,tw.jsxs)(tw.Fragment,{children:[(0,tw.jsxs)(tt,{variant:"caption",sx:{opacity:.4,userSelect:"none",lineHeight:1},children:["v",VV]}),e&&e!==VV&&(0,tw.jsx)(Mn,{title:`Daemon is running v${e}, but this page was served by v${VV}. Restart the daemon to match.`,children:(0,tw.jsx)(iar,{fontSize:"small",color:"warning","aria-label":"Version mismatch"})})]}):null}var ME=$(V(),1);function sar({open:e,onOpen:t}){return(0,ME.jsxs)(Ie,{sx:{position:"fixed",top:8,right:16,zIndex:r=>r.zIndex.drawer+2,display:"flex",alignItems:"center",gap:.5,color:"inherit"},children:[(0,ME.jsx)(aar,{}),(0,ME.jsx)(nar,{}),(0,ME.jsx)(gr,{onClick:r=>t(r.currentTarget),size:"small",sx:{color:"inherit"},"aria-label":"Open menu","aria-haspopup":"true","aria-expanded":e?"true":void 0,children:(0,ME.jsx)(ear,{fontSize:"small"})})]})}var rw=$(V(),1);function lar({mode:e,toggle:t,reconnecting:r}){let[n,i]=(0,Dhe.useState)(null),[o,a]=(0,Dhe.useState)(!1),[s,l]=(0,Dhe.useState)(!1),u=!!n,h=()=>i(null);return(0,rw.jsxs)(rw.Fragment,{children:[(0,rw.jsx)(sar,{open:u,onOpen:i}),(0,rw.jsx)(tp,{anchorEl:n,open:u,onClose:h,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:Yor({mode:e,onToggleColorMode:()=>{t(),h()},onRestart:()=>{h(),a(!0)},onUpdate:()=>{h(),l(!0)}})}),(0,rw.jsx)(Qor,{restarting:o,reconnecting:r,onCloseRestart:()=>a(!1),updating:s,onCloseUpdate:()=>l(!1)})]})}var har=$(_e(),1);var uar=$(V(),1);function car({conflict:e,onConfirm:t,onCancel:r}){let{name:n,cwd:i,port:o}=e.existing,a=Jp(i),s=o?` on port ${o}`:"",l=a?` in ${a}`:"";return(0,uar.jsx)(na,{title:"Replace running server?",message:`"${n}" is already serving${s}${l}. Replace it \u2014 stop the running server and start this one?`,confirmLabel:"Replace",confirmColor:"error",onConfirm:t,onCancel:r})}var Ohe=$(V(),1);function far({socket:e,children:t}){let{serverConflict:r,clearServerConflict:n,retrySession:i,stopSession:o,startRun:a,discardSession:s}=e,l=(0,har.useMemo)(()=>({onStop:o,onStart:a,onDiscard:s}),[o,a,s]),u=()=>{r&&(r.runName?a(r.runName,r.cwd,!0,r.launchedFrom):r.sessionId&&i(r.sessionId,!0),n())};return(0,Ohe.jsxs)(c7e.Provider,{value:l,children:[t,r&&(0,Ohe.jsx)(car,{conflict:r,onConfirm:u,onCancel:n})]})}var Nhe=$(_e(),1);function dar(e,t,r){if(!t)return null;let n=e[t];if(!n)return null;let i=r.find(o=>o.id===n);return!i||ff(i)!==t?null:n}function xO(e,t,r){if(e)return t.find(n=>n.id===e)??r.find(n=>n.sessionId===e)}function par({selectedCwd:e,selectedCardId:t,sessions:r,history:n,activeByRepo:i,onSelect:o}){let a=xO(t,r,n),s=a&&ff(a),l=!!(s&&s===e),u=dar(i,e,r),h=(0,Nhe.useRef)(t);(0,Nhe.useEffect)(()=>{let f=h.current!==t&&!!s;h.current=t,!(f||l||!u)&&o(u)},[t,s,l,u,o])}var IE=$(_e(),1);function mar(e,t,r,n){let i=xO(e,t,r);return i?.cwd&&ff(i)===n?i.cwd:n}function gar(e,t){let r=new Set,n=new Set,i=[];for(let o of t){if(o.cwdMissing)continue;let a=HS(o),s=ff(o);!a||!s||r.has(a)||n.has(s)||(r.add(a),n.add(s),i.push(s))}return e&&!r.has(fse(e,t))&&!n.has(e)&&i.unshift(e),i}var yar=$(_e(),1);function Bhe(e,t,r){let n=xO(e,t,r);return n&&ff(n)}function bar(e,t,r,n){let i=Bhe(e,t,r);(0,yar.useEffect)(()=>{i&&n(i)},[i,n])}function xar(e,t,r,n){let[i,o]=(0,IE.useState)(e);(0,IE.useEffect)(()=>{e&&!i&&o(e)},[e,i]),bar(r,n,t,o);let a=(0,IE.useMemo)(()=>gar(e,t),[e,t]),s=mar(r,n,t,i);return(0,IE.useMemo)(()=>({repos:a,selectedCwd:i,worktreeCwd:s,setSelectedCwd:o}),[a,i,s])}var $he=$(_e(),1);var nw=$(_e(),1);var Tar=$(_e(),1),Fhe="assist:reloaded-after-update";function Sar(e){(0,Tar.useEffect)(()=>{globalThis.sessionStorage?.getItem(Fhe)&&(globalThis.sessionStorage.removeItem(Fhe),e({message:"Reloaded after updating assist",sessionId:null}))},[e])}var Bg=$(_e(),1);function Car(e){return e.commandType==="assist"&&e.assistArgs?.[0]==="update"&&e.status==="done"}function war(e,t){let[r,n]=(0,Bg.useState)(!1),[i,o]=(0,Bg.useState)(!1),a=(0,Bg.useRef)(!1),s=(0,Bg.useRef)(e);s.current=e;let l=(0,Bg.useRef)(new Set),u=(0,Bg.useCallback)(()=>{a.current=!1,o(!1),l.current=new Set(s.current.filter(Car).map(h=>h.id)),n(!0)},[]);return(0,Bg.useEffect)(()=>{if(!r||i)return;if(t){a.current=!0;return}if(!a.current)return;e.some(f=>Car(f)&&!l.current.has(f.id))&&o(!0)},[r,i,t,e]),{arm:u,completed:i}}function _ar(e,t,r,n){let{arm:i,completed:o}=war(e,t),a=(0,nw.useRef)(!1),s=(0,nw.useCallback)(()=>{globalThis.sessionStorage?.setItem(Fhe,"1")},[]),{error:l,restart:u}=gO("webserver",t,s);return Sar(r),(0,nw.useEffect)(()=>{l&&n(l)},[l,n]),(0,nw.useEffect)(()=>{!o||a.current||(a.current=!0,u())},[o,u]),{armUpdateReload:(0,nw.useCallback)(()=>{a.current=!1,i()},[i])}}function kar(e){let{armUpdateReload:t}=_ar(e.sessions,e.reconnecting,e.setSuccess,e.setError),r=(0,$he.useMemo)(()=>({launchAssist:e.createAssistSession,launchAgentInStream:e.createSessionInStream,armUpdateReload:t}),[e.createAssistSession,e.createSessionInStream,t]),n=ao(),i=(0,$he.useCallback)(o=>{e.selectSession(o),n("/sessions"),e.clearSuccess()},[n,e.selectSession,e.clearSuccess]);return{launch:r,viewLaunchedSession:i}}var Ear=$(_e(),1);function Rar(e,t,r,n){let i=Bhe(e,t,r);(0,Ear.useEffect)(()=>{e&&i&&n({type:"set-active",cwd:i,sessionId:e})},[e,i,n])}var zhe=$(_e(),1);function Aar(e,t){let r=(0,zhe.useRef)(new Map);(0,zhe.useEffect)(()=>{let n=new Set;for(let{id:i,status:o}of e)n.add(i),r.current.get(i)!==o&&(r.current.set(i,o),console.debug(`[sessions] render session ${i} status=${o}`),t({type:"ui-status",sessionId:i,status:o}));for(let i of r.current.keys())n.has(i)||r.current.delete(i)},[e,t])}var Lar=$(_e(),1);function Par(e){let t=e;if(t.type==="create")return{cwd:t.cwd,title:t.prompt?.trim()||(t.design?"New design session":"New session")};if(t.type==="create-assist"){let r=t.title?.trim();return{cwd:t.cwd,title:r||"New session",named:!!r}}return null}function Mar(e,t){return(0,Lar.useCallback)(r=>{let n=e.current;n?.readyState===WebSocket.OPEN&&n.send(JSON.stringify(r));let i=Par(r);i&&t(i)},[e,t])}var Qy=$(_e(),1);function Iar(e){return(t,r)=>e({type:"create",prompt:t||void 0,cwd:r,auto:!0})}function Dar(e){return(t,r)=>e({type:"create",prompt:t||void 0,cwd:r,design:!0})}function Oar(e){return(t,r,n)=>e({type:"create",prompt:r||void 0,cwd:n,harness:t})}function Nar(e){return(t,r,n)=>e({type:"create-assist",assistArgs:t,cwd:r,...n})}function Bar(e){return(t,r,n,i)=>e({type:"resume",sessionId:t,cwd:r,name:n,harness:i})}function Far(e,t){return(r,n)=>{t.delete(r),e({type:"retry",sessionId:r,replace:n})}}function $ar(e,t){return r=>{t.delete(r),e({type:"restart",sessionId:r})}}function zar(e,t){return r=>{e({type:"dismiss",sessionId:r}),t.delete(r)}}function Uar(e,t){return r=>{e({type:"discard",sessionId:r}),t.delete(r)}}function Har(e){return t=>e({type:"stop",sessionId:t})}function War(e){return(t,r,n,i)=>e({type:"create-run",runName:t,cwd:r,replace:n,launchedFrom:i})}function Var(e){return(t,r)=>e({type:"set-autorun",sessionId:t,enabled:r})}function Gar(e){return(t,r)=>e({type:"set-autoadvance",sessionId:t,enabled:r})}function qar(e){return(t,r)=>e({type:"set-starred",sessionId:t,starred:r})}function jar(e){return(t,r)=>e({type:"input",sessionId:t,data:r})}function Yar(e){return(t,r,n)=>e({type:"resize",sessionId:t,cols:r,rows:n})}function Kar(e,t){return(r,n)=>{let i=e.get(r);return i&&n(i),t.set(r,n),()=>t.delete(r)}}function Xar(e){return(t,r,n,i)=>e({type:"pr-decision",sessionId:t,requestId:r,decision:n,...i})}var DE=$(_e(),1);function Zar(e){return(t,r,n)=>e({type:"create",prompt:r||void 0,cwd:n,joinSessionId:t,auto:!0})}function Qar(e){return{createSession:(0,DE.useMemo)(()=>Iar(e),[e]),createSessionInStream:(0,DE.useMemo)(()=>Zar(e),[e]),createDesignSession:(0,DE.useMemo)(()=>Dar(e),[e]),createHarnessSession:(0,DE.useMemo)(()=>Oar(e),[e]),createAssistSession:(0,DE.useMemo)(()=>Nar(e),[e]),resumeSession:(0,DE.useMemo)(()=>Bar(e),[e])}}var GV=$(_e(),1);function Jar(e,t){let r=(0,GV.useCallback)((a,s)=>{Far(e,t.current)(a,s)},[e,t]),n=(0,GV.useCallback)(a=>{$ar(e,t.current)(a)},[e,t]),i=(0,GV.useCallback)(a=>{zar(e,t.current)(a)},[e,t]),o=(0,GV.useCallback)(a=>{Uar(e,t.current)(a)},[e,t]);return{retrySession:r,restartSession:n,dismissSession:i,discardSession:o}}function esr(e,t,r){let n={...Qar(e),sendInput:(0,Qy.useMemo)(()=>jar(e),[e]),sendResize:(0,Qy.useMemo)(()=>Yar(e),[e]),sendPrDecision:(0,Qy.useMemo)(()=>Xar(e),[e]),setAutoRun:(0,Qy.useMemo)(()=>Var(e),[e]),setAutoAdvance:(0,Qy.useMemo)(()=>Gar(e),[e]),setStarred:(0,Qy.useMemo)(()=>qar(e),[e]),stopSession:(0,Qy.useMemo)(()=>Har(e),[e]),startRun:(0,Qy.useMemo)(()=>War(e),[e])},i=(0,Qy.useMemo)(()=>Kar(t.current,r.current),[t,r]);return{...n,...Jar(e,t),onOutput:i}}var Uhe=$(_e(),1);function tsr(e,t,r){let n=(0,Uhe.useCallback)(a=>{r(a),e({type:"fetch-transcript",sessionId:a})},[e,r]),i=(0,Uhe.useCallback)(()=>{r(null)},[r]),o=(0,Uhe.useCallback)(a=>{r(null),t(a)},[t,r]);return{viewTranscript:n,clearTranscript:i,selectSession:o}}var xx=$(_e(),1);function rsr(e,t){let r=new Set(t.map(i=>i.id)),n=null;for(let i of Object.values(e))r.has(i)&&(n=i);return n}var isr=$(_e(),1);function nsr(e,t,r=null){return t!==null?e.some(n=>n.id===t)?t:e[0]?.id??null:r&&e.some(n=>n.id===r)?r:e[0]?.id??null}function osr(e,t,r){let n=Cs().pathname,i=n.startsWith("/backlog")||n.startsWith("/usage");(0,isr.useEffect)(()=>{if(i){t(null);return}t(o=>nsr(e,o,r))},[e,t,r,i])}var lDe=$(_e(),1);function asr(){let[e,t]=(0,lDe.useState)({}),[r,n]=(0,lDe.useState)(null);return{activeByRepo:e,setActiveByRepo:t,daemonVersion:r,setDaemonVersion:n}}var OE=$(_e(),1);function ssr(e,t){if(!t.some(n=>e.has(n)))return e;let r=new Set(e);for(let n of t)r.delete(n);return r}function lsr(e,t){let r=[];for(let n of t){let i=e.get(n.id);i!==void 0&&i!==n.startedAt&&r.push(n.id)}return r}function csr(){let[e,t]=(0,OE.useState)(new Set),r=(0,OE.useRef)(new Map),n=(0,OE.useCallback)(o=>{t(a=>a.has(o)?a:new Set(a).add(o))},[]),i=(0,OE.useCallback)(o=>{let a=lsr(r.current,o);r.current=new Map(o.map(s=>[s.id,s.startedAt])),a.length&&t(s=>ssr(s,a))},[]);return{initialized:e,markInitialized:n,syncSessions:i}}var iw=$(_e(),1);function usr(){let[e,t]=(0,iw.useState)(null),[r,n]=(0,iw.useState)(null),[i,o]=(0,iw.useState)(null),a=(0,iw.useCallback)(()=>t(null),[]),s=(0,iw.useCallback)(()=>n(null),[]),l=(0,iw.useCallback)(()=>o(null),[]);return{error:e,setError:t,clearError:a,success:r,setSuccess:n,clearSuccess:s,serverConflict:i,setServerConflict:o,clearServerConflict:l}}var Jy=$(_e(),1);function hsr(e,t){return[...e,{...t,windows:YS(t.cwd),status:"launching"}]}function Hhe(e){return e.find(t=>t.status==="launching")}function fsr(e){let t=Hhe(e);return t?e.filter(r=>r.id!==t.id):e}function dsr(e,t){let r=Hhe(e);return r?cDe(e,r.id,t):e}function cDe(e,t,r){return e.map(n=>n.id===t&&n.status==="launching"?{...n,status:"error",error:r}:n)}function psr(e,t){return e.filter(r=>r.id!==t)}var msr=$(_e(),1);var WPn=6e4,VPn="Launch timed out \u2014 the session did not start.";function gsr(e,t){(0,msr.useEffect)(()=>{let r=e.filter(i=>i.status==="launching");if(r.length===0)return;let n=r.map(i=>setTimeout(()=>t(o=>cDe(o,i.id,VPn)),Math.max(0,WPn-(Date.now()-i.startedAt))));return()=>n.forEach(clearTimeout)},[e,t])}function ysr(){let[e,t]=(0,Jy.useState)([]),r=(0,Jy.useRef)([]),n=(0,Jy.useCallback)(l=>{r.current=l(r.current),t(r.current)},[]),i=(0,Jy.useCallback)(l=>{n(u=>hsr(u,{id:crypto.randomUUID(),startedAt:Date.now(),...l}))},[n]),o=(0,Jy.useCallback)(()=>{let l=Hhe(r.current);return n(fsr),l?.named?l.title:void 0},[n]),a=(0,Jy.useCallback)(l=>n(u=>dsr(u,l)),[n]),s=(0,Jy.useCallback)(l=>n(u=>psr(u,l)),[n]);return gsr(e,n),{pendingLaunches:e,addPendingLaunch:i,resolvePendingLaunch:o,failPendingLaunch:a,dismissPendingLaunch:s}}var vsr=$(_e(),1);function bsr(e,t){return(0,vsr.useCallback)(r=>{e(r),t(r)},[e,t])}var uDe=$(_e(),1);function xsr(){let[e,t]=(0,uDe.useState)(null),[r,n]=(0,uDe.useState)(null);return{transcript:e,setTranscript:t,viewingTranscriptSessionId:r,setViewingTranscriptSessionId:n}}var ow=$(_e(),1);function Tsr(e,t){let r=e.sessionId;t.buffers.current?.delete(r),t.handlers.current?.get(r)?.("\x1Bc")}function Ssr(e,t){let r=e.sessionId,n=t.resolvePendingLaunch();t.setViewingTranscriptSessionId(null),t.setActiveId(r),e.isNew&&t.setSuccess({message:n?`Started ${n}`:"New session started",sessionId:r})}function Csr(e,t){let r=e.message;t.setError(r),t.failPendingLaunch(r)}function wsr(e,t){t.setSuccess({message:e.message,sessionId:null})}function _sr(e,t){let r=e.sessionId,n=t.buffers.current?.get(r)??"";t.buffers.current?.set(r,n+e.data),t.handlers.current?.get(r)?.(e.data),t.markInitialized(r)}function ksr(e,t){t.setServerConflict({existing:e.existing,runName:e.runName,cwd:e.cwd,sessionId:e.sessionId,launchedFrom:e.launchedFrom})}function Esr(e,t){let r=e.sessions;t.setSessions(r),e.cwd&&t.setCurrentCwd(e.cwd),t.setActiveByRepo(e.active??{})}function Rsr(e,t){switch(e.type){case"sessions":Esr(e,t);break;case"created":Ssr(e,t);break;case"history":t.setHistory(e.sessions);break;case"transcript":t.setTranscript({sessionId:e.sessionId,messages:e.messages});break;case"hello":t.setDaemonVersion(e.version);break;case"error":Csr(e,t);break;case"notice":wsr(e,t);break;case"run-conflict":ksr(e,t);break;case"limits":t.setRateLimits(e.rateLimits);break;case"clear":Tsr(e,t);break;case"output":_sr(e,t);break}}function Asr(e,t={}){let r=location.protocol==="https:"?"wss:":"ws:",n=new WebSocket(`${r}//${location.host}/ws`);return n.onopen=()=>{t.onOpen?.(),n.send(JSON.stringify({type:"hello"})),n.send(JSON.stringify({type:"history"}))},n.onmessage=i=>{Rsr(JSON.parse(i.data),e)},n.onclose=()=>t.onClose?.(),n}function Psr(e,t,r,n){let i=!1,o,a=0,s=!1,l=()=>{i||t(Asr(e,{onOpen:()=>{s&&r(),s=!1,n(!1),a=0},onClose:()=>{if(i)return;s=!0,n(!0);let u=Math.min(300*2**a,2e3);a+=1,o=setTimeout(l,u)}}))};return l(),()=>{i=!0,o&&clearTimeout(o)}}function Lsr(e){let t=(0,ow.useRef)(null),[r,n]=(0,ow.useState)(!1),{handleSessions:i,markInitialized:o,buffers:a,handlers:s}=e;(0,ow.useEffect)(()=>{let u=()=>{a.current?.clear();let f=s.current;if(f)for(let d of f.values())d("\x1Bc")},h=Psr({...e,setSessions:i},f=>{t.current=f},u,n);return()=>{h(),t.current?.close()}},[i,o,a,s]);let l=(0,ow.useCallback)(()=>{let u=t.current;u?.readyState===WebSocket.OPEN&&u.send(JSON.stringify({type:"history"}))},[]);return{wsRef:t,requestHistory:l,reconnecting:r}}function Msr(){let[e,t]=(0,xx.useState)([]),[r,n]=(0,xx.useState)([]),[i,o]=(0,xx.useState)(null),a=asr(),s=xsr(),[l,u]=(0,xx.useState)(""),h=usr(),f=ysr(),[d,p]=(0,xx.useState)(null),{initialized:m,markInitialized:g,syncSessions:y}=csr(),v=(0,xx.useRef)(new Map),b=(0,xx.useRef)(new Map),x=bsr(y,t),{wsRef:C,requestHistory:S,reconnecting:w}=Lsr({handleSessions:x,setHistory:n,setActiveId:o,...a,...s,setCurrentCwd:u,...h,...f,setRateLimits:p,markInitialized:g,buffers:v,handlers:b});return osr(e,o,rsr(a.activeByRepo,e)),{sessions:e,history:r,activeId:i,setActiveId:o,...a,...s,currentCwd:l,...h,...f,rateLimits:d,initialized:m,wsRef:C,buffers:v,handlers:b,requestHistory:S,reconnecting:w}}function Isr(){let e=Msr(),{wsRef:t,buffers:r,handlers:n,addPendingLaunch:i,activeId:o,sessions:a}=e,s=Mar(t,i),l=esr(s,r,n);Rar(o,a,e.history,s),Aar(a,s);let u=tsr(s,e.setActiveId,e.setViewingTranscriptSessionId);return{...e,...l,...u}}var Osr=$(_e(),1);var Dsr="assist:sidebar-collapsed";function Nsr(){let[e,t]=(0,Osr.useState)(()=>Uy(Dsr).length>0);return{collapsed:e,onToggleCollapsed:()=>{let r=!e;Hy(Dsr,r?[!0]:[]),t(r)}}}var Whe=$(_e(),1);function Bsr(){let[e,t]=(0,Whe.useState)(!0);return(0,Whe.useEffect)(()=>{let r=!1;return(async()=>{try{let i=await(await fetch("/api/session-layout")).json();r||t(!!i?.topBar)}catch{t(!0)}})(),()=>{r=!0}},[]),e}function Fsr(){let e=Isr(),t=e.viewingTranscriptSessionId??e.activeId,r=xar(e.currentCwd,e.history,t,e.sessions);par({selectedCwd:r.selectedCwd,selectedCardId:t,sessions:e.sessions,history:e.history,activeByRepo:e.activeByRepo,onSelect:e.selectSession});let{launch:n,viewLaunchedSession:i}=kar(e),o=Bsr(),a=Nsr();return{socket:e,selection:r,launch:n,viewLaunchedSession:i,topBar:o,sidebarCollapse:a}}var Sf=$(V(),1),GPn={zIndex:e=>e.zIndex.drawer+1},qPn={minHeight:48};function $sr({mode:e,toggle:t}){let{socket:r,selection:n,launch:i,viewLaunchedSession:o,topBar:a,sidebarCollapse:s}=Fsr();return(0,Sf.jsx)(t7e.Provider,{value:a,children:(0,Sf.jsx)(R7e.Provider,{value:s,children:(0,Sf.jsx)(gB.Provider,{value:n,children:(0,Sf.jsxs)(G0e.Provider,{value:i,children:[(0,Sf.jsx)(sDe.Provider,{value:r.daemonVersion,children:(0,Sf.jsx)(lar,{mode:e,toggle:t,reconnecting:r.reconnecting})}),(0,Sf.jsx)(hde,{position:"fixed",elevation:1,sx:GPn,children:(0,Sf.jsx)(zor,{socket:r,selection:n})}),(0,Sf.jsx)(Kw,{variant:"dense",sx:qPn}),(0,Sf.jsx)(far,{socket:r,children:(0,Sf.jsx)(Fir,{socket:r})}),(0,Sf.jsx)(Jir,{socket:r,onViewLaunchedSession:o})]})})})})}var zsr=$(_e(),1);function Usr(){let[e,t]=(0,zsr.useState)(()=>{try{return localStorage.getItem("theme-mode")??"dark"}catch{return"dark"}});return{mode:e,toggle:()=>t(n=>{let i=n==="dark"?"light":"dark";try{localStorage.setItem("theme-mode",i)}catch{}return i})}}var aw=$(V(),1),jPn={MuiButtonBase:{styleOverrides:{root:{cursor:"pointer","&.Mui-disabled":{cursor:"default"}}}},MuiLink:{styleOverrides:{root:{cursor:"pointer"}}}};function YPn(){let{mode:e,toggle:t}=Usr(),r=(0,Wsr.useMemo)(()=>Vg({palette:{mode:e,...e==="dark"&&{background:{default:"#1e1e1e",paper:"#252526"}}},components:jPn}),[e]);return(0,aw.jsxs)(JG,{theme:r,children:[(0,aw.jsx)(Hq,{}),(0,aw.jsx)($sr,{mode:e,toggle:t})]})}var KPn=B0e([{path:"*",element:(0,aw.jsx)(YPn,{})}]);function XPn(){return(0,aw.jsx)(A0e,{router:KPn})}var Hsr=document.getElementById("app");Hsr&&(0,Vsr.createRoot)(Hsr).render((0,aw.jsx)(XPn,{}));})();
3974
+ `,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 eIe.get()},set promptLabel(e){eIe.set(e)},get tooMuchOutput(){return tIe.get()},set tooMuchOutput(e){tIe.set(e)}}}_verifyIntegers(...e){for(jy of e)if(jy===1/0||isNaN(jy)||jy%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(jy of e)if(jy&&(jy===1/0||isNaN(jy)||jy%1!==0||jy<0))throw new Error("This API only accepts positive integers")}};var YIe=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\^<>`]*[^\s"':,.!?{}|\\^~[\]`()<>]/;function ePn(e){try{return!!new URL(e).host}catch{return!1}}function Jnr(e,t){let r=e(t),n=e(t+1);return!!r&&!!n&&(n.isWrapped||r.isFull)}function tPn(e,t){let r=[];for(let n=t;n-t<64;n++){let i=e(n);if(!i||(r.push(i.text),!Jnr(e,n)))break}return r}function Qnr(e,t,r){let n=t;for(let i of e){if(r<i.length)return{x:r+1,y:n+1};r-=i.length,n++}}function rPn(e,t,r){let n=r[0],i=Qnr(e,t,r.index),o=Qnr(e,t,r.index+n.length-1);if(!(!ePn(n)||!i||!o))return{text:n,range:{start:i,end:o}}}function nPn(e,t,r){let n=new RegExp(r.source,`${r.flags||""}g`);return[...e.join("").matchAll(n)].flatMap(o=>rPn(e,t,o)??[])}function eir(e,t,r=YIe){if(!e(t-1))return[];let n=t-1;for(;n>0&&Jnr(e,n-1);)n--;return nPn(tPn(e,n),n,r)}function tir(e,t){let r=n=>{let i=e.buffer.active.getLine(n);if(!i)return;let o=e.cols,a=i.getCell(o-1);return{text:i.translateToString(!0,0,o),isWrapped:i.isWrapped,isFull:!!a&&a.getChars()!==""&&a.getChars()!==" "}};return{provideLinks(n,i){let o=eir(r,n,YIe);i(o.map(a=>({range:a.range,text:a.text,activate:t})))}}}function rir(e){let t=new Znr({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', Consolas, monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4"},linkHandler:{activate:(o,a)=>{window.open(a,"_blank")}}}),r=new Aer;t.loadAddon(r);let n=t.registerLinkProvider(tir(t,(o,a)=>{window.open(a,"_blank")}));t.open(e);let i;try{i=new Ytr,i.onContextLoss(()=>{i?.dispose(),i=void 0}),t.loadAddon(i)}catch{i=void 0}return r.fit(),{term:t,fitAddon:r,dispose:()=>{n.dispose(),i?.dispose(),t.dispose()}}}function nir(e,t,r,n){if(e.type!=="keydown"||!(e.ctrlKey||e.metaKey)||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(n),!1):!0}function uhe(e){return e.type==="keydown"&&(e.ctrlKey||e.metaKey)&&!e.shiftKey&&!e.altKey&&e.key.toLowerCase()==="p"}function iir(e,t,r,n,i){let o=rir(e);o.term.onData(u=>r(t,u)),o.term.attachCustomKeyEventHandler(u=>uhe(u)?!1:nir(u,o.term,navigator.clipboard,h=>o.term.paste(h)));let a=n(t,u=>o.term.write(u)),s=new ResizeObserver(()=>{yue(e)&&(o.fitAddon.fit(),i(t,o.term.cols,o.term.rows))});return s.observe(e),{handle:o,cleanup:()=>{s.disconnect(),a(),o.dispose()}}}function oir(e,t,r,n,i,o){let a=(0,IV.useRef)(null);(0,IV.useEffect)(()=>{let s=e.current;if(!s)return;let{handle:l,cleanup:u}=iir(s,t,n,i,o);return a.current=l,()=>{u(),a.current=null}},[e,t,i,n,o]),(0,IV.useEffect)(()=>{let s=a.current;if(!r||!s)return;let l=setTimeout(()=>{yue(e.current)&&(s.fitAddon.fit(),s.term.focus(),o(t,s.term.cols,s.term.rows))},50);return()=>clearTimeout(l)},[e,r,t,o])}var lir=$(V(),1);function sir({sessionId:e,visible:t,onOutput:r,sendInput:n,sendResize:i}){let o=(0,air.useRef)(null);return oir(o,e,t,n,r,i),(0,lir.jsx)(Ie,{ref:o,sx:{position:"absolute",inset:"0 0 0 8px",visibility:t?"visible":"hidden",pointerEvents:t?"auto":"none"}})}var _E=$(V(),1);function cir({sessions:e,activeId:t,activeLoading:r,onOutput:n,sendInput:i,sendResize:o}){return(0,_E.jsxs)(Ie,{sx:{flex:1,position:"relative",bgcolor:"background.default"},children:[e.map(a=>(0,_E.jsx)(sir,{sessionId:a.id,visible:a.id===t,onOutput:n,sendInput:i,sendResize:o},a.id)),r&&(0,_E.jsx)(Rer,{}),e.length===0&&(0,_E.jsx)(Ie,{sx:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:(0,_E.jsx)(tt,{variant:"body2",color:"text.disabled",children:"Create a session to get started"})})]})}var hir=$(V(),1);function uir({sessions:e,activeId:t,initialized:r,onOutput:n,sendInput:i,sendResize:o}){let a=e.find(l=>l.id===t),s=a!==void 0&&yse(a,r);return(0,hir.jsx)(cir,{sessions:e,activeId:t,activeLoading:s,onOutput:n,sendInput:i,sendResize:o})}var hO=$(V(),1),iPn={position:"relative",display:"flex",flex:1,minWidth:0,minHeight:0};function fir({activeSession:e,sendPrDecision:t,showLastMessage:r,...n}){return(0,hO.jsxs)(Ie,{sx:iPn,children:[(0,hO.jsx)(xer,{session:e,sendPrDecision:t,sendInput:n.sendInput,children:(0,hO.jsx)(uir,{...n})}),r&&e!==void 0&&(0,hO.jsx)(ker,{message:e.lastUserMessage})]})}var dir=$(V(),1),pir=Tt((0,dir.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 mm=$(V(),1);function mir({message:e}){return e.role==="tool"?(0,mm.jsx)(oPn,{tool:e.tool,target:e.target}):(0,mm.jsx)(aPn,{role:e.role,text:e.text})}function oPn({tool:e,target:t}){return(0,mm.jsxs)(Ie,{sx:{display:"flex",alignItems:"center",gap:1,py:.5,pl:1},children:[(0,mm.jsx)(pir,{sx:{fontSize:14,color:"text.disabled"}}),(0,mm.jsxs)(tt,{variant:"caption",sx:{color:"text.secondary",fontFamily:"monospace"},children:[(0,mm.jsx)(Ie,{component:"span",sx:{color:"warning.main"},children:e}),t&&(0,mm.jsxs)(Ie,{component:"span",children:[" ",t]})]})]})}function aPn({role:e,text:t}){let r=e==="user",n=r?"info.main":"success.main";return(0,mm.jsxs)(Ie,{sx:{mb:1.5,pl:1.5,py:1,pr:1,borderLeft:2,borderColor:n,borderTopRightRadius:1,borderBottomRightRadius:1,bgcolor:r?"action.hover":"transparent"},children:[(0,mm.jsx)(tt,{variant:"caption",sx:{color:n,fontWeight:600,display:"block",mb:.5},children:r?"User":"Assistant"}),(0,mm.jsx)(tt,{variant:"body2",sx:{color:"text.primary",whiteSpace:"pre-wrap",overflowWrap:"anywhere",lineHeight:1.6},children:t})]})}var Zy=$(V(),1);function sPn(e){let t=new Map;return e.map(r=>{let n=r.role==="tool"?`tool:${r.tool}:${r.target}`:`${r.role}:${r.text.slice(0,40)}`,i=t.get(n)??0;return t.set(n,i+1),{...r,key:`${n}#${i}`}})}function yir({messages:e,loading:t}){return t?(0,Zy.jsxs)(Ie,{sx:gir,children:[(0,Zy.jsx)(no,{size:20}),(0,Zy.jsx)(tt,{variant:"caption",color:"text.disabled",children:"Loading transcript\u2026"})]}):e.length===0?(0,Zy.jsx)(Ie,{sx:gir,children:(0,Zy.jsx)(tt,{variant:"body2",color:"text.disabled",children:"No transcript available"})}):(0,Zy.jsx)(Ie,{sx:{position:"absolute",inset:0,overflowY:"auto",p:2},children:(0,Zy.jsx)(Ie,{sx:{maxWidth:820,mx:"auto"},children:sPn(e).map(r=>(0,Zy.jsx)(mir,{message:r},r.key))})})}var gir={position:"absolute",inset:0,display:"flex",flexDirection:"column",gap:1.5,alignItems:"center",justifyContent:"center"};var KIe=$(V(),1);function vir({sessionId:e,transcript:t}){let r=t?.sessionId===e;return(0,KIe.jsx)(Ie,{sx:{flex:1,position:"relative",bgcolor:"background.default"},children:(0,KIe.jsx)(yir,{messages:r?t?.messages??[]:[],loading:!r})})}var GC=$(V(),1),lPn={flex:1,minHeight:0,display:"flex",flexDirection:"column"},cPn={flexShrink:0};function bir({viewingTranscriptSessionId:e,transcript:t,sendPrDecision:r,lifecycle:n,...i}){let o=df();if(e!==null)return(0,GC.jsx)(vir,{sessionId:e,transcript:t});let a=i.sessions.find(s=>s.id===i.activeId);return(0,GC.jsxs)(Ie,{sx:lPn,children:[o&&a!==void 0&&(0,GC.jsx)(Ie,{sx:cPn,children:(0,GC.jsx)(pQt,{session:a,lifecycle:n})}),(0,GC.jsx)(vQt,{sessionId:i.activeId,sessions:i.sessions,sendInput:i.sendInput,children:(0,GC.jsx)(fir,{...i,activeSession:a,sendPrDecision:r,showLastMessage:o})})]})}var Sir=$(V(),1);function Tir({socket:e}){let t=(0,xir.useMemo)(()=>({onRetry:e.retrySession,onRestart:e.restartSession,onDismiss:e.dismissSession,onSetAutoRun:e.setAutoRun,onSetAutoAdvance:e.setAutoAdvance}),[e.retrySession,e.restartSession,e.dismissSession,e.setAutoRun,e.setAutoAdvance]);return(0,Sir.jsx)(bir,{lifecycle:t,sessions:e.sessions,activeId:e.activeId,initialized:e.initialized,onOutput:e.onOutput,sendInput:e.sendInput,sendResize:e.sendResize,viewingTranscriptSessionId:e.viewingTranscriptSessionId,transcript:e.transcript,sendPrDecision:e.sendPrDecision})}function XIe(e,t,r){if(e==null)return;let n=Math.max(0,e-r),i=Math.max(0,t-n)/t;if(!(i<.05))return i}function hhe(e,t){let r=Math.max(0,e-t),n=Math.floor(r/86400),i=Math.floor(r%86400/3600),o=Math.floor(r%3600/60);return n>0?`${n}d ${i}h`:i>0?`${i}h ${o}m`:`${o}m`}function uPn(e,t,r,n){let i=XIe(t,r,n);if(i!=null)return e/i}function qC(e,t,r,n){let i=uPn(e,t,r,n);return i==null?"ok":i>100?"over":i>75?"warn":"ok"}var kE={five_hour:{label:"5h",seconds:18e3},seven_day:{label:"7d",seconds:604800,tint:{light:"rgba(0, 0, 0, 0.1)",dark:"rgba(255, 255, 255, 0.1)"}}};var hPn={ok:"success.main",warn:"warning.main",over:"error.main"};function jC(e){return hPn[e]}var NV=$(V(),1),fPn={ok:"success",warn:"warning",over:"error"};function Cir({percentage:e,level:t}){return(0,NV.jsxs)(Ie,{sx:{display:"flex",alignItems:"center",gap:1},children:[(0,NV.jsx)(L9,{variant:"determinate",value:Math.min(100,e),color:fPn[t],sx:{flexGrow:1,height:8,borderRadius:1}}),(0,NV.jsxs)(Ie,{sx:{minWidth:40,textAlign:"right",color:jC(t)},children:[Math.round(e),"%"]})]})}function wir(e){return e.avgContextPct==null?"\u2014":`${Math.round(e.avgContextPct)}%`}var dPn=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});function ZIe(e){return dPn.format(e)}var fhe=$(V(),1);function _ir({peak:e}){return(0,fhe.jsx)(Xn,{align:"right",sx:{whiteSpace:"nowrap"},children:(0,fhe.jsx)(Mn,{title:`Cycle started ${ZIe(new Date(e.createdAt))}`,children:(0,fhe.jsx)("span",{children:ZIe(new Date(e.resetsAt*1e3))})})})}var Eir=$(V(),1);function kir(){return(0,Eir.jsx)(An,{label:"reset",size:"small",color:"warning",variant:"outlined",title:"Quota reset mid-cycle \u2014 this is the peak reached before the reset.",sx:{ml:1}})}function Rir(e){return!e.tokensUp&&!e.tokensDown?"\u2014":`\u2191 ${l6(e.tokensUp)} \u2193 ${l6(e.tokensDown)}`}var Dg=$(V(),1);function Air({peak:e,now:t}){let{label:r,seconds:n,tint:i}=kE[e.window],o=qC(e.usedPercentage,e.resetsAt,n,t);return(0,Dg.jsxs)(Lm,{sx:a=>({backgroundColor:i?a.palette.mode==="dark"?i.dark:i.light:void 0}),children:[(0,Dg.jsxs)(Xn,{children:[r,e.resetDetected&&(0,Dg.jsx)(kir,{})]}),(0,Dg.jsx)(Xn,{sx:{minWidth:160},children:(0,Dg.jsx)(Cir,{percentage:e.usedPercentage,level:o})}),(0,Dg.jsx)(Xn,{align:"right",sx:{whiteSpace:"nowrap"},children:wir(e)}),(0,Dg.jsx)(Xn,{align:"right",sx:{whiteSpace:"nowrap"},children:e.phaseCount??0}),(0,Dg.jsx)(Xn,{align:"right",sx:{whiteSpace:"nowrap"},children:Rir(e)}),(0,Dg.jsx)(_ir,{peak:e})]})}var dhe=$(_e(),1);function fO(e){let[t,r]=(0,dhe.useState)(()=>Math.floor(Date.now()/1e3));return(0,dhe.useEffect)(()=>{let n=setInterval(()=>r(Math.floor(Date.now()/1e3)),e);return()=>clearInterval(n)},[e]),t}var Jl=$(V(),1);function Pir({peaks:e}){let t=fO(3e4);return(0,Jl.jsx)(eN,{component:ti,children:(0,Jl.jsxs)(jw,{size:"small",children:[(0,Jl.jsx)(tN,{sx:{"& th":{whiteSpace:"nowrap"}},children:(0,Jl.jsxs)(Lm,{children:[(0,Jl.jsx)(Xn,{children:"Window"}),(0,Jl.jsx)(Xn,{children:"Peak usage"}),(0,Jl.jsx)(Xn,{align:"right",children:(0,Jl.jsx)(Mn,{title:"Mean context-window usage across all readings in this rate-limit cycle \u2014 distinct from the Peak usage quota above.",children:(0,Jl.jsx)("span",{children:"Avg context"})})}),(0,Jl.jsx)(Xn,{align:"right",children:(0,Jl.jsx)(Mn,{title:"Number of phase readings behind the average.",children:(0,Jl.jsx)("span",{children:"Phases"})})}),(0,Jl.jsx)(Xn,{align:"right",children:"Tokens spent"}),(0,Jl.jsx)(Xn,{align:"right",children:"Cycle reset"})]})}),(0,Jl.jsx)(Yw,{children:e.map(r=>(0,Jl.jsx)(Air,{peak:r,now:t},`${r.window}-${r.resetsAt}-${r.segment}`))})]})})}var dO=$(_e(),1);function Lir(e,t){let r=(0,dO.useRef)(null),[n,i]=(0,dO.useState)();return(0,dO.useLayoutEffect)(()=>{e===t&&r.current&&i(r.current.offsetHeight)},[e,t]),{ref:r,height:n}}var YC=$(V(),1);function Mir({rows:e,total:t,page:r,pageSize:n,onPageChange:i}){let{ref:o,height:a}=Lir(e.length,n);return(0,YC.jsxs)(YC.Fragment,{children:[(0,YC.jsx)(Ie,{ref:o,sx:{minHeight:a},children:(0,YC.jsx)(Pir,{peaks:e})}),(0,YC.jsx)(Spe,{component:"div",count:t,page:r,rowsPerPage:n,rowsPerPageOptions:[n],onPageChange:(s,l)=>i(l)})]})}var QIe=$(V(),1),pPn=[{value:"all",label:"All"},{value:"five_hour",label:kE.five_hour.label},{value:"seven_day",label:kE.seven_day.label}];function Iir({window:e,onChange:t}){return(0,QIe.jsx)(np,{size:"small",exclusive:!0,value:e,onChange:(r,n)=>n&&t(n),"aria-label":"Filter peaks by rate-limit window",children:pPn.map(r=>(0,QIe.jsx)(cc,{value:r.value,children:r.label},r.value))})}var BV=$(_e(),1);var KC=$(_e(),1);async function Dir(e,t,r){let n=new URLSearchParams({page:String(e),pageSize:String(t)});r!=="all"&&n.set("window",r);let i=await fetch(`/api/usage/history?${n}`);if(!i.ok)throw new Error(`Failed to load usage history (HTTP ${i.status}).`);return i.json()}function Oir(e,t,r){let[n,i]=(0,KC.useState)([]),[o,a]=(0,KC.useState)(0),[s,l]=(0,KC.useState)(!1),[u,h]=(0,KC.useState)(!1),[f,d]=(0,KC.useState)(null);return(0,KC.useEffect)(()=>{let p=!1;return h(!0),Dir(e,t,r).then(m=>{p||(i(m.rows),a(m.total),l(!0),h(!1))},m=>{p||(d(m instanceof Error?m:new Error(String(m))),h(!1))}),()=>{p=!0}},[e,t,r]),{rows:n,total:o,loaded:s,fetching:u,error:f}}var JIe=30;function Nir(){let[e,t]=(0,BV.useState)(0),[r,n]=(0,BV.useState)("all"),i=Oir(e,JIe,r),{total:o}=i;return(0,BV.useEffect)(()=>{if(o===0)return;let s=Math.ceil(o/JIe)-1;e>s&&t(s)},[e,o]),{...i,page:e,setPage:t,window:r,selectWindow:s=>{n(s),t(0)},pageSize:JIe}}var XC=$(V(),1);function Bir(){let e=Nir(),{window:t,total:r,error:n}=e;if(n)throw n;return(0,XC.jsxs)(nm,{loading:!e.loaded,title:"Usage history",isEmpty:r===0&&t==="all",emptyMessage:"No usage peaks recorded yet.",children:[(0,XC.jsx)(Iir,{window:t,onChange:e.selectWindow}),(0,XC.jsx)(Ie,{sx:{height:4,my:1},children:e.fetching&&(0,XC.jsx)(L9,{})}),t!=="all"&&r===0?(0,XC.jsxs)(tt,{color:"text.secondary",align:"center",sx:{py:6},children:["No ",kE[t].label," usage peaks recorded yet."]}):(0,XC.jsx)(Mir,{rows:e.rows,total:r,page:e.page,pageSize:e.pageSize,onPageChange:e.setPage})]})}var Yo=$(V(),1);function mPn({socket:e}){return(0,Yo.jsx)(C9,{maxWidth:"md",sx:{py:3,px:2},children:(0,Yo.jsx)(pFt,{socket:e})})}function Fir({socket:e}){return(0,Yo.jsx)(S_,{children:(0,Yo.jsxs)(_l,{element:(0,Yo.jsx)(RUt,{socket:e}),children:[(0,Yo.jsx)(_l,{path:"sessions",element:(0,Yo.jsx)(Tir,{socket:e})}),(0,Yo.jsx)(_l,{path:"backlog/*",element:(0,Yo.jsx)(mPn,{socket:e})}),(0,Yo.jsx)(_l,{path:"news",element:(0,Yo.jsx)(ZZt,{})}),(0,Yo.jsx)(_l,{path:"usage",element:(0,Yo.jsx)(Bir,{})}),(0,Yo.jsx)(_l,{path:"backups",element:(0,Yo.jsx)(OUt,{})}),(0,Yo.jsx)(_l,{path:"config",element:(0,Yo.jsx)(yWt,{})}),(0,Yo.jsx)(_l,{path:"diff",element:(0,Yo.jsx)(xZt,{sessions:e.sessions,sendInput:e.sendInput})}),(0,Yo.jsx)(_l,{path:"file",element:(0,Yo.jsx)(jZt,{})}),(0,Yo.jsx)(_l,{path:"*",element:(0,Yo.jsx)(P0e,{to:"/sessions",replace:!0})})]})})}var xhe=$(_e(),1);var bhe=$(_e(),1);function $ir(e,t,r){if(!e)return"Select a repo to search files.";if(r.error)return"Couldn't search files in this repo.";if(!(r.files.length>0||r.loading))return t?"No matching files.":"No files in this repo."}var ZC=$(V(),1),gPn={display:"flex",gap:1,alignItems:"center",minWidth:0},yPn={display:"flex",gap:1,alignItems:"baseline",minWidth:0,overflow:"hidden"},vPn={fontFamily:"monospace",fontSize:13,whiteSpace:"nowrap"},bPn={fontFamily:"monospace",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function xPn(e){let t=e.lastIndexOf("/");return t===-1?{dir:"",basename:e}:{dir:e.slice(0,t),basename:e.slice(t+1)}}function zir({files:e,highlight:t,onHighlight:r,onSelect:n}){return(0,ZC.jsx)(Ch,{dense:!0,sx:{py:0},children:e.map((i,o)=>{let{dir:a,basename:s}=xPn(i);return(0,ZC.jsxs)(ui,{selected:o===t,onMouseEnter:()=>r(o),onClick:()=>n(i),sx:gPn,children:[(0,ZC.jsx)(WD,{path:i}),(0,ZC.jsxs)(Ie,{sx:yPn,children:[(0,ZC.jsx)(tt,{component:"span",sx:vPn,children:s}),(0,ZC.jsx)(tt,{component:"span",color:"text.secondary",sx:bPn,children:a})]})]},i)})})}var phe=$(V(),1),TPn={maxHeight:420,overflowY:"auto"},SPn={px:2,py:2,fontSize:13};function Uir({message:e,files:t,highlight:r,onHighlight:n,onSelect:i}){return(0,phe.jsx)(Ie,{sx:TPn,children:e?(0,phe.jsx)(tt,{color:"text.secondary",sx:SPn,children:e}):(0,phe.jsx)(zir,{files:t,highlight:r,onHighlight:n,onSelect:i})})}var Hir=$(V(),1);function mhe({inputRef:e,value:t,onChange:r,onKeyDown:n,placeholder:i,autoFocus:o}){return(0,Hir.jsx)(Jo,{autoFocus:o,inputRef:e,value:t,onChange:a=>r(a.target.value),onKeyDown:n,placeholder:i,size:"small",fullWidth:!0,slotProps:{input:{sx:{fontSize:12}}},sx:{p:.5}})}var ghe=$(_e(),1),Wir={files:[],loading:!1,error:!1};function Vir(e,t){let[r,n]=(0,ghe.useState)(Wir);return(0,ghe.useEffect)(()=>{if(!e){n(Wir);return}let i=!1;return n(a=>({...a,loading:!0})),(async()=>{try{let a=await fetch(`/api/files?cwd=${encodeURIComponent(e)}&q=${encodeURIComponent(t)}`);if(!a.ok)throw new Error(`HTTP ${a.status}`);let s=await a.json();if(i)return;n({files:Array.isArray(s.files)?s.files:[],loading:!1,error:!1})}catch{i||n({files:[],loading:!1,error:!0})}})(),()=>{i=!0}},[e,t]),r}var yhe=$(_e(),1);function vhe(e,t,r,n){let[i,o]=(0,yhe.useState)(0);return(0,yhe.useEffect)(()=>{o(0)},[t]),{highlight:i,setHighlight:o,onKeyDown:s=>{let l=e.length;if(s.key==="ArrowDown")s.preventDefault(),l>0&&o(u=>(u+1)%l);else if(s.key==="ArrowUp")s.preventDefault(),l>0&&o(u=>(u-1+l)%l);else if(s.key==="Enter"){s.preventDefault();let u=e[i];u&&(r(u),n())}else s.key==="Escape"&&(s.preventDefault(),n())}}}var FV=$(V(),1),CPn={mt:6,alignSelf:"flex-start"};function Gir({onClose:e}){let{worktreeCwd:t}=Oa(),[r,n]=(0,bhe.useState)(""),i=Vir(t,r),o=ao(),a=(0,bhe.useRef)(null),s=d=>o(`/file?${new URLSearchParams(t?{path:d,cwd:t}:{path:d})}`),{highlight:l,setHighlight:u,onKeyDown:h}=vhe(i.files,r,s,e),f=d=>{s(d),e()};return(0,FV.jsxs)(Th,{open:!0,onClose:e,maxWidth:"sm",fullWidth:!0,slotProps:{paper:{sx:CPn},transition:{onEntered:()=>a.current?.focus()}},children:[(0,FV.jsx)(mhe,{autoFocus:!0,inputRef:a,value:r,onChange:n,onKeyDown:h,placeholder:"Search files by name..."}),(0,FV.jsx)(Uir,{message:$ir(t,r,i),files:i.files,highlight:l,onHighlight:u,onSelect:f})]})}var jir=$(_e(),1);var qir=!0;function Yir(e){(0,jir.useEffect)(()=>{let t=r=>{uhe(r)&&(r.preventDefault(),e())};return globalThis.addEventListener("keydown",t,qir),()=>globalThis.removeEventListener("keydown",t,qir)},[e])}var Xir=$(V(),1);function Kir(){let[e,t]=(0,xhe.useState)(!1);return Yir((0,xhe.useCallback)(()=>t(!0),[])),e?(0,Xir.jsx)(Gir,{onClose:()=>t(!1)}):null}var The=$(V(),1);function Zir({notice:e,onClose:t,onView:r}){let n=e?.sessionId??null;return(0,The.jsx)(Yc,{open:e!==null,autoHideDuration:6e3,onClose:t,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:(0,The.jsx)(Xo,{severity:"success",variant:"filled",onClose:t,action:n!==null?(0,The.jsx)(xr,{color:"inherit",size:"small",onClick:()=>r(n),children:"View"}):void 0,children:e?.message})})}var She=$(V(),1);function Qir({reconnecting:e}){return(0,She.jsx)(Yc,{open:e,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:(0,She.jsx)(Xo,{severity:"info",variant:"filled",icon:(0,She.jsx)(no,{size:16,color:"inherit"}),children:"Reconnecting\u2026"})})}var yx=$(V(),1);function Jir({socket:e,onViewLaunchedSession:t}){return(0,yx.jsxs)(yx.Fragment,{children:[(0,yx.jsx)(Kir,{}),(0,yx.jsx)(Qir,{reconnecting:e.reconnecting}),(0,yx.jsx)(pf,{error:e.error,onClose:e.clearError}),(0,yx.jsx)(Zir,{notice:e.success,onClose:e.clearSuccess,onView:t})]})}var pO=$(V(),1),wPn=["/sessions","/backlog","/news"];function eor(){let e=Cs(),t=ao(),r=wPn.findIndex(i=>e.pathname.startsWith(i)),n=i=>{e.pathname!==i&&t(i)};return(0,pO.jsxs)(nN,{value:r===-1?0:r,textColor:"inherit",indicatorColor:"secondary",children:[(0,pO.jsx)(Vx,{label:"Sessions",onClick:()=>n("/sessions")}),(0,pO.jsx)(Vx,{label:"Backlog",onClick:()=>n("/backlog")}),(0,pO.jsx)(Vx,{label:"News",onClick:()=>n("/news")})]})}var whe=$(_e(),1),Che=$(V(),1),_Pn={color:"inherit"};function tor({cwd:e}){let[t,r]=(0,whe.useState)(null);return(0,whe.useEffect)(()=>{if(!e){r(null);return}let n=!1;return(async()=>{try{let o=await(await fetch(`/api/github-url?cwd=${encodeURIComponent(e)}`)).json();n||r(o?.url??null)}catch{n||r(null)}})(),()=>{n=!0}},[e]),t?(0,Che.jsx)(Mn,{title:"Open in GitHub",children:(0,Che.jsx)(gr,{sx:_Pn,onClick:()=>window.open(t,"_blank"),children:(0,Che.jsx)(Use,{})})}):null}var nor=$(_e(),1);var _he=$(V(),1);function ror({window:e,windowSeconds:t,fallbackLabel:r,now:n}){let i=e?.used_percentage;if(i==null)return null;let o=qC(i,e?.resets_at,t,n),a=e?.resets_at!=null?hhe(e.resets_at,n):r;return(0,_he.jsxs)(Ie,{component:"span",children:[(0,_he.jsxs)(Ie,{component:"span",sx:{color:jC(o)},children:[Math.round(i),"%"]})," ",(0,_he.jsxs)(Ie,{component:"span",sx:{color:"text.secondary"},children:["(",a,")"]})]})}var QC=$(V(),1);function ior({rateLimits:e}){let t=fO(3e4),r=[{window:e.five_hour,windowSeconds:18e3,fallbackLabel:"5h"},{window:e.seven_day,windowSeconds:604800,fallbackLabel:"7d"}].filter(n=>n.window?.used_percentage!=null);return(0,QC.jsx)(QC.Fragment,{children:r.map((n,i)=>(0,QC.jsxs)(nor.Fragment,{children:[i>0?(0,QC.jsx)(Ie,{component:"span",sx:{color:"text.secondary",mr:.5},children:","}):null,(0,QC.jsx)(ror,{window:n.window,windowSeconds:n.windowSeconds,fallbackLabel:n.fallbackLabel,now:t})]},n.fallbackLabel))})}function kPn(e){if(e==="over")return{level:"warn",boundary:100};if(e==="warn")return{level:"ok",boundary:75}}function EPn(e){if(e==="ok")return{level:"warn",boundary:75};if(e==="warn")return{level:"over",boundary:100}}function RPn(e,t,r,n){if(e>=t)return;let i=e/t;return Math.round(r-n*(1-i))}function sor(e,t,r,n){if(t==null)return{kind:"unprojectable"};let i=XIe(t,r,n);if(i==null)return{kind:"unprojectable"};let o=qC(e,t,r,n),a=kPn(o),s=EPn(o);return{kind:"projected",recovery:a&&{level:a.level,pct:a.boundary*i,at:RPn(e,a.boundary,t,r)},worse:s&&{level:s.level,pct:s.boundary*i}}}function lor(e,t){return e.at==null?"not before reset":`${e.level==="ok"?"green":"under"} in ${hhe(e.at,t)}`}var Og=$(V(),1);function eDe({direction:e,threshold:t}){let r=e==="back",n={display:"inline-flex",gap:.5,minWidth:"6ch",justifyContent:r?"flex-end":"flex-start"};if(!t)return(0,Og.jsx)(Ie,{component:"span",sx:n});let i=(0,Og.jsx)(Ie,{component:"span",sx:{opacity:.6},children:r?"\u2190":"\u2192"}),o=(0,Og.jsxs)(Ie,{component:"span",sx:{color:jC(t.level)},children:[Math.round(t.pct),"%"]});return(0,Og.jsx)(Ie,{component:"span",sx:n,children:r?(0,Og.jsxs)(Og.Fragment,{children:[o,i]}):(0,Og.jsxs)(Og.Fragment,{children:[i,o]})})}var JC=$(V(),1);function cor({label:e,pct:t,resetsAt:r,windowSeconds:n,now:i}){let o=qC(t,r,n,i),a=sor(t,r,n,i),s=a.kind==="projected"?a:void 0;return(0,JC.jsxs)(Ie,{sx:{display:"flex",alignItems:"baseline",gap:.75},children:[(0,JC.jsx)(Ie,{component:"span",sx:{minWidth:"2ch"},children:e}),(0,JC.jsx)(eDe,{direction:"back",threshold:s?.recovery}),(0,JC.jsxs)(Ie,{component:"span",sx:{minWidth:"4ch",textAlign:"right",color:jC(o)},children:[Math.round(t),"%"]}),(0,JC.jsx)(eDe,{direction:"forward",threshold:s?.worse}),(0,JC.jsx)(Ie,{component:"span",sx:{opacity:.6},children:s?s.recovery&&lor(s.recovery,i):"no projection yet"})]})}function uor(e){return[{label:"5h",window:e.five_hour,windowSeconds:18e3},{label:"7d",window:e.seven_day,windowSeconds:604800}].flatMap(t=>t.window?.used_percentage==null?[]:[{label:t.label,pct:t.window.used_percentage,resetsAt:t.window.resets_at,windowSeconds:t.windowSeconds}])}var $V=$(V(),1),tDe="Claude account usage (5h / 7d windows) \u2014 view history";function hor({rateLimits:e}){let t=fO(3e4);return(0,$V.jsxs)(Ie,{sx:{fontFamily:"monospace",fontSize:12},children:[uor(e).map(r=>(0,$V.jsx)(cor,{label:r.label,pct:r.pct,resetsAt:r.resetsAt,windowSeconds:r.windowSeconds,now:t},r.label)),(0,$V.jsx)(Ie,{sx:{mt:.5,opacity:.6},children:tDe})]})}var zV=$(V(),1),APn={display:"flex",alignItems:"center",ml:2,fontFamily:"monospace",fontSize:13};function PPn(e){return e?.five_hour?.used_percentage!=null||e?.seven_day?.used_percentage!=null}function dor({rateLimits:e}){let t=PPn(e);return(0,zV.jsx)(Mn,{title:t?(0,zV.jsx)(hor,{rateLimits:e}):tDe,children:(0,zV.jsx)(Qo,{component:Bm,to:"/usage",underline:"hover",color:"inherit",sx:APn,children:t?(0,zV.jsx)(ior,{rateLimits:e}):"Usage"})})}var por=$(V(),1),mor=Tt((0,por.jsx)("path",{d:"M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4z"}),"Refresh");var bx=$(_e(),1);var mO={target:"both",label:"Restart daemon",message:"This restarts the sessions daemon and the web server, then reloads the page once the server is back."};function gor(e){return fetch(`/api/restart?target=${e}`,{method:"POST"})}var vx=$(_e(),1);var LPn="/api/session-layout";async function MPn(){try{return(await fetch(LPn,{cache:"no-store"})).ok}catch{return!1}}async function yor(e){let t=0;for(;!e();){if(t=await MPn()?t+1:0,t>=2)return!e();await new Promise(r=>setTimeout(r,300))}return!1}function IPn(){return{sawDisconnect:!1,waiting:!1,abandoned:!0}}function vor(e,t,r){let n=(0,vx.useRef)(IPn()),i=(0,vx.useRef)(r);i.current=r,(0,vx.useEffect)(()=>{let s=n.current;if(!(!e||s.abandoned)){if(t){s.sawDisconnect=!0;return}!s.sawDisconnect||s.waiting||(s.waiting=!0,yor(()=>s.abandoned).then(l=>{l&&i.current()}))}},[e,t]);let o=(0,vx.useCallback)(()=>{n.current.abandoned=!0},[]),a=(0,vx.useCallback)(()=>{n.current.abandoned=!0,n.current={sawDisconnect:!1,waiting:!1,abandoned:!1}},[]);return(0,vx.useEffect)(()=>o,[o]),{arm:a,abandon:o}}var DPn=15e3;function gO(e,t,r){let[n,i]=(0,bx.useState)(!1),[o,a]=(0,bx.useState)(null),s=(0,bx.useRef)(void 0),{arm:l,abandon:u}=vor(n,t,()=>{clearTimeout(s.current),r?.(),globalThis.location.reload()});(0,bx.useEffect)(()=>()=>clearTimeout(s.current),[]);let h=(0,bx.useCallback)(async()=>{i(!0),l(),s.current=setTimeout(()=>{u(),i(!1),a("Web server did not come back")},DPn);try{if(!(await gor(e)).ok)throw new Error("restart failed")}catch{u(),clearTimeout(s.current),i(!1),a("Failed to restart web server")}},[e,l,u]);return{pending:n,error:o,clearError:()=>a(null),restart:h}}var Ng=$(V(),1),OPn={color:"inherit",mr:1.5};function bor({reconnecting:e}){let{pending:t,error:r,clearError:n,restart:i}=gO("webserver",e);return(0,Ng.jsxs)(Ng.Fragment,{children:[(0,Ng.jsx)(Mn,{title:"Restart web server",children:(0,Ng.jsx)("span",{children:(0,Ng.jsx)(gr,{sx:OPn,disabled:t,onClick:i,children:t?(0,Ng.jsx)(no,{size:24}):(0,Ng.jsx)(mor,{})})})}),(0,Ng.jsx)(pf,{error:r,onClose:n})]})}var yO=$(_e(),1);var khe=$(_e(),1);var Ehe=$(V(),1);function xor({cwd:e,selected:t,highlighted:r,onHover:n,onSelect:i}){let o=(0,khe.useRef)(null);return(0,khe.useEffect)(()=>{r&&o.current?.scrollIntoView({block:"nearest"})},[r]),(0,Ehe.jsxs)(ui,{ref:o,selected:t,title:e,onClick:i,onMouseEnter:n,sx:{fontSize:12,display:"flex",justifyContent:"space-between",gap:1,...r&&{bgcolor:"action.hover"}},children:[UV(e),YS(e)&&(0,Ehe.jsx)(US,{})]})}var rDe=$(V(),1);function Tor({repos:e,selected:t,highlight:r,onHighlight:n,onSelect:i}){return(0,rDe.jsx)(Ch,{dense:!0,children:e.map((o,a)=>(0,rDe.jsx)(xor,{cwd:o,selected:o===t,highlighted:a===r,onHover:()=>n(a),onSelect:()=>i(o)},o))})}var HV=$(V(),1);function UV(e){let t=e.includes("\\")?"\\":"/";return e.split(t).filter(Boolean).pop()??e}var NPn={...QS};function Sor({repos:e,selected:t,onSelect:r,close:n}){let[i,o]=(0,yO.useState)(""),a=(0,yO.useRef)(null);(0,yO.useEffect)(()=>{a.current?.focus()},[]);let s=i.trim().toLowerCase(),l=s?e.filter(p=>p.toLowerCase().includes(s)):e,{highlight:u,setHighlight:h,onKeyDown:f}=vhe(l,s,r,n);return(0,HV.jsxs)(ti,{elevation:4,sx:NPn,children:[(0,HV.jsx)(mhe,{inputRef:a,value:i,onChange:o,onKeyDown:f,placeholder:"Filter repos..."}),(0,HV.jsx)(Tor,{repos:l,selected:t,highlight:u,onHighlight:h,onSelect:p=>{r(p),n()}})]})}var vO=$(V(),1);function BPn(e){return e?YS(e)?(0,vO.jsxs)("span",{style:{display:"flex",flexGrow:1,alignItems:"center",justifyContent:"space-between",gap:6,minWidth:0},children:[UV(e),(0,vO.jsx)(US,{})]}):UV(e):"Select repo..."}function Cor({repos:e,selected:t,onSelect:r}){return(0,vO.jsx)(My,{label:BPn(t),children:n=>(0,vO.jsx)(Sor,{repos:e,selected:t,onSelect:r,close:n})})}var wor=$(_e(),1);var nDe=$(V(),1);function Rhe({disabled:e,onSubmit:t,label:r="prompt",allowEmpty:n=!1}){let[i,o]=(0,wor.useState)("");return(0,nDe.jsx)(My,{label:r,disabled:e,onDefaultAction:n?()=>t(""):void 0,children:a=>(0,nDe.jsx)(QI,{value:i,onChange:o,onSubmit:()=>{!n&&!i.trim()||(t(i),o(""),a())}})})}var EE=$(V(),1),FPn={textTransform:"none",fontSize:11,fontWeight:600};function _or({onSelect:e,disabled:t=!1,children:r}){return(0,EE.jsxs)(EE.Fragment,{children:[p7e.filter(n=>n.nav&&n.prompt).map(n=>(0,EE.jsx)(Rhe,{label:n.label,allowEmpty:!0,disabled:t,onSubmit:i=>e(n.value,i)},n.value)),r,p7e.filter(n=>n.nav&&!n.prompt).map(n=>(0,EE.jsx)(xr,{size:"small",variant:"outlined",disabled:t,onClick:()=>e(n.value),sx:FPn,children:n.label},n.value))]})}var iDe=$(_e(),1);function kor(e){let t=["claude"];return e.exposeCodexActions&&t.push("codex"),e.exposePiActions&&t.push("pi"),t}var Ahe=$(V(),1),$Pn={"& .MuiFormControlLabel-label":{fontSize:12}};function Eor({choices:e,value:t,onChange:r}){return(0,Ahe.jsx)(mpe,{row:!0,value:t,onChange:n=>r(n.target.value),children:e.map(n=>(0,Ahe.jsx)(Df,{value:n,control:(0,Ahe.jsx)(dpe,{size:"small"}),label:zS(n),sx:$Pn},n))})}var Phe=$(V(),1);function Ror({cwd:e,disabled:t,onCreate:r,onCreateHarness:n}){let i=kor(nse()),[o,a]=(0,iDe.useState)(""),[s,l]=(0,iDe.useState)("claude"),u=h=>{s==="claude"?r(h,e):n(s,h,e)};return(0,Phe.jsx)(My,{label:"prompt",disabled:t,onDefaultAction:()=>u(""),children:h=>(0,Phe.jsx)(QI,{value:o,onChange:a,header:i.length>1?(0,Phe.jsx)(Eor,{choices:i,value:s,onChange:l}):void 0,onSubmit:()=>{u(o),a(""),h()}})})}var RE=$(V(),1);function Aor({cwd:e,disabled:t,onCreate:r,onCreateDesign:n,onCreateHarness:i}){return(0,RE.jsxs)(RE.Fragment,{children:[(0,RE.jsx)(Ror,{cwd:e,disabled:t,onCreate:r,onCreateHarness:i}),(0,RE.jsx)(Rhe,{label:"design",allowEmpty:!0,disabled:t,onSubmit:o=>n(o,e)})]})}var Nor=$(_e(),1);var WV=$(_e(),1);function Lhe(e){let[t,r]=(0,WV.useState)([]),[n,i]=(0,WV.useState)(!0);return(0,WV.useEffect)(()=>{if(!e){r([]),i(!1);return}let o=!1;return i(!0),fetch(`/api/pr-list?cwd=${encodeURIComponent(e)}`).then(a=>a.json()).then(a=>{o||(r(Array.isArray(a?.prs)?a.prs:[]),i(!1))}).catch(()=>{o||(r([]),i(!1))}),()=>{o=!0}},[e]),{prs:t,loading:n}}var Fd=$(V(),1);function Lor({cwd:e,onPick:t}){let{prs:r,loading:n}=Lhe(e);return(0,Fd.jsx)(ti,{elevation:4,sx:{...QS,left:"auto",width:320},children:n?(0,Fd.jsx)(Por,{text:"Loading open PRs\u2026"}):r.length===0?(0,Fd.jsx)(Por,{text:"No open PRs"}):(0,Fd.jsx)(Ch,{dense:!0,disablePadding:!0,children:r.map(i=>(0,Fd.jsx)(zPn,{pr:i,onPick:t},i.number))})})}function zPn({pr:e,onPick:t}){return(0,Fd.jsx)(ui,{onMouseDown:r=>r.preventDefault(),onClick:()=>t(e),sx:{alignItems:"flex-start",py:.75,whiteSpace:"normal"},children:(0,Fd.jsxs)(ir,{spacing:.25,sx:{minWidth:0},children:[(0,Fd.jsx)(tt,{sx:{fontSize:13,lineHeight:1.3,fontWeight:500},children:e.title}),(0,Fd.jsxs)(tt,{sx:{fontSize:11,color:"text.secondary"},children:["#",e.number," \xB7 ",e.author," \xB7 ",w2(e.createdAt)]})]})})}function Por({text:e}){return(0,Fd.jsx)(Ie,{sx:{p:1.5},children:(0,Fd.jsx)(tt,{sx:{fontSize:13,color:"text.secondary"},children:e})})}var Ior=$(V(),1);function Mor({cwd:e,onPick:t}){return(0,Ior.jsx)(Lor,{cwd:e,onPick:t})}var Dor=$(_e(),1);var mu=$(V(),1);function Oor({pr:e,onSelect:t,onCancel:r}){let[n,i]=(0,Dor.useState)(YH);return(0,mu.jsxs)(Th,{open:!0,onClose:r,maxWidth:"xs",fullWidth:!0,children:[(0,mu.jsxs)(ep,{sx:{fontSize:15},children:["Review #",e.number,": ",e.title]}),(0,mu.jsx)(Jd,{sx:{px:0},children:(0,mu.jsxs)(Ch,{children:[Hse.map(({label:o,args:a})=>(0,mu.jsx)(ui,{onClick:()=>t([...a,...Wse(n)]),children:o},o)),(0,mu.jsx)(is,{}),(0,mu.jsx)(Vse,{value:n,onChange:i}),(0,mu.jsx)(is,{}),(0,mu.jsx)(ui,{onClick:()=>t(["review","--checkout-only"]),children:"Checkout"}),(0,mu.jsx)(ui,{onClick:()=>t(["review-pr-comments"]),children:"Address Comments"}),(0,mu.jsx)(ui,{onClick:()=>t(["fix-conflict"]),children:"Fix conflicts (merge)"}),(0,mu.jsx)(ui,{onClick:()=>t(["fix-conflict","--rebase"]),children:"Fix conflicts (rebase)"})]})}),(0,mu.jsx)(Qd,{children:(0,mu.jsx)(xr,{onClick:r,children:"Cancel"})})]})}var ew=$(V(),1);function Bor({cwd:e,disabled:t,onSelect:r}){let{prs:n,loading:i}=Lhe(e),[o,a]=(0,Nor.useState)(null);return i||n.length===0?null:(0,ew.jsxs)(ew.Fragment,{children:[(0,ew.jsx)(My,{label:"prs",disabled:t,children:s=>(0,ew.jsx)(Mor,{cwd:e,onPick:l=>{a(l),s()}})}),o&&(0,ew.jsx)(Oor,{pr:o,onSelect:s=>{r(o,s),a(null)},onCancel:()=>a(null)})]})}var bO=$(V(),1);function For({onStartRun:e,cwd:t}){let r=Xse(t);return!t||r.length===0?null:(0,bO.jsx)(My,{label:"server",children:n=>(0,bO.jsx)(ti,{elevation:4,sx:{...QS,left:"auto",width:200},children:(0,bO.jsx)(Ch,{dense:!0,disablePadding:!0,children:r.map(i=>(0,bO.jsx)(ui,{onMouseDown:o=>o.preventDefault(),onClick:()=>{e(i.name,t),n()},sx:{py:.75},children:(0,bO.jsx)(tt,{sx:{fontSize:13},children:i.name})},i.name))})})})}var AE=$(V(),1);function $or({onCreate:e,onCreateDesign:t,onCreateHarness:r,onCreateAssist:n,onStartRun:i}){let{selectedCwd:o}=Oa(),a=!o;return(0,AE.jsxs)(ir,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:[(0,AE.jsxs)(_or,{disabled:a,onSelect:(s,l)=>q$t(s,o,n,()=>{},l),children:[(0,AE.jsx)(Aor,{cwd:o,disabled:a,onCreate:e,onCreateDesign:t,onCreateHarness:r}),(0,AE.jsx)(Bor,{cwd:o,disabled:a,onSelect:(s,l)=>n([...l,String(s.number)],o,Gse(s))})]}),(0,AE.jsx)(For,{onStartRun:i,cwd:o})]})}var $d=$(V(),1),UPn={minHeight:48,pl:1,pr:14},HPn={width:240,ml:2};function zor({socket:e,selection:t}){let{collapsed:r,onToggleCollapsed:n}=rD();return(0,$d.jsxs)(Kw,{variant:"dense",disableGutters:!0,sx:UPn,children:[r&&(0,$d.jsx)(ole,{collapsed:r,onToggleCollapsed:n}),(0,$d.jsx)(bor,{reconnecting:e.reconnecting}),(0,$d.jsx)(eor,{}),(0,$d.jsx)(Ie,{sx:HPn,children:(0,$d.jsx)(Cor,{repos:t.repos,selected:t.selectedCwd,onSelect:t.setSelectedCwd})}),(0,$d.jsxs)(Ie,{sx:{display:"flex",ml:1,mr:2},children:[(0,$d.jsx)(Yse,{cwd:t.selectedCwd}),(0,$d.jsx)(tor,{cwd:t.selectedCwd})]}),(0,$d.jsx)($or,{onCreate:e.createSession,onCreateDesign:e.createDesignSession,onCreateHarness:e.createHarnessSession,onCreateAssist:e.createAssistSession,onStartRun:e.startRun}),(0,$d.jsx)(dor,{rateLimits:e.rateLimits})]})}var Dhe=$(_e(),1);var Uor=$(V(),1),Hor=Tt((0,Uor.jsx)("path",{d:"m12 16.5 4-4h-3v-9h-2v9H8zm9-13h-6v1.99h6v14.03H3V5.49h6V3.5H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2v-14c0-1.1-.9-2-2-2"}),"SystemUpdateAlt");var Wor=$(V(),1),Vor=Tt((0,Wor.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 Gor=$(V(),1),qor=Tt((0,Gor.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 oDe=$(V(),1);function jor({mode:e}){return e==="dark"?(0,oDe.jsx)(qor,{fontSize:"small"}):(0,oDe.jsx)(Vor,{fontSize:"small"})}var ph=$(V(),1);function Yor({mode:e,onToggleColorMode:t,onRestart:r,onUpdate:n}){return[(0,ph.jsxs)(ui,{onClick:t,children:[(0,ph.jsx)(I9,{children:(0,ph.jsx)(jor,{mode:e})}),(0,ph.jsx)(O9,{children:"Toggle dark mode"})]},"color-mode"),(0,ph.jsx)(is,{},"restart-divider"),(0,ph.jsxs)(ui,{onClick:r,children:[(0,ph.jsx)(I9,{children:(0,ph.jsx)(Dse,{fontSize:"small"})}),(0,ph.jsx)(O9,{children:mO.label})]},"restart"),(0,ph.jsxs)(ui,{onClick:n,children:[(0,ph.jsx)(I9,{children:(0,ph.jsx)(Hor,{fontSize:"small"})}),(0,ph.jsx)(O9,{children:"Update assist"})]},"update")]}var PE=$(V(),1);function Kor({reconnecting:e,onClose:t}){let{pending:r,error:n,clearError:i,restart:o}=gO(mO.target,e);return(0,PE.jsxs)(PE.Fragment,{children:[(0,PE.jsx)(na,{title:mO.label,message:mO.message,confirmLabel:"Restart",busy:r,onConfirm:()=>{o()},onCancel:t}),(0,PE.jsx)(pf,{error:n,onClose:i})]})}var Zor=$(V(),1);function Xor({onConfirm:e,onClose:t}){return(0,Zor.jsx)(na,{title:"Update assist",message:"This starts a new session running 'assist update'. Its output will appear in the terminal.",confirmLabel:"Update",onConfirm:()=>{e(),t()},onCancel:t})}var LE=$(V(),1);function Qor({restarting:e,reconnecting:t,onCloseRestart:r,updating:n,onCloseUpdate:i}){let{launchAssist:o,armUpdateReload:a}=yp();return(0,LE.jsxs)(LE.Fragment,{children:[e&&(0,LE.jsx)(Kor,{reconnecting:t,onClose:r}),n&&(0,LE.jsx)(Xor,{onConfirm:()=>{a(),o(["update"])},onClose:i})]})}var Jor=$(V(),1),ear=Tt((0,Jor.jsx)("path",{d:"M3 18h18v-2H3zm0-5h18v-2H3zm0-7v2h18V6z"}),"Menu");var tar=$(V(),1),rar=Tt((0,tar.jsx)("path",{d:"M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6"}),"Settings");var Mhe=$(V(),1);function nar(){let e=ao();return(0,Mhe.jsx)(Mn,{title:"Config",children:(0,Mhe.jsx)(gr,{size:"small",sx:{color:"inherit"},"aria-label":"Config",onClick:()=>e("/config"),children:(0,Mhe.jsx)(rar,{fontSize:"small"})})})}var aDe=$(V(),1),iar=Tt([(0,aDe.jsx)("path",{d:"M12 5.99 19.53 19H4.47zM12 2 1 21h22z"},"0"),(0,aDe.jsx)("path",{d:"M13 16h-2v2h2zm0-6h-2v5h2z"},"1")],"WarningAmber");var VV="0.616.3";var Ihe=$(_e(),1),sDe=(0,Ihe.createContext)(null);function oar(){return(0,Ihe.useContext)(sDe)}var tw=$(V(),1);function aar(){let e=oar();return VV?(0,tw.jsxs)(tw.Fragment,{children:[(0,tw.jsxs)(tt,{variant:"caption",sx:{opacity:.4,userSelect:"none",lineHeight:1},children:["v",VV]}),e&&e!==VV&&(0,tw.jsx)(Mn,{title:`Daemon is running v${e}, but this page was served by v${VV}. Restart the daemon to match.`,children:(0,tw.jsx)(iar,{fontSize:"small",color:"warning","aria-label":"Version mismatch"})})]}):null}var ME=$(V(),1);function sar({open:e,onOpen:t}){return(0,ME.jsxs)(Ie,{sx:{position:"fixed",top:8,right:16,zIndex:r=>r.zIndex.drawer+2,display:"flex",alignItems:"center",gap:.5,color:"inherit"},children:[(0,ME.jsx)(aar,{}),(0,ME.jsx)(nar,{}),(0,ME.jsx)(gr,{onClick:r=>t(r.currentTarget),size:"small",sx:{color:"inherit"},"aria-label":"Open menu","aria-haspopup":"true","aria-expanded":e?"true":void 0,children:(0,ME.jsx)(ear,{fontSize:"small"})})]})}var rw=$(V(),1);function lar({mode:e,toggle:t,reconnecting:r}){let[n,i]=(0,Dhe.useState)(null),[o,a]=(0,Dhe.useState)(!1),[s,l]=(0,Dhe.useState)(!1),u=!!n,h=()=>i(null);return(0,rw.jsxs)(rw.Fragment,{children:[(0,rw.jsx)(sar,{open:u,onOpen:i}),(0,rw.jsx)(tp,{anchorEl:n,open:u,onClose:h,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:Yor({mode:e,onToggleColorMode:()=>{t(),h()},onRestart:()=>{h(),a(!0)},onUpdate:()=>{h(),l(!0)}})}),(0,rw.jsx)(Qor,{restarting:o,reconnecting:r,onCloseRestart:()=>a(!1),updating:s,onCloseUpdate:()=>l(!1)})]})}var har=$(_e(),1);var uar=$(V(),1);function car({conflict:e,onConfirm:t,onCancel:r}){let{name:n,cwd:i,port:o}=e.existing,a=Jp(i),s=o?` on port ${o}`:"",l=a?` in ${a}`:"";return(0,uar.jsx)(na,{title:"Replace running server?",message:`"${n}" is already serving${s}${l}. Replace it \u2014 stop the running server and start this one?`,confirmLabel:"Replace",confirmColor:"error",onConfirm:t,onCancel:r})}var Ohe=$(V(),1);function far({socket:e,children:t}){let{serverConflict:r,clearServerConflict:n,retrySession:i,stopSession:o,startRun:a,discardSession:s}=e,l=(0,har.useMemo)(()=>({onStop:o,onStart:a,onDiscard:s}),[o,a,s]),u=()=>{r&&(r.runName?a(r.runName,r.cwd,!0,r.launchedFrom):r.sessionId&&i(r.sessionId,!0),n())};return(0,Ohe.jsxs)(c7e.Provider,{value:l,children:[t,r&&(0,Ohe.jsx)(car,{conflict:r,onConfirm:u,onCancel:n})]})}var Nhe=$(_e(),1);function dar(e,t,r){if(!t)return null;let n=e[t];if(!n)return null;let i=r.find(o=>o.id===n);return!i||ff(i)!==t?null:n}function xO(e,t,r){if(e)return t.find(n=>n.id===e)??r.find(n=>n.sessionId===e)}function par({selectedCwd:e,selectedCardId:t,sessions:r,history:n,activeByRepo:i,onSelect:o}){let a=xO(t,r,n),s=a&&ff(a),l=!!(s&&s===e),u=dar(i,e,r),h=(0,Nhe.useRef)(t);(0,Nhe.useEffect)(()=>{let f=h.current!==t&&!!s;h.current=t,!(f||l||!u)&&o(u)},[t,s,l,u,o])}var IE=$(_e(),1);function mar(e,t,r,n){let i=xO(e,t,r);return i?.cwd&&ff(i)===n?i.cwd:n}function gar(e,t){let r=new Set,n=new Set,i=[];for(let o of t){if(o.cwdMissing)continue;let a=HS(o),s=ff(o);!a||!s||r.has(a)||n.has(s)||(r.add(a),n.add(s),i.push(s))}return e&&!r.has(fse(e,t))&&!n.has(e)&&i.unshift(e),i}var yar=$(_e(),1);function Bhe(e,t,r){let n=xO(e,t,r);return n&&ff(n)}function bar(e,t,r,n){let i=Bhe(e,t,r);(0,yar.useEffect)(()=>{i&&n(i)},[i,n])}function xar(e,t,r,n){let[i,o]=(0,IE.useState)(e);(0,IE.useEffect)(()=>{e&&!i&&o(e)},[e,i]),bar(r,n,t,o);let a=(0,IE.useMemo)(()=>gar(e,t),[e,t]),s=mar(r,n,t,i);return(0,IE.useMemo)(()=>({repos:a,selectedCwd:i,worktreeCwd:s,setSelectedCwd:o}),[a,i,s])}var $he=$(_e(),1);var nw=$(_e(),1);var Tar=$(_e(),1),Fhe="assist:reloaded-after-update";function Sar(e){(0,Tar.useEffect)(()=>{globalThis.sessionStorage?.getItem(Fhe)&&(globalThis.sessionStorage.removeItem(Fhe),e({message:"Reloaded after updating assist",sessionId:null}))},[e])}var Bg=$(_e(),1);function Car(e){return e.commandType==="assist"&&e.assistArgs?.[0]==="update"&&e.status==="done"}function war(e,t){let[r,n]=(0,Bg.useState)(!1),[i,o]=(0,Bg.useState)(!1),a=(0,Bg.useRef)(!1),s=(0,Bg.useRef)(e);s.current=e;let l=(0,Bg.useRef)(new Set),u=(0,Bg.useCallback)(()=>{a.current=!1,o(!1),l.current=new Set(s.current.filter(Car).map(h=>h.id)),n(!0)},[]);return(0,Bg.useEffect)(()=>{if(!r||i)return;if(t){a.current=!0;return}if(!a.current)return;e.some(f=>Car(f)&&!l.current.has(f.id))&&o(!0)},[r,i,t,e]),{arm:u,completed:i}}function _ar(e,t,r,n){let{arm:i,completed:o}=war(e,t),a=(0,nw.useRef)(!1),s=(0,nw.useCallback)(()=>{globalThis.sessionStorage?.setItem(Fhe,"1")},[]),{error:l,restart:u}=gO("webserver",t,s);return Sar(r),(0,nw.useEffect)(()=>{l&&n(l)},[l,n]),(0,nw.useEffect)(()=>{!o||a.current||(a.current=!0,u())},[o,u]),{armUpdateReload:(0,nw.useCallback)(()=>{a.current=!1,i()},[i])}}function kar(e){let{armUpdateReload:t}=_ar(e.sessions,e.reconnecting,e.setSuccess,e.setError),r=(0,$he.useMemo)(()=>({launchAssist:e.createAssistSession,launchAgentInStream:e.createSessionInStream,armUpdateReload:t}),[e.createAssistSession,e.createSessionInStream,t]),n=ao(),i=(0,$he.useCallback)(o=>{e.selectSession(o),n("/sessions"),e.clearSuccess()},[n,e.selectSession,e.clearSuccess]);return{launch:r,viewLaunchedSession:i}}var Ear=$(_e(),1);function Rar(e,t,r,n){let i=Bhe(e,t,r);(0,Ear.useEffect)(()=>{e&&i&&n({type:"set-active",cwd:i,sessionId:e})},[e,i,n])}var zhe=$(_e(),1);function Aar(e,t){let r=(0,zhe.useRef)(new Map);(0,zhe.useEffect)(()=>{let n=new Set;for(let{id:i,status:o}of e)n.add(i),r.current.get(i)!==o&&(r.current.set(i,o),console.debug(`[sessions] render session ${i} status=${o}`),t({type:"ui-status",sessionId:i,status:o}));for(let i of r.current.keys())n.has(i)||r.current.delete(i)},[e,t])}var Lar=$(_e(),1);function Par(e){let t=e;if(t.type==="create")return{cwd:t.cwd,title:t.prompt?.trim()||(t.design?"New design session":"New session")};if(t.type==="create-assist"){let r=t.title?.trim();return{cwd:t.cwd,title:r||"New session",named:!!r}}return null}function Mar(e,t){return(0,Lar.useCallback)(r=>{let n=e.current;n?.readyState===WebSocket.OPEN&&n.send(JSON.stringify(r));let i=Par(r);i&&t(i)},[e,t])}var Qy=$(_e(),1);function Iar(e){return(t,r)=>e({type:"create",prompt:t||void 0,cwd:r,auto:!0})}function Dar(e){return(t,r)=>e({type:"create",prompt:t||void 0,cwd:r,design:!0})}function Oar(e){return(t,r,n)=>e({type:"create",prompt:r||void 0,cwd:n,harness:t})}function Nar(e){return(t,r,n)=>e({type:"create-assist",assistArgs:t,cwd:r,...n})}function Bar(e){return(t,r,n,i)=>e({type:"resume",sessionId:t,cwd:r,name:n,harness:i})}function Far(e,t){return(r,n)=>{t.delete(r),e({type:"retry",sessionId:r,replace:n})}}function $ar(e,t){return r=>{t.delete(r),e({type:"restart",sessionId:r})}}function zar(e,t){return r=>{e({type:"dismiss",sessionId:r}),t.delete(r)}}function Uar(e,t){return r=>{e({type:"discard",sessionId:r}),t.delete(r)}}function Har(e){return t=>e({type:"stop",sessionId:t})}function War(e){return(t,r,n,i)=>e({type:"create-run",runName:t,cwd:r,replace:n,launchedFrom:i})}function Var(e){return(t,r)=>e({type:"set-autorun",sessionId:t,enabled:r})}function Gar(e){return(t,r)=>e({type:"set-autoadvance",sessionId:t,enabled:r})}function qar(e){return(t,r)=>e({type:"set-starred",sessionId:t,starred:r})}function jar(e){return(t,r)=>e({type:"input",sessionId:t,data:r})}function Yar(e){return(t,r,n)=>e({type:"resize",sessionId:t,cols:r,rows:n})}function Kar(e,t){return(r,n)=>{let i=e.get(r);return i&&n(i),t.set(r,n),()=>t.delete(r)}}function Xar(e){return(t,r,n,i)=>e({type:"pr-decision",sessionId:t,requestId:r,decision:n,...i})}var DE=$(_e(),1);function Zar(e){return(t,r,n)=>e({type:"create",prompt:r||void 0,cwd:n,joinSessionId:t,auto:!0})}function Qar(e){return{createSession:(0,DE.useMemo)(()=>Iar(e),[e]),createSessionInStream:(0,DE.useMemo)(()=>Zar(e),[e]),createDesignSession:(0,DE.useMemo)(()=>Dar(e),[e]),createHarnessSession:(0,DE.useMemo)(()=>Oar(e),[e]),createAssistSession:(0,DE.useMemo)(()=>Nar(e),[e]),resumeSession:(0,DE.useMemo)(()=>Bar(e),[e])}}var GV=$(_e(),1);function Jar(e,t){let r=(0,GV.useCallback)((a,s)=>{Far(e,t.current)(a,s)},[e,t]),n=(0,GV.useCallback)(a=>{$ar(e,t.current)(a)},[e,t]),i=(0,GV.useCallback)(a=>{zar(e,t.current)(a)},[e,t]),o=(0,GV.useCallback)(a=>{Uar(e,t.current)(a)},[e,t]);return{retrySession:r,restartSession:n,dismissSession:i,discardSession:o}}function esr(e,t,r){let n={...Qar(e),sendInput:(0,Qy.useMemo)(()=>jar(e),[e]),sendResize:(0,Qy.useMemo)(()=>Yar(e),[e]),sendPrDecision:(0,Qy.useMemo)(()=>Xar(e),[e]),setAutoRun:(0,Qy.useMemo)(()=>Var(e),[e]),setAutoAdvance:(0,Qy.useMemo)(()=>Gar(e),[e]),setStarred:(0,Qy.useMemo)(()=>qar(e),[e]),stopSession:(0,Qy.useMemo)(()=>Har(e),[e]),startRun:(0,Qy.useMemo)(()=>War(e),[e])},i=(0,Qy.useMemo)(()=>Kar(t.current,r.current),[t,r]);return{...n,...Jar(e,t),onOutput:i}}var Uhe=$(_e(),1);function tsr(e,t,r){let n=(0,Uhe.useCallback)(a=>{r(a),e({type:"fetch-transcript",sessionId:a})},[e,r]),i=(0,Uhe.useCallback)(()=>{r(null)},[r]),o=(0,Uhe.useCallback)(a=>{r(null),t(a)},[t,r]);return{viewTranscript:n,clearTranscript:i,selectSession:o}}var xx=$(_e(),1);function rsr(e,t){let r=new Set(t.map(i=>i.id)),n=null;for(let i of Object.values(e))r.has(i)&&(n=i);return n}var isr=$(_e(),1);function nsr(e,t,r=null){return t!==null?e.some(n=>n.id===t)?t:e[0]?.id??null:r&&e.some(n=>n.id===r)?r:e[0]?.id??null}function osr(e,t,r){let n=Cs().pathname,i=n.startsWith("/backlog")||n.startsWith("/usage");(0,isr.useEffect)(()=>{if(i){t(null);return}t(o=>nsr(e,o,r))},[e,t,r,i])}var lDe=$(_e(),1);function asr(){let[e,t]=(0,lDe.useState)({}),[r,n]=(0,lDe.useState)(null);return{activeByRepo:e,setActiveByRepo:t,daemonVersion:r,setDaemonVersion:n}}var OE=$(_e(),1);function ssr(e,t){if(!t.some(n=>e.has(n)))return e;let r=new Set(e);for(let n of t)r.delete(n);return r}function lsr(e,t){let r=[];for(let n of t){let i=e.get(n.id);i!==void 0&&i!==n.startedAt&&r.push(n.id)}return r}function csr(){let[e,t]=(0,OE.useState)(new Set),r=(0,OE.useRef)(new Map),n=(0,OE.useCallback)(o=>{t(a=>a.has(o)?a:new Set(a).add(o))},[]),i=(0,OE.useCallback)(o=>{let a=lsr(r.current,o);r.current=new Map(o.map(s=>[s.id,s.startedAt])),a.length&&t(s=>ssr(s,a))},[]);return{initialized:e,markInitialized:n,syncSessions:i}}var iw=$(_e(),1);function usr(){let[e,t]=(0,iw.useState)(null),[r,n]=(0,iw.useState)(null),[i,o]=(0,iw.useState)(null),a=(0,iw.useCallback)(()=>t(null),[]),s=(0,iw.useCallback)(()=>n(null),[]),l=(0,iw.useCallback)(()=>o(null),[]);return{error:e,setError:t,clearError:a,success:r,setSuccess:n,clearSuccess:s,serverConflict:i,setServerConflict:o,clearServerConflict:l}}var Jy=$(_e(),1);function hsr(e,t){return[...e,{...t,windows:YS(t.cwd),status:"launching"}]}function Hhe(e){return e.find(t=>t.status==="launching")}function fsr(e){let t=Hhe(e);return t?e.filter(r=>r.id!==t.id):e}function dsr(e,t){let r=Hhe(e);return r?cDe(e,r.id,t):e}function cDe(e,t,r){return e.map(n=>n.id===t&&n.status==="launching"?{...n,status:"error",error:r}:n)}function psr(e,t){return e.filter(r=>r.id!==t)}var msr=$(_e(),1);var WPn=6e4,VPn="Launch timed out \u2014 the session did not start.";function gsr(e,t){(0,msr.useEffect)(()=>{let r=e.filter(i=>i.status==="launching");if(r.length===0)return;let n=r.map(i=>setTimeout(()=>t(o=>cDe(o,i.id,VPn)),Math.max(0,WPn-(Date.now()-i.startedAt))));return()=>n.forEach(clearTimeout)},[e,t])}function ysr(){let[e,t]=(0,Jy.useState)([]),r=(0,Jy.useRef)([]),n=(0,Jy.useCallback)(l=>{r.current=l(r.current),t(r.current)},[]),i=(0,Jy.useCallback)(l=>{n(u=>hsr(u,{id:crypto.randomUUID(),startedAt:Date.now(),...l}))},[n]),o=(0,Jy.useCallback)(()=>{let l=Hhe(r.current);return n(fsr),l?.named?l.title:void 0},[n]),a=(0,Jy.useCallback)(l=>n(u=>dsr(u,l)),[n]),s=(0,Jy.useCallback)(l=>n(u=>psr(u,l)),[n]);return gsr(e,n),{pendingLaunches:e,addPendingLaunch:i,resolvePendingLaunch:o,failPendingLaunch:a,dismissPendingLaunch:s}}var vsr=$(_e(),1);function bsr(e,t){return(0,vsr.useCallback)(r=>{e(r),t(r)},[e,t])}var uDe=$(_e(),1);function xsr(){let[e,t]=(0,uDe.useState)(null),[r,n]=(0,uDe.useState)(null);return{transcript:e,setTranscript:t,viewingTranscriptSessionId:r,setViewingTranscriptSessionId:n}}var ow=$(_e(),1);function Tsr(e,t){let r=e.sessionId;t.buffers.current?.delete(r),t.handlers.current?.get(r)?.("\x1Bc")}function Ssr(e,t){let r=e.sessionId,n=t.resolvePendingLaunch();t.setViewingTranscriptSessionId(null),t.setActiveId(r),e.isNew&&t.setSuccess({message:n?`Started ${n}`:"New session started",sessionId:r})}function Csr(e,t){let r=e.message;t.setError(r),t.failPendingLaunch(r)}function wsr(e,t){t.setSuccess({message:e.message,sessionId:null})}function _sr(e,t){let r=e.sessionId,n=t.buffers.current?.get(r)??"";t.buffers.current?.set(r,n+e.data),t.handlers.current?.get(r)?.(e.data),t.markInitialized(r)}function ksr(e,t){t.setServerConflict({existing:e.existing,runName:e.runName,cwd:e.cwd,sessionId:e.sessionId,launchedFrom:e.launchedFrom})}function Esr(e,t){let r=e.sessions;t.setSessions(r),e.cwd&&t.setCurrentCwd(e.cwd),t.setActiveByRepo(e.active??{})}function Rsr(e,t){switch(e.type){case"sessions":Esr(e,t);break;case"created":Ssr(e,t);break;case"history":t.setHistory(e.sessions);break;case"transcript":t.setTranscript({sessionId:e.sessionId,messages:e.messages});break;case"hello":t.setDaemonVersion(e.version);break;case"error":Csr(e,t);break;case"notice":wsr(e,t);break;case"run-conflict":ksr(e,t);break;case"limits":t.setRateLimits(e.rateLimits);break;case"clear":Tsr(e,t);break;case"output":_sr(e,t);break}}function Asr(e,t={}){let r=location.protocol==="https:"?"wss:":"ws:",n=new WebSocket(`${r}//${location.host}/ws`);return n.onopen=()=>{t.onOpen?.(),n.send(JSON.stringify({type:"hello"})),n.send(JSON.stringify({type:"history"}))},n.onmessage=i=>{Rsr(JSON.parse(i.data),e)},n.onclose=()=>t.onClose?.(),n}function Psr(e,t,r,n){let i=!1,o,a=0,s=!1,l=()=>{i||t(Asr(e,{onOpen:()=>{s&&r(),s=!1,n(!1),a=0},onClose:()=>{if(i)return;s=!0,n(!0);let u=Math.min(300*2**a,2e3);a+=1,o=setTimeout(l,u)}}))};return l(),()=>{i=!0,o&&clearTimeout(o)}}function Lsr(e){let t=(0,ow.useRef)(null),[r,n]=(0,ow.useState)(!1),{handleSessions:i,markInitialized:o,buffers:a,handlers:s}=e;(0,ow.useEffect)(()=>{let u=()=>{a.current?.clear();let f=s.current;if(f)for(let d of f.values())d("\x1Bc")},h=Psr({...e,setSessions:i},f=>{t.current=f},u,n);return()=>{h(),t.current?.close()}},[i,o,a,s]);let l=(0,ow.useCallback)(()=>{let u=t.current;u?.readyState===WebSocket.OPEN&&u.send(JSON.stringify({type:"history"}))},[]);return{wsRef:t,requestHistory:l,reconnecting:r}}function Msr(){let[e,t]=(0,xx.useState)([]),[r,n]=(0,xx.useState)([]),[i,o]=(0,xx.useState)(null),a=asr(),s=xsr(),[l,u]=(0,xx.useState)(""),h=usr(),f=ysr(),[d,p]=(0,xx.useState)(null),{initialized:m,markInitialized:g,syncSessions:y}=csr(),v=(0,xx.useRef)(new Map),b=(0,xx.useRef)(new Map),x=bsr(y,t),{wsRef:C,requestHistory:S,reconnecting:w}=Lsr({handleSessions:x,setHistory:n,setActiveId:o,...a,...s,setCurrentCwd:u,...h,...f,setRateLimits:p,markInitialized:g,buffers:v,handlers:b});return osr(e,o,rsr(a.activeByRepo,e)),{sessions:e,history:r,activeId:i,setActiveId:o,...a,...s,currentCwd:l,...h,...f,rateLimits:d,initialized:m,wsRef:C,buffers:v,handlers:b,requestHistory:S,reconnecting:w}}function Isr(){let e=Msr(),{wsRef:t,buffers:r,handlers:n,addPendingLaunch:i,activeId:o,sessions:a}=e,s=Mar(t,i),l=esr(s,r,n);Rar(o,a,e.history,s),Aar(a,s);let u=tsr(s,e.setActiveId,e.setViewingTranscriptSessionId);return{...e,...l,...u}}var Osr=$(_e(),1);var Dsr="assist:sidebar-collapsed";function Nsr(){let[e,t]=(0,Osr.useState)(()=>Uy(Dsr).length>0);return{collapsed:e,onToggleCollapsed:()=>{let r=!e;Hy(Dsr,r?[!0]:[]),t(r)}}}var Whe=$(_e(),1);function Bsr(){let[e,t]=(0,Whe.useState)(!0);return(0,Whe.useEffect)(()=>{let r=!1;return(async()=>{try{let i=await(await fetch("/api/session-layout")).json();r||t(!!i?.topBar)}catch{t(!0)}})(),()=>{r=!0}},[]),e}function Fsr(){let e=Isr(),t=e.viewingTranscriptSessionId??e.activeId,r=xar(e.currentCwd,e.history,t,e.sessions);par({selectedCwd:r.selectedCwd,selectedCardId:t,sessions:e.sessions,history:e.history,activeByRepo:e.activeByRepo,onSelect:e.selectSession});let{launch:n,viewLaunchedSession:i}=kar(e),o=Bsr(),a=Nsr();return{socket:e,selection:r,launch:n,viewLaunchedSession:i,topBar:o,sidebarCollapse:a}}var Sf=$(V(),1),GPn={zIndex:e=>e.zIndex.drawer+1},qPn={minHeight:48};function $sr({mode:e,toggle:t}){let{socket:r,selection:n,launch:i,viewLaunchedSession:o,topBar:a,sidebarCollapse:s}=Fsr();return(0,Sf.jsx)(t7e.Provider,{value:a,children:(0,Sf.jsx)(R7e.Provider,{value:s,children:(0,Sf.jsx)(gB.Provider,{value:n,children:(0,Sf.jsxs)(G0e.Provider,{value:i,children:[(0,Sf.jsx)(sDe.Provider,{value:r.daemonVersion,children:(0,Sf.jsx)(lar,{mode:e,toggle:t,reconnecting:r.reconnecting})}),(0,Sf.jsx)(hde,{position:"fixed",elevation:1,sx:GPn,children:(0,Sf.jsx)(zor,{socket:r,selection:n})}),(0,Sf.jsx)(Kw,{variant:"dense",sx:qPn}),(0,Sf.jsx)(far,{socket:r,children:(0,Sf.jsx)(Fir,{socket:r})}),(0,Sf.jsx)(Jir,{socket:r,onViewLaunchedSession:o})]})})})})}var zsr=$(_e(),1);function Usr(){let[e,t]=(0,zsr.useState)(()=>{try{return localStorage.getItem("theme-mode")??"dark"}catch{return"dark"}});return{mode:e,toggle:()=>t(n=>{let i=n==="dark"?"light":"dark";try{localStorage.setItem("theme-mode",i)}catch{}return i})}}var aw=$(V(),1),jPn={MuiButtonBase:{styleOverrides:{root:{cursor:"pointer","&.Mui-disabled":{cursor:"default"}}}},MuiLink:{styleOverrides:{root:{cursor:"pointer"}}}};function YPn(){let{mode:e,toggle:t}=Usr(),r=(0,Wsr.useMemo)(()=>Vg({palette:{mode:e,...e==="dark"&&{background:{default:"#1e1e1e",paper:"#252526"}}},components:jPn}),[e]);return(0,aw.jsxs)(JG,{theme:r,children:[(0,aw.jsx)(Hq,{}),(0,aw.jsx)($sr,{mode:e,toggle:t})]})}var KPn=B0e([{path:"*",element:(0,aw.jsx)(YPn,{})}]);function XPn(){return(0,aw.jsx)(A0e,{router:KPn})}var Hsr=document.getElementById("app");Hsr&&(0,Vsr.createRoot)(Hsr).render((0,aw.jsx)(XPn,{}));})();
3975
3975
  /*! Bundled license information:
3976
3976
 
3977
3977
  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.616.2",
9
+ version: "0.616.3",
10
10
  type: "module",
11
11
  main: "dist/index.js",
12
12
  bin: {
@@ -8087,7 +8087,8 @@ function buildResumePrompt() {
8087
8087
 
8088
8088
  // src/commands/backlog/resumeNudge.ts
8089
8089
  function resumeNudge() {
8090
- return process.env.ASSIST_RESUME_IDLE ? "" : buildResumePrompt();
8090
+ if (process.env.ASSIST_RESUME_IDLE) return "";
8091
+ return process.env.ASSIST_RESUME_PROMPT || buildResumePrompt();
8091
8092
  }
8092
8093
 
8093
8094
  // src/commands/backlog/launchPhaseSession.ts
@@ -22366,7 +22367,7 @@ function registerCreateIssue(issueCommand) {
22366
22367
  []
22367
22368
  ).addHelpText(
22368
22369
  "after",
22369
- "\nThere is no What/Why/How template: an issue reports a problem, and the target repo's own issue template is unknowable from here. Write the body as the repo's maintainers would expect.\nIn an assist web session the title and body are previewed for approve/reject first (with inline comments); nothing is created until it is approved.\n--type, --parent, --project, --status and --label are all resolved before the preview, so an unknown name, an unreadable parent, a missing project scope or --status without --project creates nothing.\nA bare --parent number is read against --repo, or the current repo; a parent in another repository is allowed.\nThe project scope is needed for --project: gh auth refresh -h github.com -s project"
22370
+ "\nThere is no What/Why/How template: an issue reports a problem, and the target repo's own issue template is unknowable from here. Write the body as the repo's maintainers would expect.\nIn an assist web session the title and body are previewed for approve/reject first (with inline comments); nothing is created until it is approved.\nThe reviewer may also drop or paste screenshots into the pane; on approval these are appended to the issue body under a ## Screenshots section automatically, and on rejection they are discarded \u2014 so never author that section yourself.\n--type, --parent, --project, --status and --label are all resolved before the preview, so an unknown name, an unreadable parent, a missing project scope or --status without --project creates nothing.\nA bare --parent number is read against --repo, or the current repo; a parent in another repository is allowed.\nThe project scope is needed for --project: gh auth refresh -h github.com -s project"
22370
22371
  ).action(createIssue);
22371
22372
  }
22372
22373
 
@@ -23378,6 +23379,7 @@ var persistedSessionSchema = z8.object({
23378
23379
  autoAdvance: z8.boolean().optional(),
23379
23380
  reviewStarted: z8.boolean().optional(),
23380
23381
  launchedFrom: z8.string().optional(),
23382
+ interrupted: z8.object({ reason: z8.string(), at: z8.number() }).optional(),
23381
23383
  undurable: z8.object({ reason: z8.string(), removesTree: z8.boolean().optional() }).optional()
23382
23384
  });
23383
23385
 
@@ -23410,6 +23412,7 @@ function toPersistedSession(session) {
23410
23412
  autoAdvance: session.autoAdvance,
23411
23413
  reviewStarted: session.reviewStarted,
23412
23414
  launchedFrom: session.launchedFrom,
23415
+ interrupted: session.interrupted,
23413
23416
  undurable: session.undurable
23414
23417
  };
23415
23418
  }
@@ -37282,6 +37285,74 @@ function hasTranscriptOnDisk(persisted) {
37282
37285
  return !!persisted.claudeSessionId && !!findTranscriptPathSync(persisted.cwd, persisted.claudeSessionId);
37283
37286
  }
37284
37287
 
37288
+ // src/commands/sessions/daemon/daemonRestartPrompt.ts
37289
+ function daemonRestartPrompt(backgroundTaskIds) {
37290
+ const preamble = "The assist sessions daemon restarted and killed this session's processes. This was not a deliberate stop and nothing you were running was told to finish.";
37291
+ if (backgroundTaskIds.length === 0)
37292
+ return `${preamble} Continue from where you left off.`;
37293
+ return `${preamble} It killed ${backgroundTaskIds.length} background task(s) that were still running (${backgroundTaskIds.join(", ")}); their output files end where the kill landed, with no exit code. Treat them as killed by the restart, not as interrupted by the user, and restart any of them that should still be running.`;
37294
+ }
37295
+
37296
+ // src/commands/sessions/shared/unfinishedBackgroundTasks.ts
37297
+ var TASK_ID = /<task-id>([^<]+)<\/task-id>/g;
37298
+ function unfinishedBackgroundTasks(entries) {
37299
+ const inFlight2 = /* @__PURE__ */ new Set();
37300
+ for (const entry of entries) {
37301
+ const started = startedTaskId(entry);
37302
+ if (started) inFlight2.add(started);
37303
+ for (const notified of notifiedTaskIds(entry)) inFlight2.delete(notified);
37304
+ }
37305
+ return [...inFlight2];
37306
+ }
37307
+ function startedTaskId(entry) {
37308
+ const result = asRecord4(entry.toolUseResult);
37309
+ return typeof result?.backgroundTaskId === "string" ? result.backgroundTaskId : void 0;
37310
+ }
37311
+ function notifiedTaskIds(entry) {
37312
+ const text18 = taskNotificationText(entry);
37313
+ if (!text18) return [];
37314
+ return [...text18.matchAll(TASK_ID)].map((match) => match[1]);
37315
+ }
37316
+ function taskNotificationText(entry) {
37317
+ const content = asRecord4(entry.message)?.content ?? entry.content;
37318
+ return typeof content === "string" && content.includes("<task-notification>") ? content : void 0;
37319
+ }
37320
+ function asRecord4(value) {
37321
+ return value && typeof value === "object" ? value : null;
37322
+ }
37323
+
37324
+ // src/commands/sessions/daemon/interruptedBackgroundTasks.ts
37325
+ function interruptedBackgroundTasks(persisted) {
37326
+ if (!persisted.claudeSessionId) return [];
37327
+ const filePath = findTranscriptPathSync(
37328
+ persisted.cwd,
37329
+ persisted.claudeSessionId
37330
+ );
37331
+ if (!filePath) return [];
37332
+ return unfinishedBackgroundTasks(readTranscriptTailSync(filePath));
37333
+ }
37334
+
37335
+ // src/commands/sessions/daemon/SessionInterruption.ts
37336
+ var DAEMON_RESTART = "daemon-restart";
37337
+ function daemonRestartInterruption() {
37338
+ return { reason: DAEMON_RESTART, at: Date.now() };
37339
+ }
37340
+ function killedByDaemonRestart(interrupted) {
37341
+ return interrupted?.reason === DAEMON_RESTART;
37342
+ }
37343
+
37344
+ // src/commands/sessions/daemon/restoreResumePlan.ts
37345
+ function restoreResumePlan(persisted, idle) {
37346
+ if (!killedByDaemonRestart(persisted.interrupted)) return { idle };
37347
+ const tasks = interruptedBackgroundTasks(persisted);
37348
+ if (idle && tasks.length === 0) return { idle: true };
37349
+ return { prompt: daemonRestartPrompt(tasks), idle: false };
37350
+ }
37351
+ function resumePrompt(plan2) {
37352
+ if (plan2.idle) return void 0;
37353
+ return plan2.prompt ?? buildResumePrompt();
37354
+ }
37355
+
37285
37356
  // src/commands/sessions/daemon/runningSession.ts
37286
37357
  function runningSession(base, persisted, pty2) {
37287
37358
  return restoredSession(base, persisted, pty2, "running");
@@ -37314,13 +37385,14 @@ function restoredSession(base, persisted, pty2, status3) {
37314
37385
  // src/commands/sessions/daemon/restoreCodexSession.ts
37315
37386
  function restoreCodexSession(id, persisted, base, idle) {
37316
37387
  if (!persisted.harnessSessionId) return null;
37388
+ const plan2 = restoreResumePlan(persisted, idle);
37317
37389
  const pty2 = spawnCodex2({
37318
37390
  resumeSessionId: persisted.harnessSessionId,
37319
- prompt: idle ? void 0 : buildResumePrompt(),
37391
+ prompt: resumePrompt(plan2),
37320
37392
  cwd: persisted.cwd,
37321
37393
  sessionId: id
37322
37394
  });
37323
- return idle ? waitingSession(base, persisted, pty2) : runningSession(base, persisted, pty2);
37395
+ return plan2.idle ? waitingSession(base, persisted, pty2) : runningSession(base, persisted, pty2);
37324
37396
  }
37325
37397
 
37326
37398
  // src/commands/sessions/daemon/unresumableReason.ts
@@ -37333,10 +37405,11 @@ function unresumableReason(harness) {
37333
37405
  // src/commands/sessions/daemon/resumeViaClaude.ts
37334
37406
  function resumeViaClaude(id, persisted, base, idle) {
37335
37407
  const mode = { design: persisted.design, auto: persisted.auto };
37408
+ const plan2 = restoreResumePlan(persisted, idle);
37336
37409
  const pty2 = spawnClaude2(
37337
37410
  hasTranscriptOnDisk(persisted) ? {
37338
37411
  resumeSessionId: persisted.claudeSessionId,
37339
- prompt: idle ? void 0 : buildResumePrompt(),
37412
+ prompt: resumePrompt(plan2),
37340
37413
  cwd: persisted.cwd,
37341
37414
  sessionId: id,
37342
37415
  ...mode
@@ -37347,7 +37420,7 @@ function resumeViaClaude(id, persisted, base, idle) {
37347
37420
  ...mode
37348
37421
  }
37349
37422
  );
37350
- return idle ? waitingSession(base, persisted, pty2) : runningSession(base, persisted, pty2);
37423
+ return plan2.idle ? waitingSession(base, persisted, pty2) : runningSession(base, persisted, pty2);
37351
37424
  }
37352
37425
 
37353
37426
  // src/commands/sessions/daemon/restoreInteractiveSession.ts
@@ -37386,9 +37459,10 @@ function notRestoredStub(base, persisted) {
37386
37459
  }
37387
37460
 
37388
37461
  // src/commands/sessions/daemon/resumedRunEnv.ts
37389
- function resumedRunEnv(itemId2, idle) {
37462
+ function resumedRunEnv(itemId2, plan2) {
37390
37463
  const env = {};
37391
- if (idle) env.ASSIST_RESUME_IDLE = "1";
37464
+ if (plan2.idle) env.ASSIST_RESUME_IDLE = "1";
37465
+ if (plan2.prompt) env.ASSIST_RESUME_PROMPT = plan2.prompt;
37392
37466
  if (itemId2 != null && isPausePending(itemId2)) env.ASSIST_KEEP_PAUSE = "1";
37393
37467
  return Object.keys(env).length > 0 ? env : void 0;
37394
37468
  }
@@ -37430,13 +37504,14 @@ function restoreSession(id, persisted) {
37430
37504
  if (needsWrapperRelaunch(persisted)) {
37431
37505
  const resumesWrittenConversation = hasTranscriptOnDisk(persisted);
37432
37506
  const reattachesIdleConversation = idle && resumesWrittenConversation;
37507
+ const plan2 = restoreResumePlan(persisted, reattachesIdleConversation);
37433
37508
  const pty2 = spawnPty(
37434
37509
  resumesWrittenConversation ? assistResumeArgs(persisted) : assistResumeArgs({ assistArgs: persisted.assistArgs }),
37435
37510
  persisted.cwd,
37436
37511
  id,
37437
- resumedRunEnv(persisted.activity?.itemId, reattachesIdleConversation)
37512
+ resumedRunEnv(persisted.activity?.itemId, plan2)
37438
37513
  );
37439
- return reattachesIdleConversation ? waitingSession(base, persisted, pty2) : runningSession(base, persisted, pty2);
37514
+ return plan2.idle ? waitingSession(base, persisted, pty2) : runningSession(base, persisted, pty2);
37440
37515
  }
37441
37516
  return restoreInteractiveSession(id, persisted, base, idle);
37442
37517
  }
@@ -38107,10 +38182,15 @@ function setSessionTitle(sessions, id, title) {
38107
38182
 
38108
38183
  // src/commands/sessions/daemon/shutdownSessions.ts
38109
38184
  function shutdownSessions(sessions) {
38110
- daemonLog(`shutting down: killing ${sessions.size} session(s)`);
38185
+ const doomed = [...sessions.values()].filter((s) => s.status !== "done");
38186
+ daemonLog(
38187
+ `shutting down: killing ${doomed.length} session(s): ${describeAll(doomed)}`
38188
+ );
38189
+ for (const session of doomed)
38190
+ session.interrupted = daemonRestartInterruption();
38191
+ recordInterruptions(sessions);
38111
38192
  let failures = 0;
38112
- for (const session of sessions.values()) {
38113
- if (session.status === "done") continue;
38193
+ for (const session of doomed) {
38114
38194
  try {
38115
38195
  session.pty?.kill();
38116
38196
  } catch (error) {
@@ -38126,6 +38206,19 @@ function shutdownSessions(sessions) {
38126
38206
  `shutting down: ${failures} session(s) failed to die; continuing so the process still exits and releases its listeners`
38127
38207
  );
38128
38208
  }
38209
+ function describeAll(doomed) {
38210
+ return doomed.length === 0 ? "none" : doomed.map((s) => `${s.name} (${s.id})`).join(", ");
38211
+ }
38212
+ function recordInterruptions(sessions) {
38213
+ try {
38214
+ persistLiveSessions(sessions);
38215
+ } catch (error) {
38216
+ const reason4 = error instanceof Error ? error.message : String(error);
38217
+ daemonLog(
38218
+ `shutting down: could not record the restart against the sessions (${reason4}); they will resume without knowing why they stopped`
38219
+ );
38220
+ }
38221
+ }
38129
38222
 
38130
38223
  // src/commands/sessions/daemon/heldStartBlocked.ts
38131
38224
  function heldStartBlocked(session, sessions) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staff0rd/assist",
3
- "version": "0.616.2",
3
+ "version": "0.616.3",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "bin": {