@staff0rd/assist 0.670.0 → 0.672.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -55,7 +55,7 @@ After installation, the `assist` command will be available globally. You can als
55
55
  - `/handover` - Write a session handover note for the next conversation
56
56
  - `/pr` - Raise a PR with a concise description, then watch CI in the background
57
57
  - `/prs-slack <number> [--no-confirm]` - Post a PR's title and URL to the Slack channel configured in `prs.slack`; `--no-confirm` skips the confirmation and posts straight away (used by chained announces)
58
- - `/prs-status [channel] <owner/repo>...` - Run `assist prs status <repos> --json` over the named repos and compose a markdown overview of what is still pending merge, sorting each open PR into pending review, changes requested, failing checks or ready to merge, excluding drafts (counted, not listed), re-listing anything untouched for 7+ days as stale, and naming any repo that could not be read. The overview goes through `assist slack post` for approve/reject in the preview pane and is posted to Slack on approval; the channel falls back to `slack.channel`
58
+ - `/prs-status [channel] <owner/repo>...` - Post an overview of the open PRs across the named repos to Slack: a summary line in the channel, the PRs grouped by what they are waiting on in its thread; the channel falls back to `slack.channel`
59
59
  - `/refactor` - Run refactoring checks for code quality
60
60
  - `/prompts` - Analyze denied tool calls and suggest settings changes to auto-allow recurring prompts
61
61
  - `/recall` - Recall the most recent handover note for this repo
@@ -67,7 +67,7 @@ After installation, the `assist` command will be available globally. You can als
67
67
  - `/github [action] [ref] [args]` - GitHub issue actions: `view`, `edit`, `associate`, `update`, `started`, `done`, `help`. `[ref]` is optional — it resolves from the session's backlog item. A bare `/github <ref>` runs `edit`, which opens the issue in the web preview pane; outside a web session the command prints the issue to chat instead
68
68
  - `/journal` - Append a journal entry summarising recent work
69
69
  - `/next [id]` - Signal completion and chain into the next backlog item
70
- - `/slack-post [channel] [--thread <ts-or-permalink>] <what to say>` - Compose a markdown message, preview it in the web pane via `assist slack post`, then post the approved body to that Slack channel with the Slack MCP connector and report the permalink. The channel falls back to `slack.channel`; `--thread` posts the message as a reply in that thread
70
+ - `/slack-post [channel] [--thread <ts-or-permalink>] <what to say>` - Compose a markdown message, preview it in the web pane via `assist slack post`, then post the approved body to that Slack channel with the Slack MCP connector and report the permalink. The channel falls back to `slack.channel`; `--thread` posts the message as a reply in that thread. Asked for a thread of several messages, it composes all of them up front and previews the batch in a single `assist slack post --parts` call — a pane per message, in order — and posts nothing until every one is approved: the first message opens the thread and the rest follow under the `thread_ts` it returns, or all of them reply under the resolved `thread_ts` when `--thread` was given. A rejection posts nothing at all; the rejected message is revised in its working file and the whole batch re-previewed from the first message
71
71
  - `/standup` - Summarise recent journal entries as a standup update
72
72
  - `/subtask <text>` - Add a sub-task to the session's current backlog item
73
73
  - `/strip-code-comments` - Strip redundant comments from tracked source files
@@ -313,7 +313,7 @@ The Config tab of the sessions web dashboard never receives secret values: `GET
313
313
  - `assist seq set-connection <name>` - Set the default Seq connection
314
314
  - `assist seq query <filter>` - Query Seq events (`-c <connection>`, `--json`, `-n <count>`, `--from <date>`, `--to <date>`)
315
315
  - `assist slack post [channel] --body <body|-> | --parts <file>... [--thread <ts-or-permalink>]` - Preview a markdown message bound for a Slack channel; `--body -` reads it from stdin. The channel falls back to `slack.channel` when the argument is omitted, and the command errors naming the `assist config set slack.channel` setter when neither is given. `--thread` takes a message ts (`1712345678.123456`) or a Slack archives permalink (`.../archives/C012AB3CD/p1712345678123456`, whose `thread_ts` query parameter wins when present, so a link to a reply resolves to its parent) and resolves it to the `thread_ts` the reply is posted under; anything else is a usage error. Posting is MCP-only, so the command never posts: in an assist web session it renders the markdown in the preview pane for approve/reject (with inline comments), and on approval writes the approved body to a working file under `~/.assist/slack/`, printing its path on the last line — preceded by the resolved `thread_ts` — for `/slack-post` to send. On rejection it exits non-zero with the reason and any inline comments, leaving the previewed markdown in that working file to revise in place and re-preview. Outside a web session there is no preview and the body passes straight through
316
- - `--parts <file>...` previews a whole thread — the files holding its messages, in thread order — so none of them is handed back until all of them are approved. Each part gets its own working file under `~/.assist/slack/` (`eng-1.md`, `eng-2.md`, …) and its own preview pane, popped in sequence and titled with the target and its position in the batch (`Post to #eng (2/3)`). Only after the last part is approved does the command print every working-file path, in thread order. The first rejection halts the batch: it exits non-zero naming that part's position, the reason, every inline comment with its excerpt, and that part's working file, and prints no paths — revise that file in place and re-run the whole batch, which re-previews from part 1. A missing or empty part file, or `--parts` together with `--body`, is an error raised before any pane opens
316
+ - `--parts <file>...` previews a whole thread — the files holding its messages, in thread order — so none of them is handed back until all of them are approved. Each part gets its own working file under `~/.assist/slack/` (`eng-1.md`, `eng-2.md`, …) and its own preview pane, popped in sequence and titled with the target and its position in the batch (`Post to #eng (2/3)`). Only after the last part is approved does the command print anything: a line naming the target, then every working-file path in thread order prefixed with its position (`2/3`), then a line saying how to thread them — without `--thread` part 1 opens the thread and the rest carry the `thread_ts` it returns, with `--thread` every part is a reply under the resolved `thread_ts`. The first rejection halts the batch: it exits non-zero naming that part's position, the reason, every inline comment with its excerpt, and that part's working file, and prints no paths — revise that file in place and re-run the whole batch, which re-previews from part 1. A missing or empty part file, or `--parts` together with `--body`, is an error raised before any pane opens
317
317
  - `assist sql auth add` - Add a new MSSQL connection
318
318
  - `assist sql auth list` - List configured SQL connections
319
319
  - `assist sql auth remove <name>` - Remove a configured connection
@@ -34,11 +34,17 @@ Each remaining PR belongs in exactly one section, taking the first that matches:
34
34
 
35
35
  ## Step 4: Compose the overview
36
36
 
37
- Write the overview to a scratch file with the Write tool — it contains backticks, quotes and newlines, so never inline it in a shell command. Plain markdown, no wrapping code fence: Slack renders markdown as it is. Slack does not render headings, so every section label is bold text, not `#`. Each PR line already names its repo, so the opening line does not list the repos again.
37
+ The overview is posted as two messages: the summary line in the channel, and every section under it as a reply in that message's thread. Write each to its own scratch file with the Write tool — they contain backticks, quotes and newlines, so never inline them in a shell command. Plain markdown, no wrapping code fence: Slack renders markdown as it is. Slack does not render headings, so every section label is bold text, not `#`. Each PR line already names its repo, so the summary does not list the repos again.
38
+
39
+ The summary file is one line, ending in a 🧵 that points at the thread:
38
40
 
39
41
  ```markdown
40
- **Open PRs** — <n> open across <n> repos (<n> drafts excluded): <n> pending review, <n> changes requested, <n> failing checks, <n> ready to merge.
42
+ **Open PRs** — <n> open across <n> repos (<n> drafts excluded): <n> pending review, <n> changes requested, <n> failing checks, <n> ready to merge. 🧵
43
+ ```
44
+
45
+ The reply file holds the sections:
41
46
 
47
+ ```markdown
42
48
  **Pending review**
43
49
 
44
50
  - [repo#123](url) — Title (author, updated 3d ago)
@@ -70,21 +76,31 @@ Write the overview to a scratch file with the Write tool — it contains backtic
70
76
 
71
77
  Omit any section with nothing in it. The stale section re-lists any PR whose `ageHours` is 168 or more, whichever bucket it sits in; mark bot-authored PRs with `[bot]` after the title. Include the "Could not be read" section whenever `errors` is non-empty, even if every other repo succeeded. When every open PR is a draft, or there are no open PRs at all, say so in one line and stop — do not preview an empty overview.
72
78
 
73
- ## Step 5: Preview it
79
+ ## Step 5: Preview and post the summary
74
80
 
75
81
  ```bash
76
- assist slack post '<channel>' --body - < <scratch file>
82
+ assist slack post '<channel>' --body - < <summary scratch file>
77
83
  ```
78
84
 
79
- In an assist web session this renders the overview in the preview pane for approve/reject. The command posts nothing either way.
85
+ In an assist web session this renders the message in the preview pane for approve/reject. The command posts nothing either way.
80
86
 
81
87
  - **Approved** — the last line of stdout is the path to the approved body under `~/.assist/slack/`. That file, not the scratch file, is what gets posted. The line above it names the target channel.
82
- - **Rejected** — the command exits non-zero with the reason and any inline comments, and names the same working file. Address every comment, rewrite that file in place, and re-run the preview against it. Do not post, and do not rebuild the overview from scratch — re-run `assist prs status` only if the rejection asks for fresh data.
83
-
84
- ## Step 6: Post it
88
+ - **Rejected** — the command exits non-zero with the reason and any inline comments, and names the same working file. Address every comment, rewrite that file in place, and re-run the preview against it. Do not post, and do not rebuild the overview from scratch — re-run `assist prs status` only if the rejection asks for fresh data. A comment on the summary that also applies to the sections is carried into the reply file before Step 6 previews it.
85
89
 
86
90
  Read the approved body from the path the command printed, then:
87
91
 
88
92
  1. Resolve the channel named on the `Approved for ...` line to its id with `mcp__claude_ai_Slack__slack_search_channels`, passing `channel_types: "public_channel,private_channel"`. If the query returns no match, or more than one plausible match, stop and ask the user which channel to use — do not guess.
89
93
  2. Post the file's contents verbatim with `mcp__claude_ai_Slack__slack_send_message` (`channel_id`, `message`).
90
- 3. Report the permalink it returns.
94
+ 3. Keep the permalink it returns — it is both the thread reference for Step 6 and what you report at the end.
95
+
96
+ ## Step 6: Preview and post the sections in the thread
97
+
98
+ ```bash
99
+ assist slack post '<channel>' --thread '<summary permalink>' --body - < <reply scratch file>
100
+ ```
101
+
102
+ `--thread` takes the permalink from Step 5; the command resolves it and prints the `thread_ts` above the approved body's path. Approval and rejection work exactly as in Step 5.
103
+
104
+ Post the approved body with `mcp__claude_ai_Slack__slack_send_message`, passing the same `channel_id` plus `thread_ts` set to the ts the command printed. Report the summary's permalink.
105
+
106
+ If the summary posted but the reply is rejected or fails, say so plainly — the channel now holds a 🧵 with nothing under it.
@@ -3,37 +3,50 @@ description: Preview a markdown message, then post it to a Slack channel
3
3
  allowed_args: "[channel] [--thread <ts-or-permalink>] <what to say>"
4
4
  ---
5
5
 
6
- Post a message to Slack on the user's behalf. `assist slack post` owns the preview and the approval; you own composing the markdown and sending it.
6
+ Post a message, or a thread of them, to Slack on the user's behalf. `assist slack post` owns the preview and the approval; you own composing the markdown and sending it.
7
7
 
8
8
  `$ARGUMENTS` may open with the target channel — `#name`, a bare name, or a channel id — followed by what the message should say. When no channel is given, omit it from the command and let `assist slack post` fall back to the `slack.channel` config key; if it errors because neither is set, pass on the setter it names rather than guessing a channel.
9
9
 
10
- A `--thread <ts-or-permalink>` argument means the message is a reply: pass it straight through to `assist slack post`. The reference is either a message ts (`1712345678.123456`) or a Slack archives permalink — the command resolves it and prints the resulting `thread_ts`.
10
+ A `--thread <ts-or-permalink>` argument means the message is a reply: pass it straight through to `assist slack post`. The reference is either a message ts (`1712345678.123456`) or a Slack archives permalink — the command resolves it once and applies it to every message you preview.
11
11
 
12
- ## Step 1: compose the message
12
+ Decide up front whether the ask is one message or a thread of several. Nothing is posted until the whole batch is approved, so compose every message before the first preview — never preview one, post it, then compose the next.
13
13
 
14
- Write the message as standard markdown. `slack_send_message` renders bold, italic, code, strikethrough, blockquotes, lists, links, code blocks (with a language specifier), tables and headers as they are, capped at 5000 characters — so no conversion to Slack's `*bold*` dialect, and no `<url|text>` links.
14
+ ## Step 1: compose every message
15
+
16
+ Write each message as standard markdown. `slack_send_message` renders bold, italic, code, strikethrough, blockquotes, lists, links, code blocks (with a language specifier), tables and headers as they are, capped at 5000 characters — so no conversion to Slack's `*bold*` dialect, and no `<url|text>` links.
15
17
 
16
18
  State only the confirmed conclusion and the facts behind it. No hedging, no speculative next steps, no pleasantries. Match the scope of what was asked.
17
19
 
18
- Write it to a scratch file with the Write tool rather than inlining it in a shell command — the markdown will contain quotes, backticks and newlines.
20
+ Write each message to its own scratch file with the Write tool rather than inlining it in a shell command — the markdown will contain quotes, backticks and newlines. For a thread, write all of them now, in thread order.
21
+
22
+ ## Step 2: preview them
19
23
 
20
- ## Step 2: preview it
24
+ One message:
21
25
 
22
26
  ```
23
27
  assist slack post '<channel>' [--thread '<ts-or-permalink>'] --body - < <scratch file>
24
28
  ```
25
29
 
26
- In an assist web session this renders the markdown in the preview pane for approve/reject. The command posts nothing either way.
30
+ A thread, in thread order:
31
+
32
+ ```
33
+ assist slack post '<channel>' [--thread '<ts-or-permalink>'] --parts <scratch file 1> <scratch file 2> ...
34
+ ```
35
+
36
+ In an assist web session this renders each message in the preview pane for approve/reject — one pane per part, in sequence, titled with the target and the part's position in the batch (`2/3`). The command posts nothing either way.
27
37
 
28
- - **Approved** — the last line of stdout is the path to the approved body under `~/.assist/slack/`. That file, not your scratch file, is what gets posted. The line above it names the target channel, and the resolved `thread_ts` when `--thread` was passed.
29
- - **Rejected** — the command exits non-zero with the reason and any inline comments, and names the same working file. Address every comment, rewrite that file in place, and re-run the preview against it (`assist slack post '<channel>' --body - < <working file>`). Do not post, and do not recompose the message from scratch.
38
+ - **Approved (`--body`)** — the last line of stdout is the path to the approved body under `~/.assist/slack/`. That file, not your scratch file, is what gets posted. The line above it names the target channel, and the resolved `thread_ts` when `--thread` was passed.
39
+ - **Approved (`--parts`)** — only after the last part is approved does the command print anything: a line naming the target, then one `k/N <path>` line per part in thread order under `~/.assist/slack/`, then a line saying how to thread them. Those files, not your scratch files, are what get posted.
40
+ - **Rejected** — the command exits non-zero with the reason and any inline comments, and names the working file of the message that was rejected (with its position, for a batch). No path is handed back, so nothing from the batch is posted. Address every comment, rewrite that working file in place, and re-run the same command with that working file in place of the scratch file it came from — a batch re-previews from part 1. Do not post, and do not recompose the messages from scratch.
30
41
 
31
- Outside a web session there is no pane: the body passes straight through and the working file is written immediately.
42
+ Outside a web session there is no pane: the bodies pass straight through and the working files are written immediately.
32
43
 
33
- ## Step 3: post it
44
+ ## Step 3: post them
34
45
 
35
- Read the approved body from the path the command printed, then:
46
+ Read the approved bodies from the paths the command printed, then:
36
47
 
37
48
  1. Resolve the channel to its id with `mcp__claude_ai_Slack__slack_search_channels` — use the channel the command's `Approved for ...` line names, which is the `slack.channel` default when you passed no argument — passing `channel_types: "public_channel,private_channel"` so private channels resolve too. If the query returns no match, or more than one plausible match, stop and ask the user which channel to use — do not guess.
38
- 2. Post the file's contents verbatim with `mcp__claude_ai_Slack__slack_send_message` (`channel_id`, `message`), adding `thread_ts` set to the ts the command printed when it printed one. Use `slack_send_message`, not `slack_send_message_draft`: the preview pane is the user's review.
39
- 3. Report the permalink it returns.
49
+ 2. Post each file's contents verbatim with `mcp__claude_ai_Slack__slack_send_message` (`channel_id`, `message`). Use `slack_send_message`, not `slack_send_message_draft`: the preview pane is the user's review.
50
+ - With `--thread`, every message carries `thread_ts` set to the ts the command printed.
51
+ - Without it, a batch is one new thread: post `1/N` to the channel with no `thread_ts`, then post `2/N` onwards in order, each with `thread_ts` set to the `ts` the first message returned.
52
+ 3. Report the permalink of the first message.
@@ -3970,7 +3970,7 @@ ${f.join(`
3970
3970
  `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),SOe&&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=hor(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=TOe(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,-SDe),SDe),t/=SDe,t/Math.abs(t)+Math.round(t*(Q8n-1)))}shouldForceSelection(e){return hhe?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(),J8n)}_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&&!(hhe&&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<eLn&&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=V8n(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,f=0,h=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&&(f++,y--),o.getWidth(v)===2&&(h++,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?(f++,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?(h++,v++):x>1&&(p+=x-1,l+=x-1),l++,v++}}l++;let m=s+u-f+d,g=Math.min(this._bufferService.cols,l-s+f+h-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=hor(r,this._bufferService.cols)}};nOe=es([br(3,gf),br(4,KE),br(5,pOe),br(6,yf),br(7,Dx),br(8,Ix)],nOe);var dor=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={}}},por=class{constructor(){this._color=new dor,this._css=new dor}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()}},pl=Object.freeze((()=>{let e=[Pa.toColor("#2e3436"),Pa.toColor("#cc0000"),Pa.toColor("#4e9a06"),Pa.toColor("#c4a000"),Pa.toColor("#3465a4"),Pa.toColor("#75507b"),Pa.toColor("#06989a"),Pa.toColor("#d3d7cf"),Pa.toColor("#555753"),Pa.toColor("#ef2929"),Pa.toColor("#8ae234"),Pa.toColor("#fce94f"),Pa.toColor("#729fcf"),Pa.toColor("#ad7fa8"),Pa.toColor("#34e2e2"),Pa.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})()),WE=Pa.toColor("#ffffff"),uG=Pa.toColor("#000000"),mor=Pa.toColor("#ffffff"),gor=uG,iG={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},nLn=WE,iOe=class extends Nn{constructor(e){super(),this._optionsService=e,this._contrastCache=new por,this._halfContrastCache=new por,this._onChangeColors=this._register(new ar),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:WE,background:uG,cursor:mor,cursorAccent:gor,selectionForeground:void 0,selectionBackgroundTransparent:iG,selectionBackgroundOpaque:Ko.blend(uG,iG),selectionInactiveBackgroundTransparent:iG,selectionInactiveBackgroundOpaque:Ko.blend(uG,iG),scrollbarSliderBackground:Ko.opacity(WE,.2),scrollbarSliderHoverBackground:Ko.opacity(WE,.4),scrollbarSliderActiveBackground:Ko.opacity(WE,.5),overviewRulerBorder:WE,ansi:pl.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=mo(e.foreground,WE),t.background=mo(e.background,uG),t.cursor=Ko.blend(t.background,mo(e.cursor,mor)),t.cursorAccent=Ko.blend(t.background,mo(e.cursorAccent,gor)),t.selectionBackgroundTransparent=mo(e.selectionBackground,iG),t.selectionBackgroundOpaque=Ko.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=mo(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Ko.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?mo(e.selectionForeground,lor):void 0,t.selectionForeground===lor&&(t.selectionForeground=void 0),Ko.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Ko.opacity(t.selectionBackgroundTransparent,.3)),Ko.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Ko.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=mo(e.scrollbarSliderBackground,Ko.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=mo(e.scrollbarSliderHoverBackground,Ko.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=mo(e.scrollbarSliderActiveBackground,Ko.opacity(t.foreground,.5)),t.overviewRulerBorder=mo(e.overviewRulerBorder,nLn),t.ansi=pl.slice(),t.ansi[0]=mo(e.black,pl[0]),t.ansi[1]=mo(e.red,pl[1]),t.ansi[2]=mo(e.green,pl[2]),t.ansi[3]=mo(e.yellow,pl[3]),t.ansi[4]=mo(e.blue,pl[4]),t.ansi[5]=mo(e.magenta,pl[5]),t.ansi[6]=mo(e.cyan,pl[6]),t.ansi[7]=mo(e.white,pl[7]),t.ansi[8]=mo(e.brightBlack,pl[8]),t.ansi[9]=mo(e.brightRed,pl[9]),t.ansi[10]=mo(e.brightGreen,pl[10]),t.ansi[11]=mo(e.brightYellow,pl[11]),t.ansi[12]=mo(e.brightBlue,pl[12]),t.ansi[13]=mo(e.brightMagenta,pl[13]),t.ansi[14]=mo(e.brightCyan,pl[14]),t.ansi[15]=mo(e.brightWhite,pl[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]=mo(e.extendedAnsi[n],pl[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()}}};iOe=es([br(0,yf)],iOe);function mo(e,t){if(e!==void 0)try{return Pa.toColor(e)}catch{}return t}var iLn=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)}},oLn=class{constructor(){this._services=new iLn,this._services.set(dOe,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let r=_Pn(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)}},aLn={trace:0,debug:1,info:2,warn:3,error:4,off:5},sLn="xterm.js: ",oOe=class extends Nn{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),lLn=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=aLn[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?"":sLn)+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)}};oOe=es([br(0,yf)],oOe);var lLn,yor=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}},Hn=3,Us=Object.freeze(new xG),Kfe=0,CDe=2,fG=class Mar{constructor(t,r,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(t*Hn);let i=r||xm.fromCharData([0,Uor,1,0]);for(let o=0;o<t;++o)this.setCell(o,i);this.length=t}get(t){let r=this._data[t*Hn+0],n=r&2097151;return[this._data[t*Hn+1],r&2097152?this._combined[t]:n?lw(n):"",r>>22,r&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n]}set(t,r){this._data[t*Hn+1]=r[0],r[1].length>1?(this._combined[t]=r[1],this._data[t*Hn+0]=t|2097152|r[2]<<22):this._data[t*Hn+0]=r[1].charCodeAt(0)|r[2]<<22}getWidth(t){return this._data[t*Hn+0]>>22}hasWidth(t){return this._data[t*Hn+0]&12582912}getFg(t){return this._data[t*Hn+1]}getBg(t){return this._data[t*Hn+2]}hasContent(t){return this._data[t*Hn+0]&4194303}getCodePoint(t){let r=this._data[t*Hn+0];return r&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):r&2097151}isCombined(t){return this._data[t*Hn+0]&2097152}getString(t){let r=this._data[t*Hn+0];return r&2097152?this._combined[t]:r&2097151?lw(r&2097151):""}isProtected(t){return this._data[t*Hn+2]&536870912}loadCell(t,r){return Kfe=t*Hn,r.content=this._data[Kfe+0],r.fg=this._data[Kfe+1],r.bg=this._data[Kfe+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*Hn+0]=r.content,this._data[t*Hn+1]=r.fg,this._data[t*Hn+2]=r.bg}setCellFromCodepoint(t,r,n,i){i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*Hn+0]=r|n<<22,this._data[t*Hn+1]=i.fg,this._data[t*Hn+2]=i.bg}addCodepointToCell(t,r,n){let i=this._data[t*Hn+0];i&2097152?this._combined[t]+=lw(r):i&2097151?(this._combined[t]=lw(i&2097151)+lw(r),i&=-2097152,i|=2097152):i=r|1<<22,n&&(i&=-12582913,i|=n<<22),this._data[t*Hn+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 xm;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 xm;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*CDe<this._data.buffer.byteLength;let n=t*Hn;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*CDe<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*CDe<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 Mar(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*Hn+0]&4194303)return t+(this._data[t*Hn+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*Hn+0]&4194303||this._data[t*Hn+2]&50331648)return t+(this._data[t*Hn+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<Hn;u++)this._data[(n+l)*Hn+u]=a[(r+l)*Hn+u];a[(r+l)*Hn+2]&268435456&&(this._extendedAttrs[n+l]=t._extendedAttrs[r+l])}else for(let l=0;l<i;l++){for(let u=0;u<Hn;u++)this._data[(n+l)*Hn+u]=a[(r+l)*Hn+u];a[(r+l)*Hn+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*Hn+0],s=a&2097151,l=a&2097152?this._combined[r]:s?lw(s):cw;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 cLn(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 f=[e.get(s)];for(;l<e.length&&u.isWrapped;)f.push(u),u=e.get(++l);if(!o&&n>=s&&n<l){s+=f.length-1;continue}let h=0,d=bG(f,h,t),p=1,m=0;for(;p<f.length;){let y=bG(f,p,t),v=y-m,b=r-d,x=Math.min(v,b);f[h].copyCellsFrom(f[p],m,d,x,!1),d+=x,d===r&&(h++,d=0),m+=x,m===y&&(p++,m=0),d===0&&h!==0&&f[h-1].getWidth(r-1)===2&&(f[h].copyCellsFrom(f[h-1],r-1,d++,1,!1),f[h-1].setCell(r-1,i))}f[h].replaceCells(d,r,i);let g=0;for(let y=f.length-1;y>0&&(y>h||f[y].getTrimmedLength()===0);y--)g++;g>0&&(a.push(s+f.length-g),a.push(g)),s+=f.length-1}return a}function uLn(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 fLn(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 hLn(e,t,r){let n=[],i=e.map((l,u)=>bG(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=bG(e,a,t);o>l&&(o-=l,a++);let u=e[a].getWidth(o-1)===2;u&&o--;let f=u?r-1:r;n.push(f),s+=f}return n}function bG(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 Iar=class Dar{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=Dar._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(),jE(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};Iar._nextId=1;var dLn=Iar,gl={},VE=gl.B;gl[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"};gl.A={"#":"\xA3"};gl.B=void 0;gl[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"};gl.C=gl[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};gl.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"};gl.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"};gl.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"};gl.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"};gl.E=gl[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"};gl.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"};gl.H=gl[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};gl["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"};var vor=4294967295,bor=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=VE,this.markers=[],this._nullCell=xm.fromCharData([0,Uor,1,0]),this._whitespaceCell=xm.fromCharData([0,cw,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new dhe,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new yor(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 ahe),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 ahe),this._whitespaceCell}getBlankLine(e,t){return new fG(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>vor?vor: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 yor(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 fG(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 fG(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=cLn(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Us),r);if(n.length>0){let i=uLn(this.lines,n);fLn(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 fG(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(),f=hLn(l,this._cols,e),h=f.length-l.length,d;this.ybase===0&&this.y!==this.lines.length-1?d=Math.max(0,this.y-this.lines.maxLength+h):d=Math.max(0,this.lines.length-this.lines.maxLength+h);let p=[];for(let x=0;x<h;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=f.length-1,g=f[m];g===0&&(m--,g=f[m]);let y=l.length-h-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=f[m]),v-=x,v===0){y--;let C=Math.max(y,0);v=bG(l,C,this._cols)}}for(let x=0;x<l.length;x++)f[x]<e&&l[x].setCell(f[x],n);let b=h-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+h,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,f=0,h=i[f];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(h&&h.start>u+d){for(let y=h.newLines.length-1;y>=0;y--)this.lines.set(g--,h.newLines[y]);g++,a.push({index:u+1,amount:h.newLines.length}),d+=h.newLines.length,h=i[++f]}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 dLn(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)}},pLn=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 bor(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new bor(!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)}},Oar=2,Nar=1,aOe=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,Oar),this.rows=Math.max(e.rawOptions.rows||0,Nar),this.buffers=this._register(new pLn(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))}};aOe=es([br(0,yf)],aOe);var VO={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:hhe,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},mLn=["normal","bold","100","200","300","400","500","600","700","800","900"],gLn=class extends Nn{constructor(e){super(),this._onOptionChange=this._register(new ar),this.onOptionChange=this._onOptionChange.event;let t={...VO};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(Xo(()=>{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 VO))throw new Error(`No option with key "${r}"`);return this.rawOptions[r]},t=(r,n)=>{if(!(r in VO))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=VO[e]),!yLn(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=VO[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=mLn.includes(t)?t:VO[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 yLn(e){return e==="block"||e==="underline"||e==="bar"}function hG(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]&&hG(e[n],t-1);return r}var xor=Object.freeze({insertMode:!1}),Tor=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),sOe=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=hG(xor),this.decPrivateModes=hG(Tor)}reset(){this.modes=hG(xor),this.decPrivateModes=hG(Tor)}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))}};sOe=es([br(0,gf),br(1,qor),br(2,yf)],sOe);var Sor={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 wDe(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 _De=String.fromCharCode,Cor={DEFAULT:e=>{let t=[wDe(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${_De(t[0])}${_De(t[1])}${_De(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${wDe(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${wDe(e,!0)};${e.x};${e.y}${t}`}},lOe=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(Sor))this.addProtocol(n,Sor[n]);for(let n of Object.keys(Cor))this.addEncoding(n,Cor[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)}};lOe=es([br(0,gf),br(1,KE),br(2,yf)],lOe);var kDe=[[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]],vLn=[[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]],ml;function bLn(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 xLn=class{constructor(){if(this.version="6",!ml){ml=new Uint8Array(65536),ml.fill(1),ml[0]=0,ml.fill(0,1,32),ml.fill(0,127,160),ml.fill(2,4352,4448),ml[9001]=2,ml[9002]=2,ml.fill(2,11904,42192),ml[12351]=1,ml.fill(2,44032,55204),ml.fill(2,63744,64256),ml.fill(2,65040,65050),ml.fill(2,65072,65136),ml.fill(2,65280,65377),ml.fill(2,65504,65511);for(let e=0;e<kDe.length;++e)ml.fill(0,kDe[e][0],kDe[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?ml[e]:bLn(e,vLn)?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=GE.extractWidth(t);i===0?n=!1:i>r&&(r=i)}return GE.createPropertyValue(0,r,n)}},GE=class ohe{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new ar,this.onChange=this._onChange.event;let t=new xLn;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=ohe.extractWidth(s);ohe.extractShouldJoin(s)&&(l-=ohe.extractWidth(n)),r+=l,n=s}return r}charProperties(t,r){return this._activeProvider.charProperties(t,r)}},TLn=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 wor(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 oG=2147483647,SLn=256,Bar=class cOe{constructor(t=32,r=32){if(this.maxLength=t,this.maxSubParamsLength=r,r>SLn)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 cOe;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 cOe(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>oG?oG: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>oG?oG: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,oG):t}},aG=[],CLn=class{constructor(){this._state=0,this._active=aG,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=aG}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=aG,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||aG,!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",mhe(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=aG,this._id=-1,this._state=0}}},Fd=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+=mhe(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}},sG=[],wLn=class{constructor(){this._handlers=Object.create(null),this._active=sG,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=sG}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=sG,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||sG,!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",mhe(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=sG,this._ident=0}},dG=new Bar;dG.addParam(0);var _or=class{constructor(e){this._handler=e,this._data="",this._params=dG,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():dG,this._data="",this._hitLimit=!1}put(e,t,r){this._hitLimit||(this._data+=mhe(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=dG,this._data="",this._hitLimit=!1,r));return this._params=dG,this._data="",this._hitLimit=!1,t}},_Ln=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}},bm=160,kLn=(function(){let e=new _Ln(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(bm,0,2,0),e.add(bm,8,5,8),e.add(bm,6,0,6),e.add(bm,11,0,11),e.add(bm,13,13,13),e})(),ELn=class extends Nn{constructor(e=kLn){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 Bar,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(Xo(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new CLn),this._dcsParser=this._register(new wLn),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:bm)],i>>4){case 2:for(let d=s+1;;++d){if(d>=t||(n=e[d])<32||n>126&&n<bm){this._printHandler(e,s,d),s=d-1;break}if(++d>=t||(n=e[d])<32||n>126&&n<bm){this._printHandler(e,s,d),s=d-1;break}if(++d>=t||(n=e[d])<32||n>126&&n<bm){this._printHandler(e,s,d),s=d-1;break}if(++d>=t||(n=e[d])<32||n>126&&n<bm){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 f=this._escHandlers[this._collect<<8|n],h=f?f.length-1:-1;for(;h>=0&&(a=f[h](),a!==!0);h--)if(a instanceof Promise)return this._preserveStack(4,f,h,i,s),a;h<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<bm){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<bm){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}}},RLn=/^([\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})$/,ALn=/^[\da-f]+$/;function kor(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf("rgb:")===0){t=t.slice(4);let r=RLn.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),ALn.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 EDe(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 PLn(e,t=16){let[r,n,i]=e;return`rgb:${EDe(r,t)}/${EDe(n,t)}/${EDe(i,t)}`}var LLn={"(":0,")":1,"*":2,"+":3,"-":1,".":2},sw=131072,Eor=10;function Ror(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 Aor=5e3,Por=0,MLn=class extends Nn{constructor(e,t,r,n,i,o,a,s,l=new ELn){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 CPn,this._utf8Decoder=new wPn,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 uOe(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(u=>this._activeBuffer=u.activeBuffer)),this._parser.setCsiHandlerFallback((u,f)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(u),params:f.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,f,h)=>{this._logService.debug("Unknown OSC code: ",{identifier:u,action:f,data:h})}),this._parser.setDcsHandlerFallback((u,f,h)=>{f==="HOOK"&&(h=h.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(u),action:f,payload:h})}),this._parser.setPrintHandler((u,f,h)=>this.print(u,f,h)),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(nhe.IND,()=>this.index()),this._parser.setExecuteHandler(nhe.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(nhe.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Fd(u=>(this.setTitle(u),this.setIconName(u),!0))),this._parser.registerOscHandler(1,new Fd(u=>this.setIconName(u))),this._parser.registerOscHandler(2,new Fd(u=>this.setTitle(u))),this._parser.registerOscHandler(4,new Fd(u=>this.setOrReportIndexedColor(u))),this._parser.registerOscHandler(8,new Fd(u=>this.setHyperlink(u))),this._parser.registerOscHandler(10,new Fd(u=>this.setOrReportFgColor(u))),this._parser.registerOscHandler(11,new Fd(u=>this.setOrReportBgColor(u))),this._parser.registerOscHandler(12,new Fd(u=>this.setOrReportCursorColor(u))),this._parser.registerOscHandler(104,new Fd(u=>this.restoreIndexedColor(u))),this._parser.registerOscHandler(110,new Fd(u=>this.restoreFgColor(u))),this._parser.registerOscHandler(111,new Fd(u=>this.restoreBgColor(u))),this._parser.registerOscHandler(112,new Fd(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 gl)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 _or((u,f)=>this.requestStatusString(u,f)))}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"),Aor))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Aor} 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>sw&&(o=this._parseStack.position+sw)}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<sw&&(this._parseBuffer=new Uint32Array(Math.min(e.length,sw))),a||this._dirtyRowTracker.clearRange(),e.length>sw)for(let u=o;u<e.length;u+=sw){let f=u+sw<e.length?u+sw:e.length,h=typeof e=="string"?this._stringDecoder.decode(e.substring(u,f),this._parseBuffer):this._utf8Decoder.decode(e.subarray(u,f),this._parseBuffer);if(r=this._parser.parse(this._parseBuffer,h))return this._preserveStack(n,i,h,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,f=this._curAttrData,h=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&r-t>0&&h.getWidth(this._activeBuffer.x-1)===2&&h.setCellFromCodepoint(this._activeBuffer.x-1,0,1,f);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=GE.extractWidth(m);let g=GE.extractShouldJoin(m),y=g?GE.extractWidth(d):0;if(d=m,a&&this._onA11yChar.fire(lw(n)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-y>s){if(l){let v=h,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),h=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),y>0&&h instanceof fG&&h.copyCellsFrom(v,b,0,y,!1);b<s;)v.setCellFromCodepoint(b++,0,1,f)}else if(this._activeBuffer.x=s-1,i===2)continue}if(g&&this._activeBuffer.x){let v=h.getWidth(this._activeBuffer.x-1)?1:2;h.addCodepointToCell(this._activeBuffer.x-v,n,i);for(let b=i-y;--b>=0;)h.setCellFromCodepoint(this._activeBuffer.x++,0,0,f);continue}if(u&&(h.insertCells(this._activeBuffer.x,i-y,this._activeBuffer.getNullCell(f)),h.getWidth(s-1)===2&&h.setCellFromCodepoint(s-1,0,1,f)),h.setCellFromCodepoint(this._activeBuffer.x++,n,i,f),i>0)for(;--i;)h.setCellFromCodepoint(this._activeBuffer.x++,0,0,f)}this._parser.precedingJoinState=d,this._activeBuffer.x<s&&r-t>0&&h.getWidth(this._activeBuffer.x)===0&&!h.hasContent(this._activeBuffer.x)&&h.setCellFromCodepoint(this._activeBuffer.x,0,1,f),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,r=>Ror(r.params[0],this._optionsService.rawOptions.windowOptions)?t(r):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new _or(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Fd(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=GE.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 f=o.codePointAt(u)||0;a[s++]=f,u+=f>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,VE),this._charsetService.setgCharset(1,VE),this._charsetService.setgCharset(2,VE),this._charsetService.setgCharset(3,VE);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:f}=s,h=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(h.convertEol)):d(m,0):m===1?d(m,p(n.applicationCursorKeys)):m===3?d(m,h.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(h.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===f)):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|=xG.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(!Ror(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>Eor&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Eor&&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(Lor(o))if(i==="?")t.push({type:0,index:o});else{let a=kor(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=kor(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]);Lor(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,VE),!0}selectCharset(e){return e.length!==2?(this.selectDefaultCharset(),!0):(e[0]==="/"||this._charsetService.setgCharset(LLn[e[0]],gl[e[1]]||VE),!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 xm;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)}},uOe=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&&(Por=e,e=t,t=Por),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};uOe=es([br(0,gf)],uOe);function Lor(e){return 0<=e&&e<256}var ILn=5e7,Mor=12,DLn=50,OLn=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>ILn)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>=Mor?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>=Mor)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>DLn&&(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()}},fOe=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)))}};fOe=es([br(0,gf)],fOe);var Ior=!1,NLn=class extends Nn{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new qO),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 oLn,this.optionsService=this._register(new gLn(e)),this._instantiationService.setService(yf,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(aOe)),this._instantiationService.setService(gf,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(oOe)),this._instantiationService.setService(qor,this._logService),this.coreService=this._register(this._instantiationService.createInstance(sOe)),this._instantiationService.setService(KE,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(lOe)),this._instantiationService.setService(Gor,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(GE)),this._instantiationService.setService(RPn,this.unicodeService),this._charsetService=this._instantiationService.createInstance(TLn),this._instantiationService.setService(EPn,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(fOe),this._instantiationService.setService(jor,this._oscLinkService),this._inputHandler=this._register(new MLn(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 OLn((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&&!Ior&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Ior=!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,Oar),t=Math.max(t,Nar),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(wor.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(wor(this._bufferService),!1))),this._windowsWrappingHeuristics.value=Xo(()=>{for(let t of e)t.dispose()})}}},BLn={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 FLn(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=BLn[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,$Ln=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new dhe,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new dhe,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}},RDe=0,Dor=0,zLn=class extends Nn{constructor(){super(),this._decorations=new $Ln(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(Xo(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new ULn(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=>{RDe=i.options.x??0,Dor=RDe+(i.options.width??1),e>=RDe&&e<Dor&&(!r||(i.options.layer??"bottom")===r)&&n(i)})}},ULn=class extends uw{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=Pa.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=Pa.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},HLn=1e3,WLn=class{constructor(e,t=HLn){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)}},Oor=20,Nor=!1,phe=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 WLn(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");Nor?(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(`
3971
3971
  `))),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(Tn(i,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(Xo(()=>{Nor?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<Oor+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
3972
3972
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===Oor+1&&(this._liveRegion.textContent+=PDe.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,f=parseInt(u?.getAttribute("aria-posinset"),10)-1;if(isNaN(f))return console.warn("row is invalid. Race condition?"),null;let h=this._rowColumns.get(u);if(!h)return console.warn("columns is null. Race condition?"),null;let d=l<h.length?h[l]:h.slice(-1)[0]+1;return d>=this._terminal.cols&&(++f,d=0),{row:f,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})`}};phe=es([br(1,dOe),br(2,Ix),br(3,Dx)],phe);var hOe=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(Xo(()=>{jE(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(Tn(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Tn(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Tn(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Tn(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&&VLn(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,jE(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}}};hOe=es([br(1,pOe),br(2,Dx),br(3,gf),br(4,Kor)],hOe);function VLn(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 GLn=class extends NLn{constructor(e={}){super(e),this._linkifier=this._register(new qO),this.browser=war,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new qO),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(zLn),this._instantiationService.setService(TG,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(I8n),this._instantiationService.setService(Kor,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(MDe)),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(Xo(()=>{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=Ko.toColorRGB(r==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[r]);this.coreService.triggerDataEvent(`${Ft.ESC}]${n};${PLn(i)}${Sar.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(phe,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(Tn(this.element,"copy",t=>{this.hasSelection()&&TPn(t,this._selectionService)}));let e=t=>SPn(t,this.textarea,this.coreService,this.optionsService);this._register(Tn(this.textarea,"paste",e)),this._register(Tn(this.element,"paste",e)),_ar?this._register(Tn(this.element,"mousedown",t=>{t.button===2&&Nir(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Tn(this.element,"contextmenu",t=>{Nir(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),SOe&&this._register(Tn(this.element,"auxclick",t=>{t.button===1&&zor(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Tn(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Tn(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Tn(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Tn(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Tn(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Tn(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Tn(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(Tn(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",ADe.get()),Rar||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(L8n,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(Ix,this._coreBrowserService),this._register(Tn(this.textarea,"focus",i=>this._handleTextAreaFocus(i))),this._register(Tn(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(eOe,this._document,this._helperContainer),this._instantiationService.setService(ghe,this._charSizeService),this._themeService=this._instantiationService.createInstance(iOe),this._instantiationService.setService(jO,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(fhe),this._instantiationService.setService(Yor,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(rOe,this.rows,this.screenElement)),this._instantiationService.setService(Dx,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(ZDe,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(tOe),this._instantiationService.setService(pOe,this._mouseService);let n=this._linkifier.value=this._register(this._instantiationService.createInstance(hOe,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(KDe,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(nOe,this.element,this.screenElement,n)),this._instantiationService.setService(PPn,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(XDe,this.screenElement)),this._register(Tn(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(phe,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",i=>this._handleScreenReaderModeOptionChange(i))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(uhe,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",i=>{!this._overviewRulerRenderer&&i&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(uhe,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(JDe,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(Tn(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(Tn(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){$or(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=FLn(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)&&(qLn(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 qLn(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var jLn=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)}},YLn=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 xm)}translateToString(e,t,r){return this._line.translateToString(e,t,r)}},Bor=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 YLn(t)}getNullCell(){return new xm}},KLn=class extends Nn{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new ar),this.onBufferChange=this._onBufferChange.event,this._normal=new Bor(this._core.buffers.normal,"normal"),this._alternate=new Bor(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)}},XLn=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)}},ZLn=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}},QLn=["cols","rows"],a1=0,Far=class extends Nn{constructor(e){super(),this._core=this._register(new GLn(e)),this._addonManager=this._register(new jLn),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(QLn.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 XLn(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new ZLn(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 KLn(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
3973
- `,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 ADe.get()},set promptLabel(e){ADe.set(e)},get tooMuchOutput(){return PDe.get()},set tooMuchOutput(e){PDe.set(e)}}}_verifyIntegers(...e){for(a1 of e)if(a1===1/0||isNaN(a1)||a1%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(a1 of e)if(a1&&(a1===1/0||isNaN(a1)||a1%1!==0||a1<0))throw new Error("This API only accepts positive integers")}};var COe=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\^<>`]*[^\s"':,.!?{}|\\^~[\]`()<>]/;function JLn(e){try{return!!new URL(e).host}catch{return!1}}function zar(e,t){let r=e(t),n=e(t+1);return!!r&&!!n&&(n.isWrapped||r.isFull)}function eMn(e,t){let r=[];for(let n=t;n-t<64;n++){let i=e(n);if(!i||(r.push(i.text),!zar(e,n)))break}return r}function $ar(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 tMn(e,t,r){let n=r[0],i=$ar(e,t,r.index),o=$ar(e,t,r.index+n.length-1);if(!(!JLn(n)||!i||!o))return{text:n,range:{start:i,end:o}}}function rMn(e,t,r){let n=new RegExp(r.source,`${r.flags||""}g`);return[...e.join("").matchAll(n)].flatMap(o=>tMn(e,t,o)??[])}function Uar(e,t,r=COe){if(!e(t-1))return[];let n=t-1;for(;n>0&&zar(e,n-1);)n--;return rMn(eMn(e,n),n,r)}function Har(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=Uar(r,n,COe);i(o.map(a=>({range:a.range,text:a.text,activate:t})))}}}function War(e){let t=new Far({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 pnr;t.loadAddon(r);let n=t.registerLinkProvider(Har(t,(o,a)=>{window.open(a,"_blank")}));t.open(e);let i;try{i=new Iir,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 Var(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 The(e){return e.type==="keydown"&&(e.ctrlKey||e.metaKey)&&!e.shiftKey&&!e.altKey&&e.key.toLowerCase()==="p"}function Gar(e,t,r,n,i){let o=War(e);o.term.onData(u=>r(t,u)),o.term.attachCustomKeyEventHandler(u=>The(u)?!1:Var(u,o.term,navigator.clipboard,f=>o.term.paste(f)));let a=n(t,u=>o.term.write(u)),s=new ResizeObserver(()=>{Rfe(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 qar(e,t,r,n,i,o){let a=(0,wG.useRef)(null);(0,wG.useEffect)(()=>{let s=e.current;if(!s)return;let{handle:l,cleanup:u}=Gar(s,t,n,i,o);return a.current=l,()=>{u(),a.current=null}},[e,t,i,n,o]),(0,wG.useEffect)(()=>{let s=a.current;if(!r||!s)return;let l=setTimeout(()=>{Rfe(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 Kar=F(W(),1);function Yar({sessionId:e,visible:t,onOutput:r,sendInput:n,sendResize:i}){let o=(0,jar.useRef)(null);return qar(o,e,t,n,r,i),(0,Kar.jsx)(Pe,{ref:o,sx:{position:"absolute",inset:"0 0 0 8px",visibility:t?"visible":"hidden",pointerEvents:t?"auto":"none"}})}var XE=F(W(),1);function Xar({sessions:e,activeId:t,activeLoading:r,onOutput:n,sendInput:i,sendResize:o}){return(0,XE.jsxs)(Pe,{sx:{flex:1,position:"relative",bgcolor:"background.default"},children:[e.map(a=>(0,XE.jsx)(Yar,{sessionId:a.id,visible:a.id===t,onOutput:n,sendInput:i,sendResize:o},a.id)),r&&(0,XE.jsx)(dnr,{}),e.length===0&&(0,XE.jsx)(Pe,{sx:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:(0,XE.jsx)(Ze,{variant:"body2",color:"text.disabled",children:"Create a session to get started"})})]})}var Qar=F(W(),1);function Zar({sessions:e,activeId:t,initialized:r,onOutput:n,sendInput:i,sendResize:o}){let a=e.find(l=>l.id===t),s=a!==void 0&&vle(a,r);return(0,Qar.jsx)(Xar,{sessions:e,activeId:t,activeLoading:s,onOutput:n,sendInput:i,sendResize:o})}var KO=F(W(),1),nMn={position:"relative",display:"flex",flex:1,minWidth:0,minHeight:0};function Jar({activeSession:e,sendPrDecision:t,showLastMessage:r,...n}){return(0,KO.jsxs)(Pe,{sx:nMn,children:[(0,KO.jsx)(onr,{session:e,sendPrDecision:t,sendInput:n.sendInput,children:(0,KO.jsx)(Zar,{...n})}),r&&e!==void 0&&(0,KO.jsx)(fnr,{message:e.lastUserMessage})]})}var esr=F(W(),1),tsr=bt((0,esr.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 Tm=F(W(),1);function rsr({message:e}){return e.role==="tool"?(0,Tm.jsx)(iMn,{tool:e.tool,target:e.target}):(0,Tm.jsx)(oMn,{role:e.role,text:e.text})}function iMn({tool:e,target:t}){return(0,Tm.jsxs)(Pe,{sx:{display:"flex",alignItems:"center",gap:1,py:.5,pl:1},children:[(0,Tm.jsx)(tsr,{sx:{fontSize:14,color:"text.disabled"}}),(0,Tm.jsxs)(Ze,{variant:"caption",sx:{color:"text.secondary",fontFamily:"monospace"},children:[(0,Tm.jsx)(Pe,{component:"span",sx:{color:"warning.main"},children:e}),t&&(0,Tm.jsxs)(Pe,{component:"span",children:[" ",t]})]})]})}function oMn({role:e,text:t}){let r=e==="user",n=r?"info.main":"success.main";return(0,Tm.jsxs)(Pe,{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,Tm.jsx)(Ze,{variant:"caption",sx:{color:n,fontWeight:600,display:"block",mb:.5},children:r?"User":"Assistant"}),(0,Tm.jsx)(Ze,{variant:"body2",sx:{color:"text.primary",whiteSpace:"pre-wrap",overflowWrap:"anywhere",lineHeight:1.6},children:t})]})}var u1=F(W(),1);function aMn(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 isr({messages:e,loading:t}){return t?(0,u1.jsxs)(Pe,{sx:nsr,children:[(0,u1.jsx)(oo,{size:20}),(0,u1.jsx)(Ze,{variant:"caption",color:"text.disabled",children:"Loading transcript\u2026"})]}):e.length===0?(0,u1.jsx)(Pe,{sx:nsr,children:(0,u1.jsx)(Ze,{variant:"body2",color:"text.disabled",children:"No transcript available"})}):(0,u1.jsx)(Pe,{sx:{position:"absolute",inset:0,overflowY:"auto",p:2},children:(0,u1.jsx)(Pe,{sx:{maxWidth:820,mx:"auto"},children:aMn(e).map(r=>(0,u1.jsx)(rsr,{message:r},r.key))})})}var nsr={position:"absolute",inset:0,display:"flex",flexDirection:"column",gap:1.5,alignItems:"center",justifyContent:"center"};var wOe=F(W(),1);function osr({sessionId:e,transcript:t}){let r=t?.sessionId===e;return(0,wOe.jsx)(Pe,{sx:{flex:1,position:"relative",bgcolor:"background.default"},children:(0,wOe.jsx)(isr,{messages:r?t?.messages??[]:[],loading:!r})})}var fw=F(W(),1),sMn={flex:1,minHeight:0,display:"flex",flexDirection:"column"},lMn={flexShrink:0};function asr({viewingTranscriptSessionId:e,transcript:t,sendPrDecision:r,lifecycle:n,...i}){let o=yh();if(e!==null)return(0,fw.jsx)(osr,{sessionId:e,transcript:t});let a=i.sessions.find(s=>s.id===i.activeId);return(0,fw.jsxs)(Pe,{sx:sMn,children:[o&&a!==void 0&&(0,fw.jsx)(Pe,{sx:lMn,children:(0,fw.jsx)(Per,{session:a,lifecycle:n})}),(0,fw.jsx)(Der,{sessionId:i.activeId,sessions:i.sessions,sendInput:i.sendInput,children:(0,fw.jsx)(Jar,{...i,activeSession:a,sendPrDecision:r,showLastMessage:o})})]})}var csr=F(W(),1);function lsr({socket:e}){let t=(0,ssr.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,csr.jsx)(asr,{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})}var Ysr=F(_e(),1);var XO=F(_e(),1);function She(e,t){let r=(0,XO.useRef)(null),[n,i]=(0,XO.useState)();return(0,XO.useLayoutEffect)(()=>{e===t&&r.current&&i(r.current.offsetHeight)},[e,t]),{ref:r,height:n}}var fsr=F(_e(),1);function Che(e){if(e.startsWith("local:")){let n=e.slice(6).replace(/\/+$/,"").split("/").filter(Boolean);return n[n.length-1]??e}let t=e.indexOf("/");return t===-1?e:e.slice(t+1)}function whe(e){let t=o=>o.startsWith("local:"),r=o=>{let a=Che(o),s=a.split("/");return s[s.length-1]??a},n=new Map;for(let o of new Set(e)){if(t(o))continue;let a=r(o);n.set(a,(n.get(a)??0)+1)}let i=new Map;for(let o of e){if(t(o)){i.set(o,Che(o));continue}let a=r(o),s=(n.get(a)??0)>1;i.set(o,s?Che(o):a)}return i}var _G={field:"lastPhase",direction:"desc"};var kG="all",EG="all";async function usr(e,t,r){let n=new URLSearchParams({page:String(e),pageSize:String(t)});r.origin!==kG&&n.set("origin",r.origin),r.status!==EG&&n.set("status",r.status),r.sort.field!==_G.field&&n.set("sort",r.sort.field),r.sort.direction!==_G.direction&&n.set("direction",r.sort.direction);let i=await fetch(`/api/usage/items?${n}`);if(!i.ok)throw new Error(`Failed to load item usage (HTTP ${i.status}).`);return i.json()}var RG=F(W(),1);function hsr({origins:e,origin:t,onChange:r}){let n=(0,fsr.useMemo)(()=>whe(e.map(o=>o.origin)),[e]),i=e.reduce((o,a)=>o+a.count,0);return(0,RG.jsxs)(xi,{select:!0,size:"small",label:"Repo",value:t,onChange:o=>r(o.target.value),sx:{minWidth:220},children:[(0,RG.jsx)(Ln,{value:kG,children:`All repos (${i})`}),e.map(o=>(0,RG.jsx)(Ln,{value:o.origin,children:`${n.get(o.origin)??o.origin} (${o.count})`},o.origin))]})}var _Oe=F(W(),1),cMn=[{value:EG,label:"All"},{value:"done",label:"Done"},{value:"running",label:"Running"}];function dsr({status:e,onChange:t}){return(0,_Oe.jsx)(Ef,{size:"small",exclusive:!0,value:e,onChange:(r,n)=>n&&t(n),"aria-label":"Filter items by status",children:cMn.map(r=>(0,_Oe.jsx)(Ks,{value:r.value,children:r.label},r.value))})}var ZO=F(W(),1),uMn={display:"flex",alignItems:"center",gap:2,flexWrap:"wrap",mb:2},fMn="Repos show their bare name, or org/repo when two share one. Totals sum every phase's recorded usage.";function psr({origins:e,origin:t,onOriginChange:r,status:n,onStatusChange:i}){return(0,ZO.jsxs)(Pe,{sx:uMn,children:[(0,ZO.jsx)(dsr,{status:n,onChange:i}),(0,ZO.jsx)(hsr,{origins:e,origin:t,onChange:r}),(0,ZO.jsx)(Ze,{variant:"caption",color:"text.disabled",children:fMn})]})}var ksr=F(_e(),1);var khe=F(W(),1),hMn={whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},msr={display:"block",fontSize:"0.75rem",color:"text.disabled",whiteSpace:"nowrap"},dMn={...msr,fontStyle:"italic"};function _he({total:e,perPhase:t,partial:r}){return(0,khe.jsxs)(bn,{align:"right",sx:hMn,children:[e,t?(0,khe.jsx)(Ze,{component:"span",sx:r?dMn:msr,children:t}):null]})}var AG=F(W(),1),pMn={width:"100%",maxWidth:0},mMn={display:"block",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},gMn={display:"block",mt:"2px",fontSize:"0.75rem",color:"text.secondary",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function gsr({id:e,name:t,type:r,repoLabel:n}){return(0,AG.jsxs)(bn,{sx:pMn,children:[(0,AG.jsx)(Wi,{component:Au,to:$2(e),underline:"hover",color:"text.primary",title:t,sx:mMn,children:t}),(0,AG.jsxs)(Ze,{component:"span",sx:gMn,children:[lo(e)," \xB7 ",r," \xB7 ",n]})]})}function ysr(e){let t=Math.max(1,e.recordedPhases);return{active:`${qm(e.activeMs/t)} / phase`,tokens:`${Nf(Math.round((e.tokensUp+e.tokensDown)/t))} / phase`}}function vsr(e){if(!(e.status==="done"||e.recordedPhases>e.phaseCount))return`${e.recordedPhases} of ${e.phaseCount} phases`}var yMn=new Set(["done","wontdo"]);function bsr(e){return yMn.has(e)?{label:e,color:MX[e]}:{label:"running",color:"warning"}}var kOe=F(W(),1),vMn={height:20,fontSize:"0.6875rem"};function xsr({status:e}){let t=bsr(e);return(0,kOe.jsx)(bn,{children:(0,kOe.jsx)(Zn,{label:t.label,size:"small",variant:"outlined",color:t.color,sx:vMn})})}var Wg=F(W(),1),Tsr={whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"};function Ssr({row:e,repoLabel:t}){let r=ysr(e);return(0,Wg.jsxs)(ku,{hover:!0,children:[(0,Wg.jsx)(gsr,{id:e.id,name:e.name,type:e.type,repoLabel:t}),(0,Wg.jsx)(xsr,{status:e.status}),(0,Wg.jsx)(_he,{total:String(e.phaseCount||e.recordedPhases),perPhase:vsr(e),partial:!0}),(0,Wg.jsx)(_he,{total:qm(e.activeMs),perPhase:r.active}),(0,Wg.jsx)(_he,{total:`\u2191 ${Nf(e.tokensUp)} \u2193 ${Nf(e.tokensDown)}`,perPhase:r.tokens}),(0,Wg.jsx)(bn,{align:"right",sx:Tsr,children:(0,Wg.jsxs)(Pe,{component:"span",sx:{color:Sle(e.peakContextPct)},children:[Math.round(e.peakContextPct),"%"]})}),(0,Wg.jsx)(bn,{align:"right",sx:Tsr,children:e.lastPhaseAt?y0(e.lastPhaseAt):"\u2014"})]})}var Csr=[{label:"Item"},{label:"Status"},{label:"Phases",sort:"phases",numeric:!0},{label:"Active",sort:"active",numeric:!0,tooltip:"Accumulated active time across the item's phases \u2014 not wall clock."},{label:"Tokens",sort:"tokens",numeric:!0},{label:"Peak ctx",sort:"peakContext",numeric:!0,tooltip:"The highest context-window usage any one phase reached."},{label:"Last phase",sort:"lastPhase",numeric:!0,tooltip:"When the item's most recent phase session started."}];var Sm=F(W(),1),bMn={"& th":{whiteSpace:"nowrap"}};function wsr({column:e}){return e.tooltip?(0,Sm.jsx)(nn,{title:e.tooltip,describeChild:!0,children:(0,Sm.jsx)("span",{children:e.label})}):(0,Sm.jsx)(Sm.Fragment,{children:e.label})}function _sr({sort:e,onSort:t}){return(0,Sm.jsx)(g_,{sx:bMn,children:(0,Sm.jsx)(ku,{children:Csr.map(r=>{let n=r.sort,i=n!==void 0&&e.field===n;return(0,Sm.jsx)(bn,{align:r.numeric?"right":"left",sortDirection:i?e.direction:!1,children:n===void 0?(0,Sm.jsx)(wsr,{column:r}):(0,Sm.jsx)(Hme,{active:i,direction:i?e.direction:"desc",onClick:()=>t(n),children:(0,Sm.jsx)(wsr,{column:r})})},r.label)})})})}var ZE=F(W(),1),xMn={"& td, & th":{px:1.5}};function Esr({rows:e,origins:t,sort:r,onSort:n}){let i=(0,ksr.useMemo)(()=>whe([...t,...e.map(o=>o.origin)]),[t,e]);return(0,ZE.jsx)(m_,{component:Fn,children:(0,ZE.jsxs)(N1,{size:"small",sx:xMn,children:[(0,ZE.jsx)(_sr,{sort:r,onSort:n}),(0,ZE.jsx)(B1,{children:e.map(o=>(0,ZE.jsx)(Ssr,{row:o,repoLabel:i.get(o.origin)??o.origin},o.id))})]})})}function Rsr(e){let t=Math.max(1,e.medianPhases),r=e.repoCount===1?"repo":"repos";return{items:String(e.itemCount),itemsFoot:`across ${e.repoCount} ${r} \xB7 ${e.doneCount} done`,phases:String(Math.round(e.medianPhases*10)/10),active:qm(e.medianActiveMs),activeFoot:`${qm(e.medianActiveMs/t)} per phase`,tokens:Nf(Math.round(e.medianTokens)),tokensFoot:`${Nf(Math.round(e.medianTokens/t))} per phase`}}var QO=F(W(),1),Asr={display:"block"},TMn={fontWeight:400,fontVariantNumeric:"tabular-nums"};function PG({label:e,value:t,foot:r}){return(0,QO.jsxs)(Pe,{children:[(0,QO.jsx)(Ze,{variant:"caption",color:"text.secondary",sx:Asr,children:e}),(0,QO.jsx)(Ze,{variant:"h5",sx:TMn,children:t}),r?(0,QO.jsx)(Ze,{variant:"caption",color:"text.disabled",sx:Asr,children:r}):null]})}var QE=F(W(),1),SMn={display:"flex",flexDirection:{xs:"column",sm:"row"},mb:3,"& > *":{flex:1,minWidth:0,p:2},"& > * + *":{borderColor:"divider",borderTop:{xs:1,sm:0},borderLeft:{xs:0,sm:1}}};function Psr({summary:e}){let t=Rsr(e);return(0,QE.jsxs)(Fn,{sx:SMn,children:[(0,QE.jsx)(PG,{label:"Items with recorded usage",value:t.items,foot:t.itemsFoot}),(0,QE.jsx)(PG,{label:"Median phases",value:t.phases}),(0,QE.jsx)(PG,{label:"Median active time",value:t.active,foot:t.activeFoot}),(0,QE.jsx)(PG,{label:"Median tokens",value:t.tokens,foot:t.tokensFoot})]})}var Ud=F(W(),1);function Lsr({items:e,data:t}){let{rows:r,total:n,page:i,pageSize:o}=e,{ref:a,height:s}=She(r.length,o);return(0,Ud.jsxs)(Ud.Fragment,{children:[(0,Ud.jsx)(Psr,{summary:t.summary}),(0,Ud.jsx)(psr,{origins:t.origins,origin:e.origin,onOriginChange:e.selectOrigin,status:e.status,onStatusChange:e.selectStatus}),n===0?(0,Ud.jsx)(Ze,{color:"text.secondary",align:"center",sx:{py:6},children:"No items match this filter."}):(0,Ud.jsxs)(Ud.Fragment,{children:[(0,Ud.jsx)(Pe,{ref:a,sx:{minHeight:s},children:(0,Ud.jsx)(Esr,{rows:r,origins:t.origins.map(l=>l.origin),sort:e.sort,onSort:e.sortBy})}),(0,Ud.jsx)(zN,{component:"div",count:n,page:i,rowsPerPage:o,rowsPerPageOptions:[o],onPageChange:(l,u)=>e.setPage(u)})]})]})}var Ox=F(W(),1);function Msr({items:e}){let{data:t}=e;return(0,Ox.jsxs)(Ox.Fragment,{children:[(0,Ox.jsx)(Pe,{sx:{height:4,mb:1},children:e.fetching&&(0,Ox.jsx)(d_,{})}),t?t.origins.length===0?(0,Ox.jsx)(Ze,{color:"text.secondary",align:"center",sx:{py:6},children:"No item usage recorded yet."}):(0,Ox.jsx)(Lsr,{items:e,data:t}):null]})}function EOe(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 Ehe(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 CMn(e,t,r,n){let i=EOe(t,r,n);if(i!=null)return e/i}function hw(e,t,r,n){let i=CMn(e,t,r,n);return i==null?"ok":i>100?"over":i>75?"warn":"ok"}var JE={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 wMn={ok:"success.main",warn:"warning.main",over:"error.main"};function dw(e){return wMn[e]}var IG=F(W(),1),_Mn={ok:"success",warn:"warning",over:"error"};function Isr({percentage:e,level:t}){return(0,IG.jsxs)(Pe,{sx:{display:"flex",alignItems:"center",gap:1},children:[(0,IG.jsx)(d_,{variant:"determinate",value:Math.min(100,e),color:_Mn[t],sx:{flexGrow:1,height:8,borderRadius:1}}),(0,IG.jsxs)(Pe,{sx:{minWidth:40,textAlign:"right",color:dw(t)},children:[Math.round(e),"%"]})]})}function Dsr(e){return e.avgContextPct==null?"\u2014":`${Math.round(e.avgContextPct)}%`}var kMn=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});function ROe(e){return kMn.format(e)}var Rhe=F(W(),1);function Osr({peak:e}){return(0,Rhe.jsx)(bn,{align:"right",sx:{whiteSpace:"nowrap"},children:(0,Rhe.jsx)(nn,{title:`Cycle started ${ROe(new Date(e.createdAt))}`,children:(0,Rhe.jsx)("span",{children:ROe(new Date(e.resetsAt*1e3))})})})}var Bsr=F(W(),1);function Nsr(){return(0,Bsr.jsx)(Zn,{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 Fsr(e){return!e.tokensUp&&!e.tokensDown?"\u2014":`\u2191 ${Nf(e.tokensUp)} \u2193 ${Nf(e.tokensDown)}`}var Vg=F(W(),1);function $sr({peak:e,now:t}){let{label:r,seconds:n,tint:i}=JE[e.window],o=hw(e.usedPercentage,e.resetsAt,n,t);return(0,Vg.jsxs)(ku,{sx:a=>({backgroundColor:i?a.palette.mode==="dark"?i.dark:i.light:void 0}),children:[(0,Vg.jsxs)(bn,{children:[r,e.resetDetected&&(0,Vg.jsx)(Nsr,{})]}),(0,Vg.jsx)(bn,{sx:{minWidth:160},children:(0,Vg.jsx)(Isr,{percentage:e.usedPercentage,level:o})}),(0,Vg.jsx)(bn,{align:"right",sx:{whiteSpace:"nowrap"},children:Dsr(e)}),(0,Vg.jsx)(bn,{align:"right",sx:{whiteSpace:"nowrap"},children:e.phaseCount??0}),(0,Vg.jsx)(bn,{align:"right",sx:{whiteSpace:"nowrap"},children:Fsr(e)}),(0,Vg.jsx)(Osr,{peak:e})]})}var Ahe=F(_e(),1);function JO(e){let[t,r]=(0,Ahe.useState)(()=>Math.floor(Date.now()/1e3));return(0,Ahe.useEffect)(()=>{let n=setInterval(()=>r(Math.floor(Date.now()/1e3)),e);return()=>clearInterval(n)},[e]),t}var ec=F(W(),1);function zsr({peaks:e}){let t=JO(3e4);return(0,ec.jsx)(m_,{component:Fn,children:(0,ec.jsxs)(N1,{size:"small",children:[(0,ec.jsx)(g_,{sx:{"& th":{whiteSpace:"nowrap"}},children:(0,ec.jsxs)(ku,{children:[(0,ec.jsx)(bn,{children:"Window"}),(0,ec.jsx)(bn,{children:"Peak usage"}),(0,ec.jsx)(bn,{align:"right",children:(0,ec.jsx)(nn,{title:"Mean context-window usage across all readings in this rate-limit cycle \u2014 distinct from the Peak usage quota above.",children:(0,ec.jsx)("span",{children:"Avg context"})})}),(0,ec.jsx)(bn,{align:"right",children:(0,ec.jsx)(nn,{title:"Number of phase readings behind the average.",children:(0,ec.jsx)("span",{children:"Phases"})})}),(0,ec.jsx)(bn,{align:"right",children:"Tokens spent"}),(0,ec.jsx)(bn,{align:"right",children:"Cycle reset"})]})}),(0,ec.jsx)(B1,{children:e.map(r=>(0,ec.jsx)($sr,{peak:r,now:t},`${r.window}-${r.resetsAt}-${r.segment}`))})]})})}var pw=F(W(),1);function Usr({rows:e,total:t,page:r,pageSize:n,onPageChange:i}){let{ref:o,height:a}=She(e.length,n);return(0,pw.jsxs)(pw.Fragment,{children:[(0,pw.jsx)(Pe,{ref:o,sx:{minHeight:a},children:(0,pw.jsx)(zsr,{peaks:e})}),(0,pw.jsx)(zN,{component:"div",count:t,page:r,rowsPerPage:n,rowsPerPageOptions:[n],onPageChange:(s,l)=>i(l)})]})}var AOe=F(W(),1),EMn=[{value:"all",label:"All"},{value:"five_hour",label:JE.five_hour.label},{value:"seven_day",label:JE.seven_day.label}];function Hsr({window:e,onChange:t}){return(0,AOe.jsx)(Ef,{size:"small",exclusive:!0,value:e,onChange:(r,n)=>n&&t(n),"aria-label":"Filter peaks by rate-limit window",children:EMn.map(r=>(0,AOe.jsx)(Ks,{value:r.value,children:r.label},r.value))})}var f1=F(W(),1);function Wsr({history:e}){let{window:t,total:r}=e;return(0,f1.jsxs)(f1.Fragment,{children:[(0,f1.jsx)(Hsr,{window:t,onChange:e.selectWindow}),(0,f1.jsx)(Pe,{sx:{height:4,my:1},children:e.fetching&&(0,f1.jsx)(d_,{})}),r===0?(0,f1.jsx)(Ze,{color:"text.secondary",align:"center",sx:{py:6},children:t==="all"?"No usage peaks recorded yet.":`No ${JE[t].label} usage peaks recorded yet.`}):(0,f1.jsx)(Usr,{rows:e.rows,total:r,page:e.page,pageSize:e.pageSize,onPageChange:e.setPage})]})}var Lhe=F(_e(),1);async function Vsr(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()}var mw=F(_e(),1);function Phe(e,t,r=!0){let[n,i]=(0,mw.useState)(0),[o,a]=(0,mw.useState)(null),[s,l]=(0,mw.useState)(!1),[u,f]=(0,mw.useState)(null);(0,mw.useEffect)(()=>{if(!r)return;let p=!1;return l(!0),e(n,t).then(m=>{p||(a(m),l(!1))},m=>{p||(f(m instanceof Error?m:new Error(String(m))),l(!1))}),()=>{p=!0}},[e,n,t,r]);let h=o?.total??0;(0,mw.useEffect)(()=>{if(h===0)return;let p=Math.ceil(h/t)-1;n>p&&i(p)},[n,t,h]);let d=o?.rows??[];return{data:o,rows:d,total:h,loaded:o!==null,fetching:s,error:u,page:n,setPage:i,pageSize:t}}var RMn=30;function Gsr(){let[e,t]=(0,Lhe.useState)("all"),r=(0,Lhe.useCallback)((o,a)=>Vsr(o,a,e),[e]),n=Phe(r,RMn);return{...n,window:e,selectWindow:o=>{t(o),n.setPage(0)}}}var e9=F(_e(),1);function qsr(e,t){return e.field!==t?{field:t,direction:"desc"}:{field:t,direction:e.direction==="desc"?"asc":"desc"}}var AMn=30;function jsr(e){let[t,r]=(0,e9.useState)(kG),[n,i]=(0,e9.useState)(EG),[o,a]=(0,e9.useState)(_G),s=(0,e9.useCallback)((d,p)=>usr(d,p,{origin:t,status:n,sort:o}),[t,n,o]),l=Phe(s,AMn,e);return{...l,origin:t,selectOrigin:d=>{r(d),l.setPage(0)},status:n,selectStatus:d=>{i(d),l.setPage(0)},sort:o,sortBy:d=>{a(p=>qsr(p,d)),l.setPage(0)}}}var gw=F(W(),1),PMn={borderBottom:1,borderColor:"divider",mb:2};function Ksr(){let[e,t]=(0,Ysr.useState)("limits"),r=Gsr(),n=jsr(e==="items");if(r.error)throw r.error;if(n.error)throw n.error;return(0,gw.jsxs)(sm,{loading:!r.loaded,title:"Usage history",maxWidth:"lg",children:[(0,gw.jsxs)(v_,{value:e,onChange:(i,o)=>t(o),textColor:"inherit",indicatorColor:"secondary",sx:PMn,"aria-label":"Usage history views",children:[(0,gw.jsx)(zm,{label:"Rate limits",value:"limits"}),(0,gw.jsx)(zm,{label:"Items",value:"items"})]}),e==="limits"?(0,gw.jsx)(Wsr,{history:r}):(0,gw.jsx)(Msr,{items:n})]})}var io=F(W(),1);function LMn({socket:e}){return(0,io.jsx)(hN,{maxWidth:"lg",sx:{py:3,px:2},children:(0,io.jsx)(uzt,{socket:e})})}function Xsr({socket:e}){return v0("AppRoutes"),(0,io.jsxs)(io.Fragment,{children:[(0,io.jsx)(her,{}),(0,io.jsx)(G_,{children:(0,io.jsxs)(kl,{element:(0,io.jsx)(SWt,{socket:e}),children:[(0,io.jsx)(kl,{path:"sessions",element:(0,io.jsx)(lsr,{socket:e})}),(0,io.jsx)(kl,{path:"backlog/*",element:(0,io.jsx)(LMn,{socket:e})}),(0,io.jsx)(kl,{path:"news",element:(0,io.jsx)(ler,{})}),(0,io.jsx)(kl,{path:"usage",element:(0,io.jsx)(Ksr,{})}),(0,io.jsx)(kl,{path:"backups",element:(0,io.jsx)(AWt,{})}),(0,io.jsx)(kl,{path:"config",element:(0,io.jsx)(gGt,{})}),(0,io.jsx)(kl,{path:"diff",element:(0,io.jsx)(EJt,{sessions:e.sessions,sendInput:e.sendInput})}),(0,io.jsx)(kl,{path:"file",element:(0,io.jsx)(ier,{sessions:e.sessions,sendInput:e.sendInput,cardId:sfe(e)})}),(0,io.jsx)(kl,{path:"*",element:(0,io.jsx)(Kye,{to:"/sessions",replace:!0})})]})})]})}var Fhe=F(_e(),1);var Bhe=F(_e(),1);function Zsr(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 yw=F(W(),1),MMn={display:"flex",gap:1,alignItems:"center",minWidth:0},IMn={display:"flex",gap:1,alignItems:"baseline",minWidth:0,overflow:"hidden"},DMn={fontFamily:"monospace",fontSize:13,whiteSpace:"nowrap"},OMn={fontFamily:"monospace",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function NMn(e){let t=e.lastIndexOf("/");return t===-1?{dir:"",basename:e}:{dir:e.slice(0,t),basename:e.slice(t+1)}}function Qsr({files:e,highlight:t,onHighlight:r,onSelect:n}){return(0,yw.jsx)(kf,{dense:!0,sx:{py:0},children:e.map((i,o)=>{let{dir:a,basename:s}=NMn(i);return(0,yw.jsxs)(Ln,{selected:o===t,onMouseEnter:()=>r(o),onClick:()=>n(i),sx:MMn,children:[(0,yw.jsx)(wO,{path:i}),(0,yw.jsxs)(Pe,{sx:IMn,children:[(0,yw.jsx)(Ze,{component:"span",sx:DMn,children:s}),(0,yw.jsx)(Ze,{component:"span",color:"text.secondary",sx:OMn,children:a})]})]},i)})})}var Mhe=F(W(),1),BMn={maxHeight:420,overflowY:"auto"},FMn={px:2,py:2,fontSize:13};function Jsr({message:e,files:t,highlight:r,onHighlight:n,onSelect:i}){return(0,Mhe.jsx)(Pe,{sx:BMn,children:e?(0,Mhe.jsx)(Ze,{color:"text.secondary",sx:FMn,children:e}):(0,Mhe.jsx)(Qsr,{files:t,highlight:r,onHighlight:n,onSelect:i})})}var elr=F(W(),1);function Ihe({inputRef:e,value:t,onChange:r,onKeyDown:n,placeholder:i,autoFocus:o}){return(0,elr.jsx)(xi,{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 Dhe=F(_e(),1),tlr={files:[],loading:!1,error:!1};function rlr(e,t){let[r,n]=(0,Dhe.useState)(tlr);return(0,Dhe.useEffect)(()=>{if(!e){n(tlr);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 Ohe=F(_e(),1);function Nhe(e,t,r,n){let[i,o]=(0,Ohe.useState)(0);return(0,Ohe.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 DG=F(W(),1),$Mn={mt:6,alignSelf:"flex-start"};function nlr({onClose:e}){let{worktreeCwd:t}=Na(),[r,n]=(0,Bhe.useState)(""),i=rlr(t,r),o=wo(),a=(0,Bhe.useRef)(null),s=d=>o(`/file?${new URLSearchParams(t?{path:d,cwd:t}:{path:d})}`),{highlight:l,setHighlight:u,onKeyDown:f}=Nhe(i.files,r,s,e),h=d=>{s(d),e()};return(0,DG.jsxs)(wf,{open:!0,onClose:e,maxWidth:"sm",fullWidth:!0,slotProps:{paper:{sx:$Mn},transition:{onEntered:()=>a.current?.focus()}},children:[(0,DG.jsx)(Ihe,{autoFocus:!0,inputRef:a,value:r,onChange:n,onKeyDown:f,placeholder:"Search files by name..."}),(0,DG.jsx)(Jsr,{message:Zsr(t,r,i),files:i.files,highlight:l,onHighlight:u,onSelect:h})]})}var olr=F(_e(),1);var ilr=!0;function alr(e){(0,olr.useEffect)(()=>{let t=r=>{The(r)&&(r.preventDefault(),e())};return globalThis.addEventListener("keydown",t,ilr),()=>globalThis.removeEventListener("keydown",t,ilr)},[e])}var llr=F(W(),1);function slr(){let[e,t]=(0,Fhe.useState)(!1);return alr((0,Fhe.useCallback)(()=>t(!0),[])),e?(0,llr.jsx)(nlr,{onClose:()=>t(!1)}):null}var $he=F(W(),1);function clr({notice:e,onClose:t,onView:r}){let n=e?.sessionId??null;return(0,$he.jsx)(Yc,{open:e!==null,autoHideDuration:6e3,onClose:t,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:(0,$he.jsx)(Qo,{severity:"success",variant:"filled",onClose:t,action:n!==null?(0,$he.jsx)(yr,{color:"inherit",size:"small",onClick:()=>r(n),children:"View"}):void 0,children:e?.message})})}var zhe=F(W(),1);function ulr({reconnecting:e}){return(0,zhe.jsx)(Yc,{open:e,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:(0,zhe.jsx)(Qo,{severity:"info",variant:"filled",icon:(0,zhe.jsx)(oo,{size:16,color:"inherit"}),children:"Reconnecting\u2026"})})}var Nx=F(W(),1);function flr({socket:e,onViewLaunchedSession:t}){return(0,Nx.jsxs)(Nx.Fragment,{children:[(0,Nx.jsx)(slr,{}),(0,Nx.jsx)(ulr,{reconnecting:e.reconnecting}),(0,Nx.jsx)(vh,{error:e.error,onClose:e.clearError}),(0,Nx.jsx)(clr,{notice:e.success,onClose:e.clearSuccess,onView:t})]})}var t9=F(W(),1),zMn=["/sessions","/backlog","/news"];function hlr(){let e=Cs(),t=wo(),r=zMn.findIndex(i=>e.pathname.startsWith(i)),n=i=>{e.pathname!==i&&t(i)};return(0,t9.jsxs)(v_,{value:r===-1?0:r,textColor:"inherit",indicatorColor:"secondary",children:[(0,t9.jsx)(zm,{label:"Sessions",onClick:()=>n("/sessions")}),(0,t9.jsx)(zm,{label:"Backlog",onClick:()=>n("/backlog")}),(0,t9.jsx)(zm,{label:"News",onClick:()=>n("/news")})]})}var Hhe=F(_e(),1),Uhe=F(W(),1),UMn={color:"inherit"};function dlr({cwd:e}){let[t,r]=(0,Hhe.useState)(null);return(0,Hhe.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,Uhe.jsx)(nn,{title:"Open in GitHub",children:(0,Uhe.jsx)(mr,{sx:UMn,onClick:()=>window.open(t,"_blank"),children:(0,Uhe.jsx)(P6,{})})}):null}var mlr=F(_e(),1);var Whe=F(W(),1);function plr({window:e,windowSeconds:t,fallbackLabel:r,now:n}){let i=e?.used_percentage;if(i==null)return null;let o=hw(i,e?.resets_at,t,n),a=e?.resets_at!=null?Ehe(e.resets_at,n):r;return(0,Whe.jsxs)(Pe,{component:"span",children:[(0,Whe.jsxs)(Pe,{component:"span",sx:{color:dw(o)},children:[Math.round(i),"%"]})," ",(0,Whe.jsxs)(Pe,{component:"span",sx:{color:"text.secondary"},children:["(",a,")"]})]})}var vw=F(W(),1);function glr({rateLimits:e}){let t=JO(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,vw.jsx)(vw.Fragment,{children:r.map((n,i)=>(0,vw.jsxs)(mlr.Fragment,{children:[i>0?(0,vw.jsx)(Pe,{component:"span",sx:{color:"text.secondary",mr:.5},children:","}):null,(0,vw.jsx)(plr,{window:n.window,windowSeconds:n.windowSeconds,fallbackLabel:n.fallbackLabel,now:t})]},n.fallbackLabel))})}function HMn(e){if(e==="over")return{level:"warn",boundary:100};if(e==="warn")return{level:"ok",boundary:75}}function WMn(e){if(e==="ok")return{level:"warn",boundary:75};if(e==="warn")return{level:"over",boundary:100}}function VMn(e,t,r,n){if(e>=t)return;let i=e/t;return Math.round(r-n*(1-i))}function blr(e,t,r,n){if(t==null)return{kind:"unprojectable"};let i=EOe(t,r,n);if(i==null)return{kind:"unprojectable"};let o=hw(e,t,r,n),a=HMn(o),s=WMn(o);return{kind:"projected",recovery:a&&{level:a.level,pct:a.boundary*i,at:VMn(e,a.boundary,t,r)},worse:s&&{level:s.level,pct:s.boundary*i}}}function xlr(e,t){return e.at==null?"not before reset":`${e.level==="ok"?"green":"under"} in ${Ehe(e.at,t)}`}var Gg=F(W(),1);function POe({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,Gg.jsx)(Pe,{component:"span",sx:n});let i=(0,Gg.jsx)(Pe,{component:"span",sx:{opacity:.6},children:r?"\u2190":"\u2192"}),o=(0,Gg.jsxs)(Pe,{component:"span",sx:{color:dw(t.level)},children:[Math.round(t.pct),"%"]});return(0,Gg.jsx)(Pe,{component:"span",sx:n,children:r?(0,Gg.jsxs)(Gg.Fragment,{children:[o,i]}):(0,Gg.jsxs)(Gg.Fragment,{children:[i,o]})})}var bw=F(W(),1);function Tlr({label:e,pct:t,resetsAt:r,windowSeconds:n,now:i}){let o=hw(t,r,n,i),a=blr(t,r,n,i),s=a.kind==="projected"?a:void 0;return(0,bw.jsxs)(Pe,{sx:{display:"flex",alignItems:"baseline",gap:.75},children:[(0,bw.jsx)(Pe,{component:"span",sx:{minWidth:"2ch"},children:e}),(0,bw.jsx)(POe,{direction:"back",threshold:s?.recovery}),(0,bw.jsxs)(Pe,{component:"span",sx:{minWidth:"4ch",textAlign:"right",color:dw(o)},children:[Math.round(t),"%"]}),(0,bw.jsx)(POe,{direction:"forward",threshold:s?.worse}),(0,bw.jsx)(Pe,{component:"span",sx:{opacity:.6},children:s?s.recovery&&xlr(s.recovery,i):"no projection yet"})]})}function Slr(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 OG=F(W(),1),LOe="Claude account usage (5h / 7d windows) \u2014 view history";function Clr({rateLimits:e}){let t=JO(3e4);return(0,OG.jsxs)(Pe,{sx:{fontFamily:"monospace",fontSize:12},children:[Slr(e).map(r=>(0,OG.jsx)(Tlr,{label:r.label,pct:r.pct,resetsAt:r.resetsAt,windowSeconds:r.windowSeconds,now:t},r.label)),(0,OG.jsx)(Pe,{sx:{mt:.5,opacity:.6},children:LOe})]})}var NG=F(W(),1),GMn={display:"flex",alignItems:"center",ml:2,fontFamily:"monospace",fontSize:13};function qMn(e){return e?.five_hour?.used_percentage!=null||e?.seven_day?.used_percentage!=null}function wlr({rateLimits:e}){let t=qMn(e);return(0,NG.jsx)(nn,{title:t?(0,NG.jsx)(Clr,{rateLimits:e}):LOe,children:(0,NG.jsx)(Wi,{component:Au,to:"/usage",underline:"hover",color:"inherit",sx:GMn,children:t?(0,NG.jsx)(glr,{rateLimits:e}):"Usage"})})}var _lr=F(W(),1),klr=bt((0,_lr.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 Fx=F(_e(),1);var r9={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 Elr(e){return fetch(`/api/restart?target=${e}`,{method:"POST"})}var Bx=F(_e(),1);var jMn="/api/session-layout";async function YMn(){try{return(await fetch(jMn,{cache:"no-store"})).ok}catch{return!1}}async function Rlr(e){let t=0;for(;!e();){if(t=await YMn()?t+1:0,t>=2)return!e();await new Promise(r=>setTimeout(r,300))}return!1}function KMn(){return{sawDisconnect:!1,waiting:!1,abandoned:!0}}function Alr(e,t,r){let n=(0,Bx.useRef)(KMn()),i=(0,Bx.useRef)(r);i.current=r,(0,Bx.useEffect)(()=>{let s=n.current;if(!(!e||s.abandoned)){if(t){s.sawDisconnect=!0;return}!s.sawDisconnect||s.waiting||(s.waiting=!0,Rlr(()=>s.abandoned).then(l=>{l&&i.current()}))}},[e,t]);let o=(0,Bx.useCallback)(()=>{n.current.abandoned=!0},[]),a=(0,Bx.useCallback)(()=>{n.current.abandoned=!0,n.current={sawDisconnect:!1,waiting:!1,abandoned:!1}},[]);return(0,Bx.useEffect)(()=>o,[o]),{arm:a,abandon:o}}var XMn=15e3;function n9(e,t,r){let[n,i]=(0,Fx.useState)(!1),[o,a]=(0,Fx.useState)(null),s=(0,Fx.useRef)(void 0),{arm:l,abandon:u}=Alr(n,t,()=>{clearTimeout(s.current),r?.(),globalThis.location.reload()});(0,Fx.useEffect)(()=>()=>clearTimeout(s.current),[]);let f=(0,Fx.useCallback)(async()=>{i(!0),l(),s.current=setTimeout(()=>{u(),i(!1),a("Web server did not come back")},XMn);try{if(!(await Elr(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:f}}var qg=F(W(),1),ZMn={color:"inherit",mr:1.5};function Plr({reconnecting:e}){let{pending:t,error:r,clearError:n,restart:i}=n9("webserver",e);return(0,qg.jsxs)(qg.Fragment,{children:[(0,qg.jsx)(nn,{title:"Restart web server",children:(0,qg.jsx)("span",{children:(0,qg.jsx)(mr,{sx:ZMn,disabled:t,onClick:i,children:t?(0,qg.jsx)(oo,{size:24}):(0,qg.jsx)(klr,{})})})}),(0,qg.jsx)(vh,{error:r,onClose:n})]})}var i9=F(_e(),1);var Vhe=F(_e(),1);var Ghe=F(W(),1);function Llr({cwd:e,selected:t,highlighted:r,onHover:n,onSelect:i}){let o=(0,Vhe.useRef)(null);return(0,Vhe.useEffect)(()=>{r&&o.current?.scrollIntoView({block:"nearest"})},[r]),(0,Ghe.jsxs)(Ln,{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:[BG(e),fC(e)&&(0,Ghe.jsx)(iC,{})]})}var MOe=F(W(),1);function Mlr({repos:e,selected:t,highlight:r,onHighlight:n,onSelect:i}){return(0,MOe.jsx)(kf,{dense:!0,children:e.map((o,a)=>(0,MOe.jsx)(Llr,{cwd:o,selected:o===t,highlighted:a===r,onHover:()=>n(a),onSelect:()=>i(o)},o))})}var FG=F(W(),1);function BG(e){let t=e.includes("\\")?"\\":"/";return e.split(t).filter(Boolean).pop()??e}var QMn={...mC};function Ilr({repos:e,selected:t,onSelect:r,close:n}){let[i,o]=(0,i9.useState)(""),a=(0,i9.useRef)(null);(0,i9.useEffect)(()=>{a.current?.focus()},[]);let s=i.trim().toLowerCase(),l=s?e.filter(p=>p.toLowerCase().includes(s)):e,{highlight:u,setHighlight:f,onKeyDown:h}=Nhe(l,s,r,n);return(0,FG.jsxs)(Fn,{elevation:4,sx:QMn,children:[(0,FG.jsx)(Ihe,{inputRef:a,value:i,onChange:o,onKeyDown:h,placeholder:"Filter repos..."}),(0,FG.jsx)(Mlr,{repos:l,selected:t,highlight:u,onHighlight:f,onSelect:p=>{r(p),n()}})]})}var o9=F(W(),1);function JMn(e){return e?fC(e)?(0,o9.jsxs)("span",{style:{display:"flex",flexGrow:1,alignItems:"center",justifyContent:"space-between",gap:6,minWidth:0},children:[BG(e),(0,o9.jsx)(iC,{})]}):BG(e):"Select repo..."}function Dlr({repos:e,selected:t,onSelect:r}){return(0,o9.jsx)(Gy,{label:JMn(t),children:n=>(0,o9.jsx)(Ilr,{repos:e,selected:t,onSelect:r,close:n})})}var Olr=F(_e(),1);var IOe=F(W(),1);function qhe({disabled:e,onSubmit:t,label:r="prompt",allowEmpty:n=!1}){let[i,o]=(0,Olr.useState)("");return(0,IOe.jsx)(Gy,{label:r,disabled:e,onDefaultAction:n?()=>t(""):void 0,children:a=>(0,IOe.jsx)(PD,{value:i,onChange:o,onSubmit:()=>{!n&&!i.trim()||(t(i),o(""),a())}})})}var e3=F(W(),1),eIn={textTransform:"none",fontSize:11,fontWeight:600};function Nlr({onSelect:e,disabled:t=!1,children:r}){return(0,e3.jsxs)(e3.Fragment,{children:[N8e.filter(n=>n.nav&&n.prompt).map(n=>(0,e3.jsx)(qhe,{label:n.label,allowEmpty:!0,disabled:t,onSubmit:i=>e(n.value,i)},n.value)),r,N8e.filter(n=>n.nav&&!n.prompt).map(n=>(0,e3.jsx)(yr,{size:"small",variant:"outlined",disabled:t,onClick:()=>e(n.value),sx:eIn,children:n.label},n.value))]})}var DOe=F(_e(),1);function Blr(e){let t=["claude"];return e.exposeCodexActions&&t.push("codex"),e.exposePiActions&&t.push("pi"),t}var jhe=F(W(),1),tIn={"& .MuiFormControlLabel-label":{fontSize:12}};function Flr({choices:e,value:t,onChange:r}){return(0,jhe.jsx)(Dme,{row:!0,value:t,onChange:n=>r(n.target.value),children:e.map(n=>(0,jhe.jsx)(Fm,{value:n,control:(0,jhe.jsx)(Mme,{size:"small"}),label:nC(n),sx:tIn},n))})}var Yhe=F(W(),1);function $lr({cwd:e,disabled:t,onCreate:r,onCreateHarness:n}){let i=Blr(rle()),[o,a]=(0,DOe.useState)(""),[s,l]=(0,DOe.useState)("claude"),u=f=>{s==="claude"?r(f,e):n(s,f,e)};return(0,Yhe.jsx)(Gy,{label:"prompt",disabled:t,onDefaultAction:()=>u(""),children:f=>(0,Yhe.jsx)(PD,{value:o,onChange:a,header:i.length>1?(0,Yhe.jsx)(Flr,{choices:i,value:s,onChange:l}):void 0,onSubmit:()=>{u(o),a(""),f()}})})}var t3=F(W(),1);function zlr({cwd:e,disabled:t,onCreate:r,onCreateDesign:n,onCreateHarness:i}){return(0,t3.jsxs)(t3.Fragment,{children:[(0,t3.jsx)($lr,{cwd:e,disabled:t,onCreate:r,onCreateHarness:i}),(0,t3.jsx)(qhe,{label:"design",allowEmpty:!0,disabled:t,onSubmit:o=>n(o,e)})]})}var jlr=F(_e(),1);var $G=F(_e(),1);function Khe(e){let[t,r]=(0,$G.useState)([]),[n,i]=(0,$G.useState)(!0);return(0,$G.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 Hd=F(W(),1);function Hlr({cwd:e,onPick:t}){let{prs:r,loading:n}=Khe(e);return(0,Hd.jsx)(Fn,{elevation:4,sx:{...mC,left:"auto",width:320},children:n?(0,Hd.jsx)(Ulr,{text:"Loading open PRs\u2026"}):r.length===0?(0,Hd.jsx)(Ulr,{text:"No open PRs"}):(0,Hd.jsx)(kf,{dense:!0,disablePadding:!0,children:r.map(i=>(0,Hd.jsx)(rIn,{pr:i,onPick:t},i.number))})})}function rIn({pr:e,onPick:t}){return(0,Hd.jsx)(Ln,{onMouseDown:r=>r.preventDefault(),onClick:()=>t(e),sx:{alignItems:"flex-start",py:.75,whiteSpace:"normal"},children:(0,Hd.jsxs)(Qt,{spacing:.25,sx:{minWidth:0},children:[(0,Hd.jsx)(Ze,{sx:{fontSize:13,lineHeight:1.3,fontWeight:500},children:e.title}),(0,Hd.jsxs)(Ze,{sx:{fontSize:11,color:"text.secondary"},children:["#",e.number," \xB7 ",e.author," \xB7 ",y0(e.createdAt)]})]})})}function Ulr({text:e}){return(0,Hd.jsx)(Pe,{sx:{p:1.5},children:(0,Hd.jsx)(Ze,{sx:{fontSize:13,color:"text.secondary"},children:e})})}var Vlr=F(W(),1);function Wlr({cwd:e,onPick:t}){return(0,Vlr.jsx)(Hlr,{cwd:e,onPick:t})}var Glr=F(_e(),1);var mu=F(W(),1);function qlr({pr:e,onSelect:t,onCancel:r}){let[n,i]=(0,Glr.useState)(OW);return(0,mu.jsxs)(wf,{open:!0,onClose:r,maxWidth:"xs",fullWidth:!0,children:[(0,mu.jsxs)(op,{sx:{fontSize:15},children:["Review #",e.number,": ",e.title]}),(0,mu.jsx)(ip,{sx:{px:0},children:(0,mu.jsxs)(kf,{children:[Wle.map(({label:o,args:a})=>(0,mu.jsx)(Ln,{onClick:()=>t([...a,...Vle(n)]),children:o},o)),(0,mu.jsx)(ea,{}),(0,mu.jsx)(Gle,{value:n,onChange:i}),(0,mu.jsx)(ea,{}),(0,mu.jsx)(Ln,{onClick:()=>t(["review","--checkout-only"]),children:"Checkout"}),(0,mu.jsx)(Ln,{onClick:()=>t(["review-pr-comments"]),children:"Address Comments"}),(0,mu.jsx)(Ln,{onClick:()=>t(["fix-conflict"]),children:"Fix conflicts (merge)"}),(0,mu.jsx)(Ln,{onClick:()=>t(["fix-conflict","--rebase"]),children:"Fix conflicts (rebase)"})]})}),(0,mu.jsx)(np,{children:(0,mu.jsx)(yr,{onClick:r,children:"Cancel"})})]})}var xw=F(W(),1);function Ylr({cwd:e,disabled:t,onSelect:r}){let{prs:n,loading:i}=Khe(e),[o,a]=(0,jlr.useState)(null);return i||n.length===0?null:(0,xw.jsxs)(xw.Fragment,{children:[(0,xw.jsx)(Gy,{label:"prs",disabled:t,children:s=>(0,xw.jsx)(Wlr,{cwd:e,onPick:l=>{a(l),s()}})}),o&&(0,xw.jsx)(qlr,{pr:o,onSelect:s=>{r(o,s),a(null)},onCancel:()=>a(null)})]})}var a9=F(W(),1);function Klr({onStartRun:e,cwd:t}){let r=Zle(t);return!t||r.length===0?null:(0,a9.jsx)(Gy,{label:"server",children:n=>(0,a9.jsx)(Fn,{elevation:4,sx:{...mC,left:"auto",width:200},children:(0,a9.jsx)(kf,{dense:!0,disablePadding:!0,children:r.map(i=>(0,a9.jsx)(Ln,{onMouseDown:o=>o.preventDefault(),onClick:()=>{e(i.name,t),n()},sx:{py:.75},children:(0,a9.jsx)(Ze,{sx:{fontSize:13},children:i.name})},i.name))})})})}var r3=F(W(),1);function Xlr({onCreate:e,onCreateDesign:t,onCreateHarness:r,onCreateAssist:n,onStartRun:i}){let{selectedCwd:o}=Na(),a=!o;return(0,r3.jsxs)(Qt,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:[(0,r3.jsxs)(Nlr,{disabled:a,onSelect:(s,l)=>UUt(s,o,n,()=>{},l),children:[(0,r3.jsx)(zlr,{cwd:o,disabled:a,onCreate:e,onCreateDesign:t,onCreateHarness:r}),(0,r3.jsx)(Ylr,{cwd:o,disabled:a,onSelect:(s,l)=>n([...l,String(s.number)],o,qle(s))})]}),(0,r3.jsx)(Klr,{onStartRun:i,cwd:o})]})}var Wd=F(W(),1),nIn={minHeight:48,pl:1,pr:14},iIn={width:240,ml:2};function Zlr({socket:e,selection:t}){let{collapsed:r,onToggleCollapsed:n}=DD();return(0,Wd.jsxs)(y_,{variant:"dense",disableGutters:!0,sx:nIn,children:[r&&(0,Wd.jsx)(ace,{collapsed:r,onToggleCollapsed:n}),(0,Wd.jsx)(Plr,{reconnecting:e.reconnecting}),(0,Wd.jsx)(hlr,{}),(0,Wd.jsx)(Pe,{sx:iIn,children:(0,Wd.jsx)(Dlr,{repos:t.repos,selected:t.selectedCwd,onSelect:t.setSelectedCwd})}),(0,Wd.jsxs)(Pe,{sx:{display:"flex",ml:1,mr:2},children:[(0,Wd.jsx)(Kle,{cwd:t.selectedCwd}),(0,Wd.jsx)(dlr,{cwd:t.selectedCwd})]}),(0,Wd.jsx)(Xlr,{onCreate:e.createSession,onCreateDesign:e.createDesignSession,onCreateHarness:e.createHarnessSession,onCreateAssist:e.createAssistSession,onStartRun:e.startRun}),(0,Wd.jsx)(wlr,{rateLimits:e.rateLimits})]})}var Qhe=F(_e(),1);var Qlr=F(W(),1),Jlr=bt((0,Qlr.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 ecr=F(W(),1),tcr=bt((0,ecr.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 rcr=F(W(),1),ncr=bt((0,rcr.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 OOe=F(W(),1);function icr({mode:e}){return e==="dark"?(0,OOe.jsx)(ncr,{fontSize:"small"}):(0,OOe.jsx)(tcr,{fontSize:"small"})}var ocr=F(W(),1),acr=bt((0,ocr.jsx)("path",{d:"m20.38 8.57-1.23 1.85a8 8 0 0 1-.22 7.58H5.07A8 8 0 0 1 15.58 6.85l1.85-1.23A10 10 0 0 0 3.35 19a2 2 0 0 0 1.72 1h13.85a2 2 0 0 0 1.74-1 10 10 0 0 0-.27-10.44zm-9.79 6.84a2 2 0 0 0 2.83 0l5.66-8.49-8.49 5.66a2 2 0 0 0 0 2.83"}),"Speed");var s9=F(W(),1);function scr(){let e=afe();return(0,s9.jsxs)(Ln,{onClick:()=>jKe(!e),children:[(0,s9.jsx)(p_,{children:(0,s9.jsx)(acr,{fontSize:"small"})}),(0,s9.jsx)($m,{children:e?"Hide render HUD":"Show render HUD"})]})}var gu=F(W(),1);function lcr({mode:e,onToggleColorMode:t,onRestart:r,onUpdate:n}){return[(0,gu.jsxs)(Ln,{onClick:t,children:[(0,gu.jsx)(p_,{children:(0,gu.jsx)(icr,{mode:e})}),(0,gu.jsx)($m,{children:"Toggle dark mode"})]},"color-mode"),(0,gu.jsx)(scr,{},"render-hud"),(0,gu.jsx)(ea,{},"restart-divider"),(0,gu.jsxs)(Ln,{onClick:r,children:[(0,gu.jsx)(p_,{children:(0,gu.jsx)(Nle,{fontSize:"small"})}),(0,gu.jsx)($m,{children:r9.label})]},"restart"),(0,gu.jsxs)(Ln,{onClick:n,children:[(0,gu.jsx)(p_,{children:(0,gu.jsx)(Jlr,{fontSize:"small"})}),(0,gu.jsx)($m,{children:"Update assist"})]},"update")]}var n3=F(W(),1);function ccr({reconnecting:e,onClose:t}){let{pending:r,error:n,clearError:i,restart:o}=n9(r9.target,e);return(0,n3.jsxs)(n3.Fragment,{children:[(0,n3.jsx)(ia,{title:r9.label,message:r9.message,confirmLabel:"Restart",busy:r,onConfirm:()=>{o()},onCancel:t}),(0,n3.jsx)(vh,{error:n,onClose:i})]})}var fcr=F(W(),1);function ucr({onConfirm:e,onClose:t}){return(0,fcr.jsx)(ia,{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 i3=F(W(),1);function hcr({restarting:e,reconnecting:t,onCloseRestart:r,updating:n,onCloseUpdate:i}){let{launchAssist:o,armUpdateReload:a}=Bf();return(0,i3.jsxs)(i3.Fragment,{children:[e&&(0,i3.jsx)(ccr,{reconnecting:t,onClose:r}),n&&(0,i3.jsx)(ucr,{onConfirm:()=>{a(),o(["update"])},onClose:i})]})}var dcr=F(W(),1),pcr=bt((0,dcr.jsx)("path",{d:"M3 18h18v-2H3zm0-5h18v-2H3zm0-7v2h18V6z"}),"Menu");var mcr=F(W(),1),gcr=bt((0,mcr.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 Xhe=F(W(),1);function ycr(){let e=wo();return(0,Xhe.jsx)(nn,{title:"Config",children:(0,Xhe.jsx)(mr,{size:"small",sx:{color:"inherit"},"aria-label":"Config",onClick:()=>e("/config"),children:(0,Xhe.jsx)(gcr,{fontSize:"small"})})})}var NOe=F(W(),1),vcr=bt([(0,NOe.jsx)("path",{d:"M12 5.99 19.53 19H4.47zM12 2 1 21h22z"},"0"),(0,NOe.jsx)("path",{d:"M13 16h-2v2h2zm0-6h-2v5h2z"},"1")],"WarningAmber");var zG="0.670.0";var Zhe=F(_e(),1),BOe=(0,Zhe.createContext)(null);function bcr(){return(0,Zhe.useContext)(BOe)}var Tw=F(W(),1);function xcr(){let e=bcr();return zG?(0,Tw.jsxs)(Tw.Fragment,{children:[(0,Tw.jsxs)(Ze,{variant:"caption",sx:{opacity:.4,userSelect:"none",lineHeight:1},children:["v",zG]}),e&&e!==zG&&(0,Tw.jsx)(nn,{title:`Daemon is running v${e}, but this page was served by v${zG}. Restart the daemon to match.`,children:(0,Tw.jsx)(vcr,{fontSize:"small",color:"warning","aria-label":"Version mismatch"})})]}):null}var o3=F(W(),1);function Tcr({open:e,onOpen:t}){return(0,o3.jsxs)(Pe,{sx:{position:"fixed",top:8,right:16,zIndex:r=>r.zIndex.drawer+2,display:"flex",alignItems:"center",gap:.5,color:"inherit"},children:[(0,o3.jsx)(xcr,{}),(0,o3.jsx)(ycr,{}),(0,o3.jsx)(mr,{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,o3.jsx)(pcr,{fontSize:"small"})})]})}var Sw=F(W(),1);function Scr({mode:e,toggle:t,reconnecting:r}){let[n,i]=(0,Qhe.useState)(null),[o,a]=(0,Qhe.useState)(!1),[s,l]=(0,Qhe.useState)(!1),u=!!n,f=()=>i(null);return(0,Sw.jsxs)(Sw.Fragment,{children:[(0,Sw.jsx)(Tcr,{open:u,onOpen:i}),(0,Sw.jsx)(ap,{anchorEl:n,open:u,onClose:f,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:lcr({mode:e,onToggleColorMode:()=>{t(),f()},onRestart:()=>{f(),a(!0)},onUpdate:()=>{f(),l(!0)}})}),(0,Sw.jsx)(hcr,{restarting:o,reconnecting:r,onCloseRestart:()=>a(!1),updating:s,onCloseUpdate:()=>l(!1)})]})}var _cr=F(_e(),1);var wcr=F(W(),1);function Ccr({conflict:e,onConfirm:t,onCancel:r}){let{name:n,cwd:i,port:o}=e.existing,a=rm(i),s=o?` on port ${o}`:"",l=a?` in ${a}`:"";return(0,wcr.jsx)(ia,{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 Jhe=F(W(),1);function kcr({socket:e,children:t}){let{serverConflict:r,clearServerConflict:n,retrySession:i,stopSession:o,startRun:a,discardSession:s}=e,l=(0,_cr.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,Jhe.jsxs)(L8e.Provider,{value:l,children:[t,r&&(0,Jhe.jsx)(Ccr,{conflict:r,onConfirm:u,onCancel:n})]})}var Ecr=new Map;function Rcr(e,t){if(!VX())return;let r=Ecr.get(e);if(Ecr.set(e,t),!!r)for(let[n,i]of Object.entries(t))Object.is(i,r[n])||v0(`\u0394 ${e}.${n}`)}var tde=F(_e(),1);function Acr(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||nm(i)!==t?null:n}function l9(e,t,r){if(e)return t.find(n=>n.id===e)??r.find(n=>n.sessionId===e)}function ede(){let{pathname:e}=Cs();return e.startsWith("/backlog")||e.startsWith("/usage")}function Pcr({selectedCwd:e,selectedCardId:t,sessions:r,history:n,activeByRepo:i,onSelect:o}){let a=l9(t,r,n),s=a&&nm(a),l=!!(s&&s===e),u=Acr(i,e,r),f=(0,tde.useRef)(t),h=ede();(0,tde.useEffect)(()=>{let d=f.current!==t&&!!s;f.current=t,!(h||d||l||!u)&&o(u)},[t,s,l,u,o,h])}var a3=F(_e(),1);function Lcr(e,t,r,n){return l9(e,t,r)?.cwd||n}function Mcr(e,t){let r=new Set,n=new Set,i=[];for(let o of t){if(o.cwdMissing)continue;let a=oC(o),s=nm(o);!a||!s||r.has(a)||n.has(s)||(r.add(a),n.add(s),i.push(s))}return e&&!r.has(hle(e,t))&&!n.has(e)&&i.unshift(e),i}var Icr=F(_e(),1);function rde(e,t,r){let n=l9(e,t,r);return n&&nm(n)}function Dcr(e,t,r,n){let i=rde(e,t,r);(0,Icr.useEffect)(()=>{i&&n(i)},[i,n])}function Ocr(e,t,r,n){let[i,o]=(0,a3.useState)(e);(0,a3.useEffect)(()=>{e&&!i&&o(e)},[e,i]),Dcr(r,n,t,o);let a=(0,a3.useMemo)(()=>Mcr(e,t),[e,t]),s=Lcr(r,n,t,i);return(0,a3.useMemo)(()=>({repos:a,selectedCwd:i,worktreeCwd:s,setSelectedCwd:o}),[a,i,s])}var ide=F(_e(),1);var Cw=F(_e(),1);var Ncr=F(_e(),1),nde="assist:reloaded-after-update";function Bcr(e){(0,Ncr.useEffect)(()=>{globalThis.sessionStorage?.getItem(nde)&&(globalThis.sessionStorage.removeItem(nde),e({message:"Reloaded after updating assist",sessionId:null}))},[e])}var jg=F(_e(),1);function Fcr(e){return e.commandType==="assist"&&e.assistArgs?.[0]==="update"&&e.status==="done"}function $cr(e,t){let[r,n]=(0,jg.useState)(!1),[i,o]=(0,jg.useState)(!1),a=(0,jg.useRef)(!1),s=(0,jg.useRef)(e);s.current=e;let l=(0,jg.useRef)(new Set),u=(0,jg.useCallback)(()=>{a.current=!1,o(!1),l.current=new Set(s.current.filter(Fcr).map(f=>f.id)),n(!0)},[]);return(0,jg.useEffect)(()=>{if(!r||i)return;if(t){a.current=!0;return}if(!a.current)return;e.some(h=>Fcr(h)&&!l.current.has(h.id))&&o(!0)},[r,i,t,e]),{arm:u,completed:i}}function zcr(e,t,r,n){let{arm:i,completed:o}=$cr(e,t),a=(0,Cw.useRef)(!1),s=(0,Cw.useCallback)(()=>{globalThis.sessionStorage?.setItem(nde,"1")},[]),{error:l,restart:u}=n9("webserver",t,s);return Bcr(r),(0,Cw.useEffect)(()=>{l&&n(l)},[l,n]),(0,Cw.useEffect)(()=>{!o||a.current||(a.current=!0,u())},[o,u]),{armUpdateReload:(0,Cw.useCallback)(()=>{a.current=!1,i()},[i])}}function Ucr(e){let{armUpdateReload:t}=zcr(e.sessions,e.reconnecting,e.setSuccess,e.setError),r=(0,ide.useMemo)(()=>({launchAssist:e.createAssistSession,launchAgentInStream:e.createSessionInStream,resumeSession:e.resumeSession,armUpdateReload:t}),[e.createAssistSession,e.createSessionInStream,e.resumeSession,t]),n=wo(),i=(0,ide.useCallback)(o=>{e.selectSession(o),n("/sessions"),e.clearSuccess()},[n,e.selectSession,e.clearSuccess]);return{launch:r,viewLaunchedSession:i}}var Hcr=F(_e(),1);function Wcr(e,t,r,n){let i=rde(e,t,r);(0,Hcr.useEffect)(()=>{e&&i&&n({type:"set-active",cwd:i,sessionId:e})},[e,i,n])}var ode=F(_e(),1);function Vcr(e,t){let r=(0,ode.useRef)(new Map);(0,ode.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 qcr=F(_e(),1);function Gcr(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 jcr(e,t){return(0,qcr.useCallback)(r=>{let n=e.current;n?.readyState===WebSocket.OPEN&&n.send(JSON.stringify(r));let i=Gcr(r);i&&t(i)},[e,t])}var h1=F(_e(),1);function Ycr(e){return(t,r)=>e({type:"create",prompt:t||void 0,cwd:r,auto:!0})}function Kcr(e){return(t,r)=>e({type:"create",prompt:t||void 0,cwd:r,design:!0})}function Xcr(e){return(t,r,n)=>e({type:"create",prompt:r||void 0,cwd:n,harness:t})}function Zcr(e){return(t,r,n)=>e({type:"create-assist",assistArgs:t,cwd:r,...n})}function Qcr(e){return(t,r,n,i)=>e({type:"resume",sessionId:t,cwd:r,name:n,harness:i})}function Jcr(e,t){return(r,n)=>{t.delete(r),e({type:"retry",sessionId:r,replace:n})}}function eur(e,t){return r=>{t.delete(r),e({type:"restart",sessionId:r})}}function tur(e,t){return r=>{e({type:"dismiss",sessionId:r}),t.delete(r)}}function rur(e,t){return r=>{e({type:"discard",sessionId:r}),t.delete(r)}}function nur(e){return t=>e({type:"stop",sessionId:t})}function iur(e){return(t,r,n,i)=>e({type:"create-run",runName:t,cwd:r,replace:n,launchedFrom:i})}function our(e){return(t,r)=>e({type:"set-autorun",sessionId:t,enabled:r})}function aur(e){return(t,r)=>e({type:"set-autoadvance",sessionId:t,enabled:r})}function sur(e){return(t,r)=>e({type:"set-starred",sessionId:t,starred:r})}function lur(e){return(t,r)=>e({type:"input",sessionId:t,data:r})}function cur(e){return(t,r,n)=>e({type:"resize",sessionId:t,cols:r,rows:n})}function uur(e,t){return(r,n)=>{let i=e.get(r);return i&&n(i),t.set(r,n),()=>t.delete(r)}}function fur(e){return(t,r,n,i)=>e({type:"pr-decision",sessionId:t,requestId:r,decision:n,...i})}var s3=F(_e(),1);function hur(e){return(t,r,n)=>e({type:"create",prompt:r||void 0,cwd:n,joinSessionId:t,auto:!0})}function dur(e){return{createSession:(0,s3.useMemo)(()=>Ycr(e),[e]),createSessionInStream:(0,s3.useMemo)(()=>hur(e),[e]),createDesignSession:(0,s3.useMemo)(()=>Kcr(e),[e]),createHarnessSession:(0,s3.useMemo)(()=>Xcr(e),[e]),createAssistSession:(0,s3.useMemo)(()=>Zcr(e),[e]),resumeSession:(0,s3.useMemo)(()=>Qcr(e),[e])}}var UG=F(_e(),1);function pur(e,t){let r=(0,UG.useCallback)((a,s)=>{Jcr(e,t.current)(a,s)},[e,t]),n=(0,UG.useCallback)(a=>{eur(e,t.current)(a)},[e,t]),i=(0,UG.useCallback)(a=>{tur(e,t.current)(a)},[e,t]),o=(0,UG.useCallback)(a=>{rur(e,t.current)(a)},[e,t]);return{retrySession:r,restartSession:n,dismissSession:i,discardSession:o}}function mur(e,t,r){let n={...dur(e),sendInput:(0,h1.useMemo)(()=>lur(e),[e]),sendResize:(0,h1.useMemo)(()=>cur(e),[e]),sendPrDecision:(0,h1.useMemo)(()=>fur(e),[e]),setAutoRun:(0,h1.useMemo)(()=>our(e),[e]),setAutoAdvance:(0,h1.useMemo)(()=>aur(e),[e]),setStarred:(0,h1.useMemo)(()=>sur(e),[e]),stopSession:(0,h1.useMemo)(()=>nur(e),[e]),startRun:(0,h1.useMemo)(()=>iur(e),[e])},i=(0,h1.useMemo)(()=>uur(t.current,r.current),[t,r]);return{...n,...pur(e,t),onOutput:i}}var ade=F(_e(),1);function gur(e,t,r){let n=(0,ade.useCallback)(a=>{r(a),e({type:"fetch-transcript",sessionId:a})},[e,r]),i=(0,ade.useCallback)(()=>{r(null)},[r]),o=(0,ade.useCallback)(a=>{r(null),t(a)},[t,r]);return{viewTranscript:n,clearTranscript:i,selectSession:o}}var $x=F(_e(),1);function yur(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 bur=F(_e(),1);function vur(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 xur(e,t,r){let n=ede();(0,bur.useEffect)(()=>{if(n){t(null);return}t(i=>vur(e,i,r))},[e,t,r,n])}var FOe=F(_e(),1);function Tur(){let[e,t]=(0,FOe.useState)({}),[r,n]=(0,FOe.useState)(null);return{activeByRepo:e,setActiveByRepo:t,daemonVersion:r,setDaemonVersion:n}}var l3=F(_e(),1);function Sur(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 Cur(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 wur(){let[e,t]=(0,l3.useState)(new Set),r=(0,l3.useRef)(new Map),n=(0,l3.useCallback)(o=>{t(a=>a.has(o)?a:new Set(a).add(o))},[]),i=(0,l3.useCallback)(o=>{let a=Cur(r.current,o);r.current=new Map(o.map(s=>[s.id,s.startedAt])),a.length&&t(s=>Sur(s,a))},[]);return{initialized:e,markInitialized:n,syncSessions:i}}var ww=F(_e(),1);function _ur(){let[e,t]=(0,ww.useState)(null),[r,n]=(0,ww.useState)(null),[i,o]=(0,ww.useState)(null),a=(0,ww.useCallback)(()=>t(null),[]),s=(0,ww.useCallback)(()=>n(null),[]),l=(0,ww.useCallback)(()=>o(null),[]);return{error:e,setError:t,clearError:a,success:r,setSuccess:n,clearSuccess:s,serverConflict:i,setServerConflict:o,clearServerConflict:l}}var d1=F(_e(),1);function kur(e,t){return[...e,{...t,windows:fC(t.cwd),status:"launching"}]}function sde(e){return e.find(t=>t.status==="launching")}function Eur(e){let t=sde(e);return t?e.filter(r=>r.id!==t.id):e}function Rur(e,t){let r=sde(e);return r?$Oe(e,r.id,t):e}function $Oe(e,t,r){return e.map(n=>n.id===t&&n.status==="launching"?{...n,status:"error",error:r}:n)}function Aur(e,t){return e.filter(r=>r.id!==t)}var Pur=F(_e(),1);var oIn=6e4,aIn="Launch timed out \u2014 the session did not start.";function Lur(e,t){(0,Pur.useEffect)(()=>{let r=e.filter(i=>i.status==="launching");if(r.length===0)return;let n=r.map(i=>setTimeout(()=>t(o=>$Oe(o,i.id,aIn)),Math.max(0,oIn-(Date.now()-i.startedAt))));return()=>n.forEach(clearTimeout)},[e,t])}function Mur(){let[e,t]=(0,d1.useState)([]),r=(0,d1.useRef)([]),n=(0,d1.useCallback)(l=>{r.current=l(r.current),t(r.current)},[]),i=(0,d1.useCallback)(l=>{n(u=>kur(u,{id:crypto.randomUUID(),startedAt:Date.now(),...l}))},[n]),o=(0,d1.useCallback)(()=>{let l=sde(r.current);return n(Eur),l?.named?l.title:void 0},[n]),a=(0,d1.useCallback)(l=>n(u=>Rur(u,l)),[n]),s=(0,d1.useCallback)(l=>n(u=>Aur(u,l)),[n]);return Lur(e,n),{pendingLaunches:e,addPendingLaunch:i,resolvePendingLaunch:o,failPendingLaunch:a,dismissPendingLaunch:s}}var Iur=F(_e(),1);function Dur(e,t){return(0,Iur.useCallback)(r=>{e(r),t(r)},[e,t])}var zOe=F(_e(),1);function Our(){let[e,t]=(0,zOe.useState)(null),[r,n]=(0,zOe.useState)(null);return{transcript:e,setTranscript:t,viewingTranscriptSessionId:r,setViewingTranscriptSessionId:n}}var _w=F(_e(),1);function Nur(e,t){let r=e.sessionId;t.buffers.current?.delete(r),t.handlers.current?.get(r)?.("\x1Bc")}function Bur(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 Fur(e,t){let r=e.message;t.setError(r),t.failPendingLaunch(r)}function $ur(e,t){t.setSuccess({message:e.message,sessionId:null})}function zur(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 Uur(e,t){t.setServerConflict({existing:e.existing,runName:e.runName,cwd:e.cwd,sessionId:e.sessionId,launchedFrom:e.launchedFrom})}function Hur(e,t){let r=e.sessions;t.setSessions(r),e.cwd&&t.setCurrentCwd(e.cwd),t.setActiveByRepo(e.active??{})}function Wur(e,t){switch(e.type){case"sessions":Hur(e,t);break;case"created":Bur(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":Fur(e,t);break;case"notice":$ur(e,t);break;case"run-conflict":Uur(e,t);break;case"limits":t.setRateLimits(e.rateLimits);break;case"clear":Nur(e,t);break;case"output":zur(e,t);break}}function Vur(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=>{Wur(JSON.parse(i.data),e)},n.onclose=()=>t.onClose?.(),n}function Gur(e,t,r,n){let i=!1,o,a=0,s=!1,l=()=>{i||t(Vur(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 qur(e){let t=(0,_w.useRef)(null),[r,n]=(0,_w.useState)(!1),{handleSessions:i,markInitialized:o,buffers:a,handlers:s}=e;(0,_w.useEffect)(()=>{let u=()=>{a.current?.clear();let h=s.current;if(h)for(let d of h.values())d("\x1Bc")},f=Gur({...e,setSessions:i},h=>{t.current=h},u,n);return()=>{f(),t.current?.close()}},[i,o,a,s]);let l=(0,_w.useCallback)(()=>{let u=t.current;u?.readyState===WebSocket.OPEN&&u.send(JSON.stringify({type:"history"}))},[]);return{wsRef:t,requestHistory:l,reconnecting:r}}function jur(){let[e,t]=(0,$x.useState)([]),[r,n]=(0,$x.useState)([]),[i,o]=(0,$x.useState)(null),a=Tur(),s=Our(),[l,u]=(0,$x.useState)(""),f=_ur(),h=Mur(),[d,p]=(0,$x.useState)(null),{initialized:m,markInitialized:g,syncSessions:y}=wur(),v=(0,$x.useRef)(new Map),b=(0,$x.useRef)(new Map),x=Dur(y,t),{wsRef:C,requestHistory:S,reconnecting:w}=qur({handleSessions:x,setHistory:n,setActiveId:o,...a,...s,setCurrentCwd:u,...f,...h,setRateLimits:p,markInitialized:g,buffers:v,handlers:b});return xur(e,o,yur(a.activeByRepo,e)),{sessions:e,history:r,activeId:i,setActiveId:o,...a,...s,currentCwd:l,...f,...h,rateLimits:d,initialized:m,wsRef:C,buffers:v,handlers:b,requestHistory:S,reconnecting:w}}function Yur(){let e=jur(),{wsRef:t,buffers:r,handlers:n,addPendingLaunch:i,activeId:o,sessions:a}=e,s=jcr(t,i),l=mur(s,r,n);Wcr(o,a,e.history,s),Vcr(a,s);let u=gur(s,e.setActiveId,e.setViewingTranscriptSessionId);return{...e,...l,...u}}var c9=F(_e(),1);var Kur="assist:sidebar-collapsed";function Xur(){let[e,t]=(0,c9.useState)(()=>hm(Kur).length>0),r=(0,c9.useCallback)(()=>{t(n=>{let i=!n;return dm(Kur,i?[!0]:[]),i})},[]);return(0,c9.useMemo)(()=>({collapsed:e,onToggleCollapsed:r}),[e,r])}var lde=F(_e(),1);function Zur(){let[e,t]=(0,lde.useState)(!0);return(0,lde.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 Qur(){let e=Yur(),t=sfe(e),r=Ocr(e.currentCwd,e.history,t,e.sessions);Pcr({selectedCwd:r.selectedCwd,selectedCardId:t,sessions:e.sessions,history:e.history,activeByRepo:e.activeByRepo,onSelect:e.selectSession});let{launch:n,viewLaunchedSession:i}=Ucr(e),o=Zur(),a=Xur();return Rcr("shell",{...e,selection:r,launch:n,topBar:o,sidebarCollapse:a}),{socket:e,selection:r,launch:n,viewLaunchedSession:i,topBar:o,sidebarCollapse:a}}var kh=F(W(),1),sIn={zIndex:e=>e.zIndex.drawer+1},lIn={minHeight:48};function Jur({mode:e,toggle:t}){let{socket:r,selection:n,launch:i,viewLaunchedSession:o,topBar:a,sidebarCollapse:s}=Qur();return(0,kh.jsx)(C8e.Provider,{value:a,children:(0,kh.jsx)(X8e.Provider,{value:s,children:(0,kh.jsx)(eF.Provider,{value:n,children:(0,kh.jsxs)(f1e.Provider,{value:i,children:[(0,kh.jsx)(BOe.Provider,{value:r.daemonVersion,children:(0,kh.jsx)(Scr,{mode:e,toggle:t,reconnecting:r.reconnecting})}),(0,kh.jsx)(Ppe,{position:"fixed",elevation:1,sx:sIn,children:(0,kh.jsx)(Zlr,{socket:r,selection:n})}),(0,kh.jsx)(y_,{variant:"dense",sx:lIn}),(0,kh.jsx)(kcr,{socket:r,children:(0,kh.jsx)(Xsr,{socket:r})}),(0,kh.jsx)(flr,{socket:r,onViewLaunchedSession:o})]})})})})}var efr=F(_e(),1);function tfr(){let[e,t]=(0,efr.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 kw=F(W(),1),cIn={MuiButtonBase:{styleOverrides:{root:{cursor:"pointer","&.Mui-disabled":{cursor:"default"}}}},MuiLink:{styleOverrides:{root:{cursor:"pointer"}}}};function uIn(){let{mode:e,toggle:t}=tfr(),r=(0,nfr.useMemo)(()=>e0({palette:{mode:e,...e==="dark"&&{background:{default:"#1e1e1e",paper:"#252526"}}},components:cIn}),[e]);return(0,kw.jsxs)(Kq,{theme:r,children:[(0,kw.jsx)(Fj,{}),(0,kw.jsx)(Jur,{mode:e,toggle:t})]})}var fIn=r1e([{path:"*",element:(0,kw.jsx)(uIn,{})}]);function hIn(){return(0,kw.jsx)(Yye,{router:fIn})}var rfr=document.getElementById("app");rfr&&(0,ifr.createRoot)(rfr).render((0,kw.jsx)(hIn,{}));})();
3973
+ `,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 ADe.get()},set promptLabel(e){ADe.set(e)},get tooMuchOutput(){return PDe.get()},set tooMuchOutput(e){PDe.set(e)}}}_verifyIntegers(...e){for(a1 of e)if(a1===1/0||isNaN(a1)||a1%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(a1 of e)if(a1&&(a1===1/0||isNaN(a1)||a1%1!==0||a1<0))throw new Error("This API only accepts positive integers")}};var COe=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\^<>`]*[^\s"':,.!?{}|\\^~[\]`()<>]/;function JLn(e){try{return!!new URL(e).host}catch{return!1}}function zar(e,t){let r=e(t),n=e(t+1);return!!r&&!!n&&(n.isWrapped||r.isFull)}function eMn(e,t){let r=[];for(let n=t;n-t<64;n++){let i=e(n);if(!i||(r.push(i.text),!zar(e,n)))break}return r}function $ar(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 tMn(e,t,r){let n=r[0],i=$ar(e,t,r.index),o=$ar(e,t,r.index+n.length-1);if(!(!JLn(n)||!i||!o))return{text:n,range:{start:i,end:o}}}function rMn(e,t,r){let n=new RegExp(r.source,`${r.flags||""}g`);return[...e.join("").matchAll(n)].flatMap(o=>tMn(e,t,o)??[])}function Uar(e,t,r=COe){if(!e(t-1))return[];let n=t-1;for(;n>0&&zar(e,n-1);)n--;return rMn(eMn(e,n),n,r)}function Har(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=Uar(r,n,COe);i(o.map(a=>({range:a.range,text:a.text,activate:t})))}}}function War(e){let t=new Far({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 pnr;t.loadAddon(r);let n=t.registerLinkProvider(Har(t,(o,a)=>{window.open(a,"_blank")}));t.open(e);let i;try{i=new Iir,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 Var(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 The(e){return e.type==="keydown"&&(e.ctrlKey||e.metaKey)&&!e.shiftKey&&!e.altKey&&e.key.toLowerCase()==="p"}function Gar(e,t,r,n,i){let o=War(e);o.term.onData(u=>r(t,u)),o.term.attachCustomKeyEventHandler(u=>The(u)?!1:Var(u,o.term,navigator.clipboard,f=>o.term.paste(f)));let a=n(t,u=>o.term.write(u)),s=new ResizeObserver(()=>{Rfe(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 qar(e,t,r,n,i,o){let a=(0,wG.useRef)(null);(0,wG.useEffect)(()=>{let s=e.current;if(!s)return;let{handle:l,cleanup:u}=Gar(s,t,n,i,o);return a.current=l,()=>{u(),a.current=null}},[e,t,i,n,o]),(0,wG.useEffect)(()=>{let s=a.current;if(!r||!s)return;let l=setTimeout(()=>{Rfe(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 Kar=F(W(),1);function Yar({sessionId:e,visible:t,onOutput:r,sendInput:n,sendResize:i}){let o=(0,jar.useRef)(null);return qar(o,e,t,n,r,i),(0,Kar.jsx)(Pe,{ref:o,sx:{position:"absolute",inset:"0 0 0 8px",visibility:t?"visible":"hidden",pointerEvents:t?"auto":"none"}})}var XE=F(W(),1);function Xar({sessions:e,activeId:t,activeLoading:r,onOutput:n,sendInput:i,sendResize:o}){return(0,XE.jsxs)(Pe,{sx:{flex:1,position:"relative",bgcolor:"background.default"},children:[e.map(a=>(0,XE.jsx)(Yar,{sessionId:a.id,visible:a.id===t,onOutput:n,sendInput:i,sendResize:o},a.id)),r&&(0,XE.jsx)(dnr,{}),e.length===0&&(0,XE.jsx)(Pe,{sx:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:(0,XE.jsx)(Ze,{variant:"body2",color:"text.disabled",children:"Create a session to get started"})})]})}var Qar=F(W(),1);function Zar({sessions:e,activeId:t,initialized:r,onOutput:n,sendInput:i,sendResize:o}){let a=e.find(l=>l.id===t),s=a!==void 0&&vle(a,r);return(0,Qar.jsx)(Xar,{sessions:e,activeId:t,activeLoading:s,onOutput:n,sendInput:i,sendResize:o})}var KO=F(W(),1),nMn={position:"relative",display:"flex",flex:1,minWidth:0,minHeight:0};function Jar({activeSession:e,sendPrDecision:t,showLastMessage:r,...n}){return(0,KO.jsxs)(Pe,{sx:nMn,children:[(0,KO.jsx)(onr,{session:e,sendPrDecision:t,sendInput:n.sendInput,children:(0,KO.jsx)(Zar,{...n})}),r&&e!==void 0&&(0,KO.jsx)(fnr,{message:e.lastUserMessage})]})}var esr=F(W(),1),tsr=bt((0,esr.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 Tm=F(W(),1);function rsr({message:e}){return e.role==="tool"?(0,Tm.jsx)(iMn,{tool:e.tool,target:e.target}):(0,Tm.jsx)(oMn,{role:e.role,text:e.text})}function iMn({tool:e,target:t}){return(0,Tm.jsxs)(Pe,{sx:{display:"flex",alignItems:"center",gap:1,py:.5,pl:1},children:[(0,Tm.jsx)(tsr,{sx:{fontSize:14,color:"text.disabled"}}),(0,Tm.jsxs)(Ze,{variant:"caption",sx:{color:"text.secondary",fontFamily:"monospace"},children:[(0,Tm.jsx)(Pe,{component:"span",sx:{color:"warning.main"},children:e}),t&&(0,Tm.jsxs)(Pe,{component:"span",children:[" ",t]})]})]})}function oMn({role:e,text:t}){let r=e==="user",n=r?"info.main":"success.main";return(0,Tm.jsxs)(Pe,{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,Tm.jsx)(Ze,{variant:"caption",sx:{color:n,fontWeight:600,display:"block",mb:.5},children:r?"User":"Assistant"}),(0,Tm.jsx)(Ze,{variant:"body2",sx:{color:"text.primary",whiteSpace:"pre-wrap",overflowWrap:"anywhere",lineHeight:1.6},children:t})]})}var u1=F(W(),1);function aMn(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 isr({messages:e,loading:t}){return t?(0,u1.jsxs)(Pe,{sx:nsr,children:[(0,u1.jsx)(oo,{size:20}),(0,u1.jsx)(Ze,{variant:"caption",color:"text.disabled",children:"Loading transcript\u2026"})]}):e.length===0?(0,u1.jsx)(Pe,{sx:nsr,children:(0,u1.jsx)(Ze,{variant:"body2",color:"text.disabled",children:"No transcript available"})}):(0,u1.jsx)(Pe,{sx:{position:"absolute",inset:0,overflowY:"auto",p:2},children:(0,u1.jsx)(Pe,{sx:{maxWidth:820,mx:"auto"},children:aMn(e).map(r=>(0,u1.jsx)(rsr,{message:r},r.key))})})}var nsr={position:"absolute",inset:0,display:"flex",flexDirection:"column",gap:1.5,alignItems:"center",justifyContent:"center"};var wOe=F(W(),1);function osr({sessionId:e,transcript:t}){let r=t?.sessionId===e;return(0,wOe.jsx)(Pe,{sx:{flex:1,position:"relative",bgcolor:"background.default"},children:(0,wOe.jsx)(isr,{messages:r?t?.messages??[]:[],loading:!r})})}var fw=F(W(),1),sMn={flex:1,minHeight:0,display:"flex",flexDirection:"column"},lMn={flexShrink:0};function asr({viewingTranscriptSessionId:e,transcript:t,sendPrDecision:r,lifecycle:n,...i}){let o=yh();if(e!==null)return(0,fw.jsx)(osr,{sessionId:e,transcript:t});let a=i.sessions.find(s=>s.id===i.activeId);return(0,fw.jsxs)(Pe,{sx:sMn,children:[o&&a!==void 0&&(0,fw.jsx)(Pe,{sx:lMn,children:(0,fw.jsx)(Per,{session:a,lifecycle:n})}),(0,fw.jsx)(Der,{sessionId:i.activeId,sessions:i.sessions,sendInput:i.sendInput,children:(0,fw.jsx)(Jar,{...i,activeSession:a,sendPrDecision:r,showLastMessage:o})})]})}var csr=F(W(),1);function lsr({socket:e}){let t=(0,ssr.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,csr.jsx)(asr,{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})}var Ysr=F(_e(),1);var XO=F(_e(),1);function She(e,t){let r=(0,XO.useRef)(null),[n,i]=(0,XO.useState)();return(0,XO.useLayoutEffect)(()=>{e===t&&r.current&&i(r.current.offsetHeight)},[e,t]),{ref:r,height:n}}var fsr=F(_e(),1);function Che(e){if(e.startsWith("local:")){let n=e.slice(6).replace(/\/+$/,"").split("/").filter(Boolean);return n[n.length-1]??e}let t=e.indexOf("/");return t===-1?e:e.slice(t+1)}function whe(e){let t=o=>o.startsWith("local:"),r=o=>{let a=Che(o),s=a.split("/");return s[s.length-1]??a},n=new Map;for(let o of new Set(e)){if(t(o))continue;let a=r(o);n.set(a,(n.get(a)??0)+1)}let i=new Map;for(let o of e){if(t(o)){i.set(o,Che(o));continue}let a=r(o),s=(n.get(a)??0)>1;i.set(o,s?Che(o):a)}return i}var _G={field:"lastPhase",direction:"desc"};var kG="all",EG="all";async function usr(e,t,r){let n=new URLSearchParams({page:String(e),pageSize:String(t)});r.origin!==kG&&n.set("origin",r.origin),r.status!==EG&&n.set("status",r.status),r.sort.field!==_G.field&&n.set("sort",r.sort.field),r.sort.direction!==_G.direction&&n.set("direction",r.sort.direction);let i=await fetch(`/api/usage/items?${n}`);if(!i.ok)throw new Error(`Failed to load item usage (HTTP ${i.status}).`);return i.json()}var RG=F(W(),1);function hsr({origins:e,origin:t,onChange:r}){let n=(0,fsr.useMemo)(()=>whe(e.map(o=>o.origin)),[e]),i=e.reduce((o,a)=>o+a.count,0);return(0,RG.jsxs)(xi,{select:!0,size:"small",label:"Repo",value:t,onChange:o=>r(o.target.value),sx:{minWidth:220},children:[(0,RG.jsx)(Ln,{value:kG,children:`All repos (${i})`}),e.map(o=>(0,RG.jsx)(Ln,{value:o.origin,children:`${n.get(o.origin)??o.origin} (${o.count})`},o.origin))]})}var _Oe=F(W(),1),cMn=[{value:EG,label:"All"},{value:"done",label:"Done"},{value:"running",label:"Running"}];function dsr({status:e,onChange:t}){return(0,_Oe.jsx)(Ef,{size:"small",exclusive:!0,value:e,onChange:(r,n)=>n&&t(n),"aria-label":"Filter items by status",children:cMn.map(r=>(0,_Oe.jsx)(Ks,{value:r.value,children:r.label},r.value))})}var ZO=F(W(),1),uMn={display:"flex",alignItems:"center",gap:2,flexWrap:"wrap",mb:2},fMn="Repos show their bare name, or org/repo when two share one. Totals sum every phase's recorded usage.";function psr({origins:e,origin:t,onOriginChange:r,status:n,onStatusChange:i}){return(0,ZO.jsxs)(Pe,{sx:uMn,children:[(0,ZO.jsx)(dsr,{status:n,onChange:i}),(0,ZO.jsx)(hsr,{origins:e,origin:t,onChange:r}),(0,ZO.jsx)(Ze,{variant:"caption",color:"text.disabled",children:fMn})]})}var ksr=F(_e(),1);var khe=F(W(),1),hMn={whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},msr={display:"block",fontSize:"0.75rem",color:"text.disabled",whiteSpace:"nowrap"},dMn={...msr,fontStyle:"italic"};function _he({total:e,perPhase:t,partial:r}){return(0,khe.jsxs)(bn,{align:"right",sx:hMn,children:[e,t?(0,khe.jsx)(Ze,{component:"span",sx:r?dMn:msr,children:t}):null]})}var AG=F(W(),1),pMn={width:"100%",maxWidth:0},mMn={display:"block",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},gMn={display:"block",mt:"2px",fontSize:"0.75rem",color:"text.secondary",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function gsr({id:e,name:t,type:r,repoLabel:n}){return(0,AG.jsxs)(bn,{sx:pMn,children:[(0,AG.jsx)(Wi,{component:Au,to:$2(e),underline:"hover",color:"text.primary",title:t,sx:mMn,children:t}),(0,AG.jsxs)(Ze,{component:"span",sx:gMn,children:[lo(e)," \xB7 ",r," \xB7 ",n]})]})}function ysr(e){let t=Math.max(1,e.recordedPhases);return{active:`${qm(e.activeMs/t)} / phase`,tokens:`${Nf(Math.round((e.tokensUp+e.tokensDown)/t))} / phase`}}function vsr(e){if(!(e.status==="done"||e.recordedPhases>e.phaseCount))return`${e.recordedPhases} of ${e.phaseCount} phases`}var yMn=new Set(["done","wontdo"]);function bsr(e){return yMn.has(e)?{label:e,color:MX[e]}:{label:"running",color:"warning"}}var kOe=F(W(),1),vMn={height:20,fontSize:"0.6875rem"};function xsr({status:e}){let t=bsr(e);return(0,kOe.jsx)(bn,{children:(0,kOe.jsx)(Zn,{label:t.label,size:"small",variant:"outlined",color:t.color,sx:vMn})})}var Wg=F(W(),1),Tsr={whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"};function Ssr({row:e,repoLabel:t}){let r=ysr(e);return(0,Wg.jsxs)(ku,{hover:!0,children:[(0,Wg.jsx)(gsr,{id:e.id,name:e.name,type:e.type,repoLabel:t}),(0,Wg.jsx)(xsr,{status:e.status}),(0,Wg.jsx)(_he,{total:String(e.phaseCount||e.recordedPhases),perPhase:vsr(e),partial:!0}),(0,Wg.jsx)(_he,{total:qm(e.activeMs),perPhase:r.active}),(0,Wg.jsx)(_he,{total:`\u2191 ${Nf(e.tokensUp)} \u2193 ${Nf(e.tokensDown)}`,perPhase:r.tokens}),(0,Wg.jsx)(bn,{align:"right",sx:Tsr,children:(0,Wg.jsxs)(Pe,{component:"span",sx:{color:Sle(e.peakContextPct)},children:[Math.round(e.peakContextPct),"%"]})}),(0,Wg.jsx)(bn,{align:"right",sx:Tsr,children:e.lastPhaseAt?y0(e.lastPhaseAt):"\u2014"})]})}var Csr=[{label:"Item"},{label:"Status"},{label:"Phases",sort:"phases",numeric:!0},{label:"Active",sort:"active",numeric:!0,tooltip:"Accumulated active time across the item's phases \u2014 not wall clock."},{label:"Tokens",sort:"tokens",numeric:!0},{label:"Peak ctx",sort:"peakContext",numeric:!0,tooltip:"The highest context-window usage any one phase reached."},{label:"Last phase",sort:"lastPhase",numeric:!0,tooltip:"When the item's most recent phase session started."}];var Sm=F(W(),1),bMn={"& th":{whiteSpace:"nowrap"}};function wsr({column:e}){return e.tooltip?(0,Sm.jsx)(nn,{title:e.tooltip,describeChild:!0,children:(0,Sm.jsx)("span",{children:e.label})}):(0,Sm.jsx)(Sm.Fragment,{children:e.label})}function _sr({sort:e,onSort:t}){return(0,Sm.jsx)(g_,{sx:bMn,children:(0,Sm.jsx)(ku,{children:Csr.map(r=>{let n=r.sort,i=n!==void 0&&e.field===n;return(0,Sm.jsx)(bn,{align:r.numeric?"right":"left",sortDirection:i?e.direction:!1,children:n===void 0?(0,Sm.jsx)(wsr,{column:r}):(0,Sm.jsx)(Hme,{active:i,direction:i?e.direction:"desc",onClick:()=>t(n),children:(0,Sm.jsx)(wsr,{column:r})})},r.label)})})})}var ZE=F(W(),1),xMn={"& td, & th":{px:1.5}};function Esr({rows:e,origins:t,sort:r,onSort:n}){let i=(0,ksr.useMemo)(()=>whe([...t,...e.map(o=>o.origin)]),[t,e]);return(0,ZE.jsx)(m_,{component:Fn,children:(0,ZE.jsxs)(N1,{size:"small",sx:xMn,children:[(0,ZE.jsx)(_sr,{sort:r,onSort:n}),(0,ZE.jsx)(B1,{children:e.map(o=>(0,ZE.jsx)(Ssr,{row:o,repoLabel:i.get(o.origin)??o.origin},o.id))})]})})}function Rsr(e){let t=Math.max(1,e.medianPhases),r=e.repoCount===1?"repo":"repos";return{items:String(e.itemCount),itemsFoot:`across ${e.repoCount} ${r} \xB7 ${e.doneCount} done`,phases:String(Math.round(e.medianPhases*10)/10),active:qm(e.medianActiveMs),activeFoot:`${qm(e.medianActiveMs/t)} per phase`,tokens:Nf(Math.round(e.medianTokens)),tokensFoot:`${Nf(Math.round(e.medianTokens/t))} per phase`}}var QO=F(W(),1),Asr={display:"block"},TMn={fontWeight:400,fontVariantNumeric:"tabular-nums"};function PG({label:e,value:t,foot:r}){return(0,QO.jsxs)(Pe,{children:[(0,QO.jsx)(Ze,{variant:"caption",color:"text.secondary",sx:Asr,children:e}),(0,QO.jsx)(Ze,{variant:"h5",sx:TMn,children:t}),r?(0,QO.jsx)(Ze,{variant:"caption",color:"text.disabled",sx:Asr,children:r}):null]})}var QE=F(W(),1),SMn={display:"flex",flexDirection:{xs:"column",sm:"row"},mb:3,"& > *":{flex:1,minWidth:0,p:2},"& > * + *":{borderColor:"divider",borderTop:{xs:1,sm:0},borderLeft:{xs:0,sm:1}}};function Psr({summary:e}){let t=Rsr(e);return(0,QE.jsxs)(Fn,{sx:SMn,children:[(0,QE.jsx)(PG,{label:"Items with recorded usage",value:t.items,foot:t.itemsFoot}),(0,QE.jsx)(PG,{label:"Median phases",value:t.phases}),(0,QE.jsx)(PG,{label:"Median active time",value:t.active,foot:t.activeFoot}),(0,QE.jsx)(PG,{label:"Median tokens",value:t.tokens,foot:t.tokensFoot})]})}var Ud=F(W(),1);function Lsr({items:e,data:t}){let{rows:r,total:n,page:i,pageSize:o}=e,{ref:a,height:s}=She(r.length,o);return(0,Ud.jsxs)(Ud.Fragment,{children:[(0,Ud.jsx)(Psr,{summary:t.summary}),(0,Ud.jsx)(psr,{origins:t.origins,origin:e.origin,onOriginChange:e.selectOrigin,status:e.status,onStatusChange:e.selectStatus}),n===0?(0,Ud.jsx)(Ze,{color:"text.secondary",align:"center",sx:{py:6},children:"No items match this filter."}):(0,Ud.jsxs)(Ud.Fragment,{children:[(0,Ud.jsx)(Pe,{ref:a,sx:{minHeight:s},children:(0,Ud.jsx)(Esr,{rows:r,origins:t.origins.map(l=>l.origin),sort:e.sort,onSort:e.sortBy})}),(0,Ud.jsx)(zN,{component:"div",count:n,page:i,rowsPerPage:o,rowsPerPageOptions:[o],onPageChange:(l,u)=>e.setPage(u)})]})]})}var Ox=F(W(),1);function Msr({items:e}){let{data:t}=e;return(0,Ox.jsxs)(Ox.Fragment,{children:[(0,Ox.jsx)(Pe,{sx:{height:4,mb:1},children:e.fetching&&(0,Ox.jsx)(d_,{})}),t?t.origins.length===0?(0,Ox.jsx)(Ze,{color:"text.secondary",align:"center",sx:{py:6},children:"No item usage recorded yet."}):(0,Ox.jsx)(Lsr,{items:e,data:t}):null]})}function EOe(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 Ehe(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 CMn(e,t,r,n){let i=EOe(t,r,n);if(i!=null)return e/i}function hw(e,t,r,n){let i=CMn(e,t,r,n);return i==null?"ok":i>100?"over":i>75?"warn":"ok"}var JE={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 wMn={ok:"success.main",warn:"warning.main",over:"error.main"};function dw(e){return wMn[e]}var IG=F(W(),1),_Mn={ok:"success",warn:"warning",over:"error"};function Isr({percentage:e,level:t}){return(0,IG.jsxs)(Pe,{sx:{display:"flex",alignItems:"center",gap:1},children:[(0,IG.jsx)(d_,{variant:"determinate",value:Math.min(100,e),color:_Mn[t],sx:{flexGrow:1,height:8,borderRadius:1}}),(0,IG.jsxs)(Pe,{sx:{minWidth:40,textAlign:"right",color:dw(t)},children:[Math.round(e),"%"]})]})}function Dsr(e){return e.avgContextPct==null?"\u2014":`${Math.round(e.avgContextPct)}%`}var kMn=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});function ROe(e){return kMn.format(e)}var Rhe=F(W(),1);function Osr({peak:e}){return(0,Rhe.jsx)(bn,{align:"right",sx:{whiteSpace:"nowrap"},children:(0,Rhe.jsx)(nn,{title:`Cycle started ${ROe(new Date(e.createdAt))}`,children:(0,Rhe.jsx)("span",{children:ROe(new Date(e.resetsAt*1e3))})})})}var Bsr=F(W(),1);function Nsr(){return(0,Bsr.jsx)(Zn,{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 Fsr(e){return!e.tokensUp&&!e.tokensDown?"\u2014":`\u2191 ${Nf(e.tokensUp)} \u2193 ${Nf(e.tokensDown)}`}var Vg=F(W(),1);function $sr({peak:e,now:t}){let{label:r,seconds:n,tint:i}=JE[e.window],o=hw(e.usedPercentage,e.resetsAt,n,t);return(0,Vg.jsxs)(ku,{sx:a=>({backgroundColor:i?a.palette.mode==="dark"?i.dark:i.light:void 0}),children:[(0,Vg.jsxs)(bn,{children:[r,e.resetDetected&&(0,Vg.jsx)(Nsr,{})]}),(0,Vg.jsx)(bn,{sx:{minWidth:160},children:(0,Vg.jsx)(Isr,{percentage:e.usedPercentage,level:o})}),(0,Vg.jsx)(bn,{align:"right",sx:{whiteSpace:"nowrap"},children:Dsr(e)}),(0,Vg.jsx)(bn,{align:"right",sx:{whiteSpace:"nowrap"},children:e.phaseCount??0}),(0,Vg.jsx)(bn,{align:"right",sx:{whiteSpace:"nowrap"},children:Fsr(e)}),(0,Vg.jsx)(Osr,{peak:e})]})}var Ahe=F(_e(),1);function JO(e){let[t,r]=(0,Ahe.useState)(()=>Math.floor(Date.now()/1e3));return(0,Ahe.useEffect)(()=>{let n=setInterval(()=>r(Math.floor(Date.now()/1e3)),e);return()=>clearInterval(n)},[e]),t}var ec=F(W(),1);function zsr({peaks:e}){let t=JO(3e4);return(0,ec.jsx)(m_,{component:Fn,children:(0,ec.jsxs)(N1,{size:"small",children:[(0,ec.jsx)(g_,{sx:{"& th":{whiteSpace:"nowrap"}},children:(0,ec.jsxs)(ku,{children:[(0,ec.jsx)(bn,{children:"Window"}),(0,ec.jsx)(bn,{children:"Peak usage"}),(0,ec.jsx)(bn,{align:"right",children:(0,ec.jsx)(nn,{title:"Mean context-window usage across all readings in this rate-limit cycle \u2014 distinct from the Peak usage quota above.",children:(0,ec.jsx)("span",{children:"Avg context"})})}),(0,ec.jsx)(bn,{align:"right",children:(0,ec.jsx)(nn,{title:"Number of phase readings behind the average.",children:(0,ec.jsx)("span",{children:"Phases"})})}),(0,ec.jsx)(bn,{align:"right",children:"Tokens spent"}),(0,ec.jsx)(bn,{align:"right",children:"Cycle reset"})]})}),(0,ec.jsx)(B1,{children:e.map(r=>(0,ec.jsx)($sr,{peak:r,now:t},`${r.window}-${r.resetsAt}-${r.segment}`))})]})})}var pw=F(W(),1);function Usr({rows:e,total:t,page:r,pageSize:n,onPageChange:i}){let{ref:o,height:a}=She(e.length,n);return(0,pw.jsxs)(pw.Fragment,{children:[(0,pw.jsx)(Pe,{ref:o,sx:{minHeight:a},children:(0,pw.jsx)(zsr,{peaks:e})}),(0,pw.jsx)(zN,{component:"div",count:t,page:r,rowsPerPage:n,rowsPerPageOptions:[n],onPageChange:(s,l)=>i(l)})]})}var AOe=F(W(),1),EMn=[{value:"all",label:"All"},{value:"five_hour",label:JE.five_hour.label},{value:"seven_day",label:JE.seven_day.label}];function Hsr({window:e,onChange:t}){return(0,AOe.jsx)(Ef,{size:"small",exclusive:!0,value:e,onChange:(r,n)=>n&&t(n),"aria-label":"Filter peaks by rate-limit window",children:EMn.map(r=>(0,AOe.jsx)(Ks,{value:r.value,children:r.label},r.value))})}var f1=F(W(),1);function Wsr({history:e}){let{window:t,total:r}=e;return(0,f1.jsxs)(f1.Fragment,{children:[(0,f1.jsx)(Hsr,{window:t,onChange:e.selectWindow}),(0,f1.jsx)(Pe,{sx:{height:4,my:1},children:e.fetching&&(0,f1.jsx)(d_,{})}),r===0?(0,f1.jsx)(Ze,{color:"text.secondary",align:"center",sx:{py:6},children:t==="all"?"No usage peaks recorded yet.":`No ${JE[t].label} usage peaks recorded yet.`}):(0,f1.jsx)(Usr,{rows:e.rows,total:r,page:e.page,pageSize:e.pageSize,onPageChange:e.setPage})]})}var Lhe=F(_e(),1);async function Vsr(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()}var mw=F(_e(),1);function Phe(e,t,r=!0){let[n,i]=(0,mw.useState)(0),[o,a]=(0,mw.useState)(null),[s,l]=(0,mw.useState)(!1),[u,f]=(0,mw.useState)(null);(0,mw.useEffect)(()=>{if(!r)return;let p=!1;return l(!0),e(n,t).then(m=>{p||(a(m),l(!1))},m=>{p||(f(m instanceof Error?m:new Error(String(m))),l(!1))}),()=>{p=!0}},[e,n,t,r]);let h=o?.total??0;(0,mw.useEffect)(()=>{if(h===0)return;let p=Math.ceil(h/t)-1;n>p&&i(p)},[n,t,h]);let d=o?.rows??[];return{data:o,rows:d,total:h,loaded:o!==null,fetching:s,error:u,page:n,setPage:i,pageSize:t}}var RMn=30;function Gsr(){let[e,t]=(0,Lhe.useState)("all"),r=(0,Lhe.useCallback)((o,a)=>Vsr(o,a,e),[e]),n=Phe(r,RMn);return{...n,window:e,selectWindow:o=>{t(o),n.setPage(0)}}}var e9=F(_e(),1);function qsr(e,t){return e.field!==t?{field:t,direction:"desc"}:{field:t,direction:e.direction==="desc"?"asc":"desc"}}var AMn=30;function jsr(e){let[t,r]=(0,e9.useState)(kG),[n,i]=(0,e9.useState)(EG),[o,a]=(0,e9.useState)(_G),s=(0,e9.useCallback)((d,p)=>usr(d,p,{origin:t,status:n,sort:o}),[t,n,o]),l=Phe(s,AMn,e);return{...l,origin:t,selectOrigin:d=>{r(d),l.setPage(0)},status:n,selectStatus:d=>{i(d),l.setPage(0)},sort:o,sortBy:d=>{a(p=>qsr(p,d)),l.setPage(0)}}}var gw=F(W(),1),PMn={borderBottom:1,borderColor:"divider",mb:2};function Ksr(){let[e,t]=(0,Ysr.useState)("limits"),r=Gsr(),n=jsr(e==="items");if(r.error)throw r.error;if(n.error)throw n.error;return(0,gw.jsxs)(sm,{loading:!r.loaded,title:"Usage history",maxWidth:"lg",children:[(0,gw.jsxs)(v_,{value:e,onChange:(i,o)=>t(o),textColor:"inherit",indicatorColor:"secondary",sx:PMn,"aria-label":"Usage history views",children:[(0,gw.jsx)(zm,{label:"Rate limits",value:"limits"}),(0,gw.jsx)(zm,{label:"Items",value:"items"})]}),e==="limits"?(0,gw.jsx)(Wsr,{history:r}):(0,gw.jsx)(Msr,{items:n})]})}var io=F(W(),1);function LMn({socket:e}){return(0,io.jsx)(hN,{maxWidth:"lg",sx:{py:3,px:2},children:(0,io.jsx)(uzt,{socket:e})})}function Xsr({socket:e}){return v0("AppRoutes"),(0,io.jsxs)(io.Fragment,{children:[(0,io.jsx)(her,{}),(0,io.jsx)(G_,{children:(0,io.jsxs)(kl,{element:(0,io.jsx)(SWt,{socket:e}),children:[(0,io.jsx)(kl,{path:"sessions",element:(0,io.jsx)(lsr,{socket:e})}),(0,io.jsx)(kl,{path:"backlog/*",element:(0,io.jsx)(LMn,{socket:e})}),(0,io.jsx)(kl,{path:"news",element:(0,io.jsx)(ler,{})}),(0,io.jsx)(kl,{path:"usage",element:(0,io.jsx)(Ksr,{})}),(0,io.jsx)(kl,{path:"backups",element:(0,io.jsx)(AWt,{})}),(0,io.jsx)(kl,{path:"config",element:(0,io.jsx)(gGt,{})}),(0,io.jsx)(kl,{path:"diff",element:(0,io.jsx)(EJt,{sessions:e.sessions,sendInput:e.sendInput})}),(0,io.jsx)(kl,{path:"file",element:(0,io.jsx)(ier,{sessions:e.sessions,sendInput:e.sendInput,cardId:sfe(e)})}),(0,io.jsx)(kl,{path:"*",element:(0,io.jsx)(Kye,{to:"/sessions",replace:!0})})]})})]})}var Fhe=F(_e(),1);var Bhe=F(_e(),1);function Zsr(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 yw=F(W(),1),MMn={display:"flex",gap:1,alignItems:"center",minWidth:0},IMn={display:"flex",gap:1,alignItems:"baseline",minWidth:0,overflow:"hidden"},DMn={fontFamily:"monospace",fontSize:13,whiteSpace:"nowrap"},OMn={fontFamily:"monospace",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function NMn(e){let t=e.lastIndexOf("/");return t===-1?{dir:"",basename:e}:{dir:e.slice(0,t),basename:e.slice(t+1)}}function Qsr({files:e,highlight:t,onHighlight:r,onSelect:n}){return(0,yw.jsx)(kf,{dense:!0,sx:{py:0},children:e.map((i,o)=>{let{dir:a,basename:s}=NMn(i);return(0,yw.jsxs)(Ln,{selected:o===t,onMouseEnter:()=>r(o),onClick:()=>n(i),sx:MMn,children:[(0,yw.jsx)(wO,{path:i}),(0,yw.jsxs)(Pe,{sx:IMn,children:[(0,yw.jsx)(Ze,{component:"span",sx:DMn,children:s}),(0,yw.jsx)(Ze,{component:"span",color:"text.secondary",sx:OMn,children:a})]})]},i)})})}var Mhe=F(W(),1),BMn={maxHeight:420,overflowY:"auto"},FMn={px:2,py:2,fontSize:13};function Jsr({message:e,files:t,highlight:r,onHighlight:n,onSelect:i}){return(0,Mhe.jsx)(Pe,{sx:BMn,children:e?(0,Mhe.jsx)(Ze,{color:"text.secondary",sx:FMn,children:e}):(0,Mhe.jsx)(Qsr,{files:t,highlight:r,onHighlight:n,onSelect:i})})}var elr=F(W(),1);function Ihe({inputRef:e,value:t,onChange:r,onKeyDown:n,placeholder:i,autoFocus:o}){return(0,elr.jsx)(xi,{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 Dhe=F(_e(),1),tlr={files:[],loading:!1,error:!1};function rlr(e,t){let[r,n]=(0,Dhe.useState)(tlr);return(0,Dhe.useEffect)(()=>{if(!e){n(tlr);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 Ohe=F(_e(),1);function Nhe(e,t,r,n){let[i,o]=(0,Ohe.useState)(0);return(0,Ohe.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 DG=F(W(),1),$Mn={mt:6,alignSelf:"flex-start"};function nlr({onClose:e}){let{worktreeCwd:t}=Na(),[r,n]=(0,Bhe.useState)(""),i=rlr(t,r),o=wo(),a=(0,Bhe.useRef)(null),s=d=>o(`/file?${new URLSearchParams(t?{path:d,cwd:t}:{path:d})}`),{highlight:l,setHighlight:u,onKeyDown:f}=Nhe(i.files,r,s,e),h=d=>{s(d),e()};return(0,DG.jsxs)(wf,{open:!0,onClose:e,maxWidth:"sm",fullWidth:!0,slotProps:{paper:{sx:$Mn},transition:{onEntered:()=>a.current?.focus()}},children:[(0,DG.jsx)(Ihe,{autoFocus:!0,inputRef:a,value:r,onChange:n,onKeyDown:f,placeholder:"Search files by name..."}),(0,DG.jsx)(Jsr,{message:Zsr(t,r,i),files:i.files,highlight:l,onHighlight:u,onSelect:h})]})}var olr=F(_e(),1);var ilr=!0;function alr(e){(0,olr.useEffect)(()=>{let t=r=>{The(r)&&(r.preventDefault(),e())};return globalThis.addEventListener("keydown",t,ilr),()=>globalThis.removeEventListener("keydown",t,ilr)},[e])}var llr=F(W(),1);function slr(){let[e,t]=(0,Fhe.useState)(!1);return alr((0,Fhe.useCallback)(()=>t(!0),[])),e?(0,llr.jsx)(nlr,{onClose:()=>t(!1)}):null}var $he=F(W(),1);function clr({notice:e,onClose:t,onView:r}){let n=e?.sessionId??null;return(0,$he.jsx)(Yc,{open:e!==null,autoHideDuration:6e3,onClose:t,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:(0,$he.jsx)(Qo,{severity:"success",variant:"filled",onClose:t,action:n!==null?(0,$he.jsx)(yr,{color:"inherit",size:"small",onClick:()=>r(n),children:"View"}):void 0,children:e?.message})})}var zhe=F(W(),1);function ulr({reconnecting:e}){return(0,zhe.jsx)(Yc,{open:e,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:(0,zhe.jsx)(Qo,{severity:"info",variant:"filled",icon:(0,zhe.jsx)(oo,{size:16,color:"inherit"}),children:"Reconnecting\u2026"})})}var Nx=F(W(),1);function flr({socket:e,onViewLaunchedSession:t}){return(0,Nx.jsxs)(Nx.Fragment,{children:[(0,Nx.jsx)(slr,{}),(0,Nx.jsx)(ulr,{reconnecting:e.reconnecting}),(0,Nx.jsx)(vh,{error:e.error,onClose:e.clearError}),(0,Nx.jsx)(clr,{notice:e.success,onClose:e.clearSuccess,onView:t})]})}var t9=F(W(),1),zMn=["/sessions","/backlog","/news"];function hlr(){let e=Cs(),t=wo(),r=zMn.findIndex(i=>e.pathname.startsWith(i)),n=i=>{e.pathname!==i&&t(i)};return(0,t9.jsxs)(v_,{value:r===-1?0:r,textColor:"inherit",indicatorColor:"secondary",children:[(0,t9.jsx)(zm,{label:"Sessions",onClick:()=>n("/sessions")}),(0,t9.jsx)(zm,{label:"Backlog",onClick:()=>n("/backlog")}),(0,t9.jsx)(zm,{label:"News",onClick:()=>n("/news")})]})}var Hhe=F(_e(),1),Uhe=F(W(),1),UMn={color:"inherit"};function dlr({cwd:e}){let[t,r]=(0,Hhe.useState)(null);return(0,Hhe.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,Uhe.jsx)(nn,{title:"Open in GitHub",children:(0,Uhe.jsx)(mr,{sx:UMn,onClick:()=>window.open(t,"_blank"),children:(0,Uhe.jsx)(P6,{})})}):null}var mlr=F(_e(),1);var Whe=F(W(),1);function plr({window:e,windowSeconds:t,fallbackLabel:r,now:n}){let i=e?.used_percentage;if(i==null)return null;let o=hw(i,e?.resets_at,t,n),a=e?.resets_at!=null?Ehe(e.resets_at,n):r;return(0,Whe.jsxs)(Pe,{component:"span",children:[(0,Whe.jsxs)(Pe,{component:"span",sx:{color:dw(o)},children:[Math.round(i),"%"]})," ",(0,Whe.jsxs)(Pe,{component:"span",sx:{color:"text.secondary"},children:["(",a,")"]})]})}var vw=F(W(),1);function glr({rateLimits:e}){let t=JO(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,vw.jsx)(vw.Fragment,{children:r.map((n,i)=>(0,vw.jsxs)(mlr.Fragment,{children:[i>0?(0,vw.jsx)(Pe,{component:"span",sx:{color:"text.secondary",mr:.5},children:","}):null,(0,vw.jsx)(plr,{window:n.window,windowSeconds:n.windowSeconds,fallbackLabel:n.fallbackLabel,now:t})]},n.fallbackLabel))})}function HMn(e){if(e==="over")return{level:"warn",boundary:100};if(e==="warn")return{level:"ok",boundary:75}}function WMn(e){if(e==="ok")return{level:"warn",boundary:75};if(e==="warn")return{level:"over",boundary:100}}function VMn(e,t,r,n){if(e>=t)return;let i=e/t;return Math.round(r-n*(1-i))}function blr(e,t,r,n){if(t==null)return{kind:"unprojectable"};let i=EOe(t,r,n);if(i==null)return{kind:"unprojectable"};let o=hw(e,t,r,n),a=HMn(o),s=WMn(o);return{kind:"projected",recovery:a&&{level:a.level,pct:a.boundary*i,at:VMn(e,a.boundary,t,r)},worse:s&&{level:s.level,pct:s.boundary*i}}}function xlr(e,t){return e.at==null?"not before reset":`${e.level==="ok"?"green":"under"} in ${Ehe(e.at,t)}`}var Gg=F(W(),1);function POe({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,Gg.jsx)(Pe,{component:"span",sx:n});let i=(0,Gg.jsx)(Pe,{component:"span",sx:{opacity:.6},children:r?"\u2190":"\u2192"}),o=(0,Gg.jsxs)(Pe,{component:"span",sx:{color:dw(t.level)},children:[Math.round(t.pct),"%"]});return(0,Gg.jsx)(Pe,{component:"span",sx:n,children:r?(0,Gg.jsxs)(Gg.Fragment,{children:[o,i]}):(0,Gg.jsxs)(Gg.Fragment,{children:[i,o]})})}var bw=F(W(),1);function Tlr({label:e,pct:t,resetsAt:r,windowSeconds:n,now:i}){let o=hw(t,r,n,i),a=blr(t,r,n,i),s=a.kind==="projected"?a:void 0;return(0,bw.jsxs)(Pe,{sx:{display:"flex",alignItems:"baseline",gap:.75},children:[(0,bw.jsx)(Pe,{component:"span",sx:{minWidth:"2ch"},children:e}),(0,bw.jsx)(POe,{direction:"back",threshold:s?.recovery}),(0,bw.jsxs)(Pe,{component:"span",sx:{minWidth:"4ch",textAlign:"right",color:dw(o)},children:[Math.round(t),"%"]}),(0,bw.jsx)(POe,{direction:"forward",threshold:s?.worse}),(0,bw.jsx)(Pe,{component:"span",sx:{opacity:.6},children:s?s.recovery&&xlr(s.recovery,i):"no projection yet"})]})}function Slr(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 OG=F(W(),1),LOe="Claude account usage (5h / 7d windows) \u2014 view history";function Clr({rateLimits:e}){let t=JO(3e4);return(0,OG.jsxs)(Pe,{sx:{fontFamily:"monospace",fontSize:12},children:[Slr(e).map(r=>(0,OG.jsx)(Tlr,{label:r.label,pct:r.pct,resetsAt:r.resetsAt,windowSeconds:r.windowSeconds,now:t},r.label)),(0,OG.jsx)(Pe,{sx:{mt:.5,opacity:.6},children:LOe})]})}var NG=F(W(),1),GMn={display:"flex",alignItems:"center",ml:2,fontFamily:"monospace",fontSize:13};function qMn(e){return e?.five_hour?.used_percentage!=null||e?.seven_day?.used_percentage!=null}function wlr({rateLimits:e}){let t=qMn(e);return(0,NG.jsx)(nn,{title:t?(0,NG.jsx)(Clr,{rateLimits:e}):LOe,children:(0,NG.jsx)(Wi,{component:Au,to:"/usage",underline:"hover",color:"inherit",sx:GMn,children:t?(0,NG.jsx)(glr,{rateLimits:e}):"Usage"})})}var _lr=F(W(),1),klr=bt((0,_lr.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 Fx=F(_e(),1);var r9={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 Elr(e){return fetch(`/api/restart?target=${e}`,{method:"POST"})}var Bx=F(_e(),1);var jMn="/api/session-layout";async function YMn(){try{return(await fetch(jMn,{cache:"no-store"})).ok}catch{return!1}}async function Rlr(e){let t=0;for(;!e();){if(t=await YMn()?t+1:0,t>=2)return!e();await new Promise(r=>setTimeout(r,300))}return!1}function KMn(){return{sawDisconnect:!1,waiting:!1,abandoned:!0}}function Alr(e,t,r){let n=(0,Bx.useRef)(KMn()),i=(0,Bx.useRef)(r);i.current=r,(0,Bx.useEffect)(()=>{let s=n.current;if(!(!e||s.abandoned)){if(t){s.sawDisconnect=!0;return}!s.sawDisconnect||s.waiting||(s.waiting=!0,Rlr(()=>s.abandoned).then(l=>{l&&i.current()}))}},[e,t]);let o=(0,Bx.useCallback)(()=>{n.current.abandoned=!0},[]),a=(0,Bx.useCallback)(()=>{n.current.abandoned=!0,n.current={sawDisconnect:!1,waiting:!1,abandoned:!1}},[]);return(0,Bx.useEffect)(()=>o,[o]),{arm:a,abandon:o}}var XMn=15e3;function n9(e,t,r){let[n,i]=(0,Fx.useState)(!1),[o,a]=(0,Fx.useState)(null),s=(0,Fx.useRef)(void 0),{arm:l,abandon:u}=Alr(n,t,()=>{clearTimeout(s.current),r?.(),globalThis.location.reload()});(0,Fx.useEffect)(()=>()=>clearTimeout(s.current),[]);let f=(0,Fx.useCallback)(async()=>{i(!0),l(),s.current=setTimeout(()=>{u(),i(!1),a("Web server did not come back")},XMn);try{if(!(await Elr(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:f}}var qg=F(W(),1),ZMn={color:"inherit",mr:1.5};function Plr({reconnecting:e}){let{pending:t,error:r,clearError:n,restart:i}=n9("webserver",e);return(0,qg.jsxs)(qg.Fragment,{children:[(0,qg.jsx)(nn,{title:"Restart web server",children:(0,qg.jsx)("span",{children:(0,qg.jsx)(mr,{sx:ZMn,disabled:t,onClick:i,children:t?(0,qg.jsx)(oo,{size:24}):(0,qg.jsx)(klr,{})})})}),(0,qg.jsx)(vh,{error:r,onClose:n})]})}var i9=F(_e(),1);var Vhe=F(_e(),1);var Ghe=F(W(),1);function Llr({cwd:e,selected:t,highlighted:r,onHover:n,onSelect:i}){let o=(0,Vhe.useRef)(null);return(0,Vhe.useEffect)(()=>{r&&o.current?.scrollIntoView({block:"nearest"})},[r]),(0,Ghe.jsxs)(Ln,{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:[BG(e),fC(e)&&(0,Ghe.jsx)(iC,{})]})}var MOe=F(W(),1);function Mlr({repos:e,selected:t,highlight:r,onHighlight:n,onSelect:i}){return(0,MOe.jsx)(kf,{dense:!0,children:e.map((o,a)=>(0,MOe.jsx)(Llr,{cwd:o,selected:o===t,highlighted:a===r,onHover:()=>n(a),onSelect:()=>i(o)},o))})}var FG=F(W(),1);function BG(e){let t=e.includes("\\")?"\\":"/";return e.split(t).filter(Boolean).pop()??e}var QMn={...mC};function Ilr({repos:e,selected:t,onSelect:r,close:n}){let[i,o]=(0,i9.useState)(""),a=(0,i9.useRef)(null);(0,i9.useEffect)(()=>{a.current?.focus()},[]);let s=i.trim().toLowerCase(),l=s?e.filter(p=>p.toLowerCase().includes(s)):e,{highlight:u,setHighlight:f,onKeyDown:h}=Nhe(l,s,r,n);return(0,FG.jsxs)(Fn,{elevation:4,sx:QMn,children:[(0,FG.jsx)(Ihe,{inputRef:a,value:i,onChange:o,onKeyDown:h,placeholder:"Filter repos..."}),(0,FG.jsx)(Mlr,{repos:l,selected:t,highlight:u,onHighlight:f,onSelect:p=>{r(p),n()}})]})}var o9=F(W(),1);function JMn(e){return e?fC(e)?(0,o9.jsxs)("span",{style:{display:"flex",flexGrow:1,alignItems:"center",justifyContent:"space-between",gap:6,minWidth:0},children:[BG(e),(0,o9.jsx)(iC,{})]}):BG(e):"Select repo..."}function Dlr({repos:e,selected:t,onSelect:r}){return(0,o9.jsx)(Gy,{label:JMn(t),children:n=>(0,o9.jsx)(Ilr,{repos:e,selected:t,onSelect:r,close:n})})}var Olr=F(_e(),1);var IOe=F(W(),1);function qhe({disabled:e,onSubmit:t,label:r="prompt",allowEmpty:n=!1}){let[i,o]=(0,Olr.useState)("");return(0,IOe.jsx)(Gy,{label:r,disabled:e,onDefaultAction:n?()=>t(""):void 0,children:a=>(0,IOe.jsx)(PD,{value:i,onChange:o,onSubmit:()=>{!n&&!i.trim()||(t(i),o(""),a())}})})}var e3=F(W(),1),eIn={textTransform:"none",fontSize:11,fontWeight:600};function Nlr({onSelect:e,disabled:t=!1,children:r}){return(0,e3.jsxs)(e3.Fragment,{children:[N8e.filter(n=>n.nav&&n.prompt).map(n=>(0,e3.jsx)(qhe,{label:n.label,allowEmpty:!0,disabled:t,onSubmit:i=>e(n.value,i)},n.value)),r,N8e.filter(n=>n.nav&&!n.prompt).map(n=>(0,e3.jsx)(yr,{size:"small",variant:"outlined",disabled:t,onClick:()=>e(n.value),sx:eIn,children:n.label},n.value))]})}var DOe=F(_e(),1);function Blr(e){let t=["claude"];return e.exposeCodexActions&&t.push("codex"),e.exposePiActions&&t.push("pi"),t}var jhe=F(W(),1),tIn={"& .MuiFormControlLabel-label":{fontSize:12}};function Flr({choices:e,value:t,onChange:r}){return(0,jhe.jsx)(Dme,{row:!0,value:t,onChange:n=>r(n.target.value),children:e.map(n=>(0,jhe.jsx)(Fm,{value:n,control:(0,jhe.jsx)(Mme,{size:"small"}),label:nC(n),sx:tIn},n))})}var Yhe=F(W(),1);function $lr({cwd:e,disabled:t,onCreate:r,onCreateHarness:n}){let i=Blr(rle()),[o,a]=(0,DOe.useState)(""),[s,l]=(0,DOe.useState)("claude"),u=f=>{s==="claude"?r(f,e):n(s,f,e)};return(0,Yhe.jsx)(Gy,{label:"prompt",disabled:t,onDefaultAction:()=>u(""),children:f=>(0,Yhe.jsx)(PD,{value:o,onChange:a,header:i.length>1?(0,Yhe.jsx)(Flr,{choices:i,value:s,onChange:l}):void 0,onSubmit:()=>{u(o),a(""),f()}})})}var t3=F(W(),1);function zlr({cwd:e,disabled:t,onCreate:r,onCreateDesign:n,onCreateHarness:i}){return(0,t3.jsxs)(t3.Fragment,{children:[(0,t3.jsx)($lr,{cwd:e,disabled:t,onCreate:r,onCreateHarness:i}),(0,t3.jsx)(qhe,{label:"design",allowEmpty:!0,disabled:t,onSubmit:o=>n(o,e)})]})}var jlr=F(_e(),1);var $G=F(_e(),1);function Khe(e){let[t,r]=(0,$G.useState)([]),[n,i]=(0,$G.useState)(!0);return(0,$G.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 Hd=F(W(),1);function Hlr({cwd:e,onPick:t}){let{prs:r,loading:n}=Khe(e);return(0,Hd.jsx)(Fn,{elevation:4,sx:{...mC,left:"auto",width:320},children:n?(0,Hd.jsx)(Ulr,{text:"Loading open PRs\u2026"}):r.length===0?(0,Hd.jsx)(Ulr,{text:"No open PRs"}):(0,Hd.jsx)(kf,{dense:!0,disablePadding:!0,children:r.map(i=>(0,Hd.jsx)(rIn,{pr:i,onPick:t},i.number))})})}function rIn({pr:e,onPick:t}){return(0,Hd.jsx)(Ln,{onMouseDown:r=>r.preventDefault(),onClick:()=>t(e),sx:{alignItems:"flex-start",py:.75,whiteSpace:"normal"},children:(0,Hd.jsxs)(Qt,{spacing:.25,sx:{minWidth:0},children:[(0,Hd.jsx)(Ze,{sx:{fontSize:13,lineHeight:1.3,fontWeight:500},children:e.title}),(0,Hd.jsxs)(Ze,{sx:{fontSize:11,color:"text.secondary"},children:["#",e.number," \xB7 ",e.author," \xB7 ",y0(e.createdAt)]})]})})}function Ulr({text:e}){return(0,Hd.jsx)(Pe,{sx:{p:1.5},children:(0,Hd.jsx)(Ze,{sx:{fontSize:13,color:"text.secondary"},children:e})})}var Vlr=F(W(),1);function Wlr({cwd:e,onPick:t}){return(0,Vlr.jsx)(Hlr,{cwd:e,onPick:t})}var Glr=F(_e(),1);var mu=F(W(),1);function qlr({pr:e,onSelect:t,onCancel:r}){let[n,i]=(0,Glr.useState)(OW);return(0,mu.jsxs)(wf,{open:!0,onClose:r,maxWidth:"xs",fullWidth:!0,children:[(0,mu.jsxs)(op,{sx:{fontSize:15},children:["Review #",e.number,": ",e.title]}),(0,mu.jsx)(ip,{sx:{px:0},children:(0,mu.jsxs)(kf,{children:[Wle.map(({label:o,args:a})=>(0,mu.jsx)(Ln,{onClick:()=>t([...a,...Vle(n)]),children:o},o)),(0,mu.jsx)(ea,{}),(0,mu.jsx)(Gle,{value:n,onChange:i}),(0,mu.jsx)(ea,{}),(0,mu.jsx)(Ln,{onClick:()=>t(["review","--checkout-only"]),children:"Checkout"}),(0,mu.jsx)(Ln,{onClick:()=>t(["review-pr-comments"]),children:"Address Comments"}),(0,mu.jsx)(Ln,{onClick:()=>t(["fix-conflict"]),children:"Fix conflicts (merge)"}),(0,mu.jsx)(Ln,{onClick:()=>t(["fix-conflict","--rebase"]),children:"Fix conflicts (rebase)"})]})}),(0,mu.jsx)(np,{children:(0,mu.jsx)(yr,{onClick:r,children:"Cancel"})})]})}var xw=F(W(),1);function Ylr({cwd:e,disabled:t,onSelect:r}){let{prs:n,loading:i}=Khe(e),[o,a]=(0,jlr.useState)(null);return i||n.length===0?null:(0,xw.jsxs)(xw.Fragment,{children:[(0,xw.jsx)(Gy,{label:"prs",disabled:t,children:s=>(0,xw.jsx)(Wlr,{cwd:e,onPick:l=>{a(l),s()}})}),o&&(0,xw.jsx)(qlr,{pr:o,onSelect:s=>{r(o,s),a(null)},onCancel:()=>a(null)})]})}var a9=F(W(),1);function Klr({onStartRun:e,cwd:t}){let r=Zle(t);return!t||r.length===0?null:(0,a9.jsx)(Gy,{label:"server",children:n=>(0,a9.jsx)(Fn,{elevation:4,sx:{...mC,left:"auto",width:200},children:(0,a9.jsx)(kf,{dense:!0,disablePadding:!0,children:r.map(i=>(0,a9.jsx)(Ln,{onMouseDown:o=>o.preventDefault(),onClick:()=>{e(i.name,t),n()},sx:{py:.75},children:(0,a9.jsx)(Ze,{sx:{fontSize:13},children:i.name})},i.name))})})})}var r3=F(W(),1);function Xlr({onCreate:e,onCreateDesign:t,onCreateHarness:r,onCreateAssist:n,onStartRun:i}){let{selectedCwd:o}=Na(),a=!o;return(0,r3.jsxs)(Qt,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:[(0,r3.jsxs)(Nlr,{disabled:a,onSelect:(s,l)=>UUt(s,o,n,()=>{},l),children:[(0,r3.jsx)(zlr,{cwd:o,disabled:a,onCreate:e,onCreateDesign:t,onCreateHarness:r}),(0,r3.jsx)(Ylr,{cwd:o,disabled:a,onSelect:(s,l)=>n([...l,String(s.number)],o,qle(s))})]}),(0,r3.jsx)(Klr,{onStartRun:i,cwd:o})]})}var Wd=F(W(),1),nIn={minHeight:48,pl:1,pr:14},iIn={width:240,ml:2};function Zlr({socket:e,selection:t}){let{collapsed:r,onToggleCollapsed:n}=DD();return(0,Wd.jsxs)(y_,{variant:"dense",disableGutters:!0,sx:nIn,children:[r&&(0,Wd.jsx)(ace,{collapsed:r,onToggleCollapsed:n}),(0,Wd.jsx)(Plr,{reconnecting:e.reconnecting}),(0,Wd.jsx)(hlr,{}),(0,Wd.jsx)(Pe,{sx:iIn,children:(0,Wd.jsx)(Dlr,{repos:t.repos,selected:t.selectedCwd,onSelect:t.setSelectedCwd})}),(0,Wd.jsxs)(Pe,{sx:{display:"flex",ml:1,mr:2},children:[(0,Wd.jsx)(Kle,{cwd:t.selectedCwd}),(0,Wd.jsx)(dlr,{cwd:t.selectedCwd})]}),(0,Wd.jsx)(Xlr,{onCreate:e.createSession,onCreateDesign:e.createDesignSession,onCreateHarness:e.createHarnessSession,onCreateAssist:e.createAssistSession,onStartRun:e.startRun}),(0,Wd.jsx)(wlr,{rateLimits:e.rateLimits})]})}var Qhe=F(_e(),1);var Qlr=F(W(),1),Jlr=bt((0,Qlr.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 ecr=F(W(),1),tcr=bt((0,ecr.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 rcr=F(W(),1),ncr=bt((0,rcr.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 OOe=F(W(),1);function icr({mode:e}){return e==="dark"?(0,OOe.jsx)(ncr,{fontSize:"small"}):(0,OOe.jsx)(tcr,{fontSize:"small"})}var ocr=F(W(),1),acr=bt((0,ocr.jsx)("path",{d:"m20.38 8.57-1.23 1.85a8 8 0 0 1-.22 7.58H5.07A8 8 0 0 1 15.58 6.85l1.85-1.23A10 10 0 0 0 3.35 19a2 2 0 0 0 1.72 1h13.85a2 2 0 0 0 1.74-1 10 10 0 0 0-.27-10.44zm-9.79 6.84a2 2 0 0 0 2.83 0l5.66-8.49-8.49 5.66a2 2 0 0 0 0 2.83"}),"Speed");var s9=F(W(),1);function scr(){let e=afe();return(0,s9.jsxs)(Ln,{onClick:()=>jKe(!e),children:[(0,s9.jsx)(p_,{children:(0,s9.jsx)(acr,{fontSize:"small"})}),(0,s9.jsx)($m,{children:e?"Hide render HUD":"Show render HUD"})]})}var gu=F(W(),1);function lcr({mode:e,onToggleColorMode:t,onRestart:r,onUpdate:n}){return[(0,gu.jsxs)(Ln,{onClick:t,children:[(0,gu.jsx)(p_,{children:(0,gu.jsx)(icr,{mode:e})}),(0,gu.jsx)($m,{children:"Toggle dark mode"})]},"color-mode"),(0,gu.jsx)(scr,{},"render-hud"),(0,gu.jsx)(ea,{},"restart-divider"),(0,gu.jsxs)(Ln,{onClick:r,children:[(0,gu.jsx)(p_,{children:(0,gu.jsx)(Nle,{fontSize:"small"})}),(0,gu.jsx)($m,{children:r9.label})]},"restart"),(0,gu.jsxs)(Ln,{onClick:n,children:[(0,gu.jsx)(p_,{children:(0,gu.jsx)(Jlr,{fontSize:"small"})}),(0,gu.jsx)($m,{children:"Update assist"})]},"update")]}var n3=F(W(),1);function ccr({reconnecting:e,onClose:t}){let{pending:r,error:n,clearError:i,restart:o}=n9(r9.target,e);return(0,n3.jsxs)(n3.Fragment,{children:[(0,n3.jsx)(ia,{title:r9.label,message:r9.message,confirmLabel:"Restart",busy:r,onConfirm:()=>{o()},onCancel:t}),(0,n3.jsx)(vh,{error:n,onClose:i})]})}var fcr=F(W(),1);function ucr({onConfirm:e,onClose:t}){return(0,fcr.jsx)(ia,{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 i3=F(W(),1);function hcr({restarting:e,reconnecting:t,onCloseRestart:r,updating:n,onCloseUpdate:i}){let{launchAssist:o,armUpdateReload:a}=Bf();return(0,i3.jsxs)(i3.Fragment,{children:[e&&(0,i3.jsx)(ccr,{reconnecting:t,onClose:r}),n&&(0,i3.jsx)(ucr,{onConfirm:()=>{a(),o(["update"])},onClose:i})]})}var dcr=F(W(),1),pcr=bt((0,dcr.jsx)("path",{d:"M3 18h18v-2H3zm0-5h18v-2H3zm0-7v2h18V6z"}),"Menu");var mcr=F(W(),1),gcr=bt((0,mcr.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 Xhe=F(W(),1);function ycr(){let e=wo();return(0,Xhe.jsx)(nn,{title:"Config",children:(0,Xhe.jsx)(mr,{size:"small",sx:{color:"inherit"},"aria-label":"Config",onClick:()=>e("/config"),children:(0,Xhe.jsx)(gcr,{fontSize:"small"})})})}var NOe=F(W(),1),vcr=bt([(0,NOe.jsx)("path",{d:"M12 5.99 19.53 19H4.47zM12 2 1 21h22z"},"0"),(0,NOe.jsx)("path",{d:"M13 16h-2v2h2zm0-6h-2v5h2z"},"1")],"WarningAmber");var zG="0.672.0";var Zhe=F(_e(),1),BOe=(0,Zhe.createContext)(null);function bcr(){return(0,Zhe.useContext)(BOe)}var Tw=F(W(),1);function xcr(){let e=bcr();return zG?(0,Tw.jsxs)(Tw.Fragment,{children:[(0,Tw.jsxs)(Ze,{variant:"caption",sx:{opacity:.4,userSelect:"none",lineHeight:1},children:["v",zG]}),e&&e!==zG&&(0,Tw.jsx)(nn,{title:`Daemon is running v${e}, but this page was served by v${zG}. Restart the daemon to match.`,children:(0,Tw.jsx)(vcr,{fontSize:"small",color:"warning","aria-label":"Version mismatch"})})]}):null}var o3=F(W(),1);function Tcr({open:e,onOpen:t}){return(0,o3.jsxs)(Pe,{sx:{position:"fixed",top:8,right:16,zIndex:r=>r.zIndex.drawer+2,display:"flex",alignItems:"center",gap:.5,color:"inherit"},children:[(0,o3.jsx)(xcr,{}),(0,o3.jsx)(ycr,{}),(0,o3.jsx)(mr,{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,o3.jsx)(pcr,{fontSize:"small"})})]})}var Sw=F(W(),1);function Scr({mode:e,toggle:t,reconnecting:r}){let[n,i]=(0,Qhe.useState)(null),[o,a]=(0,Qhe.useState)(!1),[s,l]=(0,Qhe.useState)(!1),u=!!n,f=()=>i(null);return(0,Sw.jsxs)(Sw.Fragment,{children:[(0,Sw.jsx)(Tcr,{open:u,onOpen:i}),(0,Sw.jsx)(ap,{anchorEl:n,open:u,onClose:f,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:lcr({mode:e,onToggleColorMode:()=>{t(),f()},onRestart:()=>{f(),a(!0)},onUpdate:()=>{f(),l(!0)}})}),(0,Sw.jsx)(hcr,{restarting:o,reconnecting:r,onCloseRestart:()=>a(!1),updating:s,onCloseUpdate:()=>l(!1)})]})}var _cr=F(_e(),1);var wcr=F(W(),1);function Ccr({conflict:e,onConfirm:t,onCancel:r}){let{name:n,cwd:i,port:o}=e.existing,a=rm(i),s=o?` on port ${o}`:"",l=a?` in ${a}`:"";return(0,wcr.jsx)(ia,{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 Jhe=F(W(),1);function kcr({socket:e,children:t}){let{serverConflict:r,clearServerConflict:n,retrySession:i,stopSession:o,startRun:a,discardSession:s}=e,l=(0,_cr.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,Jhe.jsxs)(L8e.Provider,{value:l,children:[t,r&&(0,Jhe.jsx)(Ccr,{conflict:r,onConfirm:u,onCancel:n})]})}var Ecr=new Map;function Rcr(e,t){if(!VX())return;let r=Ecr.get(e);if(Ecr.set(e,t),!!r)for(let[n,i]of Object.entries(t))Object.is(i,r[n])||v0(`\u0394 ${e}.${n}`)}var tde=F(_e(),1);function Acr(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||nm(i)!==t?null:n}function l9(e,t,r){if(e)return t.find(n=>n.id===e)??r.find(n=>n.sessionId===e)}function ede(){let{pathname:e}=Cs();return e.startsWith("/backlog")||e.startsWith("/usage")}function Pcr({selectedCwd:e,selectedCardId:t,sessions:r,history:n,activeByRepo:i,onSelect:o}){let a=l9(t,r,n),s=a&&nm(a),l=!!(s&&s===e),u=Acr(i,e,r),f=(0,tde.useRef)(t),h=ede();(0,tde.useEffect)(()=>{let d=f.current!==t&&!!s;f.current=t,!(h||d||l||!u)&&o(u)},[t,s,l,u,o,h])}var a3=F(_e(),1);function Lcr(e,t,r,n){return l9(e,t,r)?.cwd||n}function Mcr(e,t){let r=new Set,n=new Set,i=[];for(let o of t){if(o.cwdMissing)continue;let a=oC(o),s=nm(o);!a||!s||r.has(a)||n.has(s)||(r.add(a),n.add(s),i.push(s))}return e&&!r.has(hle(e,t))&&!n.has(e)&&i.unshift(e),i}var Icr=F(_e(),1);function rde(e,t,r){let n=l9(e,t,r);return n&&nm(n)}function Dcr(e,t,r,n){let i=rde(e,t,r);(0,Icr.useEffect)(()=>{i&&n(i)},[i,n])}function Ocr(e,t,r,n){let[i,o]=(0,a3.useState)(e);(0,a3.useEffect)(()=>{e&&!i&&o(e)},[e,i]),Dcr(r,n,t,o);let a=(0,a3.useMemo)(()=>Mcr(e,t),[e,t]),s=Lcr(r,n,t,i);return(0,a3.useMemo)(()=>({repos:a,selectedCwd:i,worktreeCwd:s,setSelectedCwd:o}),[a,i,s])}var ide=F(_e(),1);var Cw=F(_e(),1);var Ncr=F(_e(),1),nde="assist:reloaded-after-update";function Bcr(e){(0,Ncr.useEffect)(()=>{globalThis.sessionStorage?.getItem(nde)&&(globalThis.sessionStorage.removeItem(nde),e({message:"Reloaded after updating assist",sessionId:null}))},[e])}var jg=F(_e(),1);function Fcr(e){return e.commandType==="assist"&&e.assistArgs?.[0]==="update"&&e.status==="done"}function $cr(e,t){let[r,n]=(0,jg.useState)(!1),[i,o]=(0,jg.useState)(!1),a=(0,jg.useRef)(!1),s=(0,jg.useRef)(e);s.current=e;let l=(0,jg.useRef)(new Set),u=(0,jg.useCallback)(()=>{a.current=!1,o(!1),l.current=new Set(s.current.filter(Fcr).map(f=>f.id)),n(!0)},[]);return(0,jg.useEffect)(()=>{if(!r||i)return;if(t){a.current=!0;return}if(!a.current)return;e.some(h=>Fcr(h)&&!l.current.has(h.id))&&o(!0)},[r,i,t,e]),{arm:u,completed:i}}function zcr(e,t,r,n){let{arm:i,completed:o}=$cr(e,t),a=(0,Cw.useRef)(!1),s=(0,Cw.useCallback)(()=>{globalThis.sessionStorage?.setItem(nde,"1")},[]),{error:l,restart:u}=n9("webserver",t,s);return Bcr(r),(0,Cw.useEffect)(()=>{l&&n(l)},[l,n]),(0,Cw.useEffect)(()=>{!o||a.current||(a.current=!0,u())},[o,u]),{armUpdateReload:(0,Cw.useCallback)(()=>{a.current=!1,i()},[i])}}function Ucr(e){let{armUpdateReload:t}=zcr(e.sessions,e.reconnecting,e.setSuccess,e.setError),r=(0,ide.useMemo)(()=>({launchAssist:e.createAssistSession,launchAgentInStream:e.createSessionInStream,resumeSession:e.resumeSession,armUpdateReload:t}),[e.createAssistSession,e.createSessionInStream,e.resumeSession,t]),n=wo(),i=(0,ide.useCallback)(o=>{e.selectSession(o),n("/sessions"),e.clearSuccess()},[n,e.selectSession,e.clearSuccess]);return{launch:r,viewLaunchedSession:i}}var Hcr=F(_e(),1);function Wcr(e,t,r,n){let i=rde(e,t,r);(0,Hcr.useEffect)(()=>{e&&i&&n({type:"set-active",cwd:i,sessionId:e})},[e,i,n])}var ode=F(_e(),1);function Vcr(e,t){let r=(0,ode.useRef)(new Map);(0,ode.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 qcr=F(_e(),1);function Gcr(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 jcr(e,t){return(0,qcr.useCallback)(r=>{let n=e.current;n?.readyState===WebSocket.OPEN&&n.send(JSON.stringify(r));let i=Gcr(r);i&&t(i)},[e,t])}var h1=F(_e(),1);function Ycr(e){return(t,r)=>e({type:"create",prompt:t||void 0,cwd:r,auto:!0})}function Kcr(e){return(t,r)=>e({type:"create",prompt:t||void 0,cwd:r,design:!0})}function Xcr(e){return(t,r,n)=>e({type:"create",prompt:r||void 0,cwd:n,harness:t})}function Zcr(e){return(t,r,n)=>e({type:"create-assist",assistArgs:t,cwd:r,...n})}function Qcr(e){return(t,r,n,i)=>e({type:"resume",sessionId:t,cwd:r,name:n,harness:i})}function Jcr(e,t){return(r,n)=>{t.delete(r),e({type:"retry",sessionId:r,replace:n})}}function eur(e,t){return r=>{t.delete(r),e({type:"restart",sessionId:r})}}function tur(e,t){return r=>{e({type:"dismiss",sessionId:r}),t.delete(r)}}function rur(e,t){return r=>{e({type:"discard",sessionId:r}),t.delete(r)}}function nur(e){return t=>e({type:"stop",sessionId:t})}function iur(e){return(t,r,n,i)=>e({type:"create-run",runName:t,cwd:r,replace:n,launchedFrom:i})}function our(e){return(t,r)=>e({type:"set-autorun",sessionId:t,enabled:r})}function aur(e){return(t,r)=>e({type:"set-autoadvance",sessionId:t,enabled:r})}function sur(e){return(t,r)=>e({type:"set-starred",sessionId:t,starred:r})}function lur(e){return(t,r)=>e({type:"input",sessionId:t,data:r})}function cur(e){return(t,r,n)=>e({type:"resize",sessionId:t,cols:r,rows:n})}function uur(e,t){return(r,n)=>{let i=e.get(r);return i&&n(i),t.set(r,n),()=>t.delete(r)}}function fur(e){return(t,r,n,i)=>e({type:"pr-decision",sessionId:t,requestId:r,decision:n,...i})}var s3=F(_e(),1);function hur(e){return(t,r,n)=>e({type:"create",prompt:r||void 0,cwd:n,joinSessionId:t,auto:!0})}function dur(e){return{createSession:(0,s3.useMemo)(()=>Ycr(e),[e]),createSessionInStream:(0,s3.useMemo)(()=>hur(e),[e]),createDesignSession:(0,s3.useMemo)(()=>Kcr(e),[e]),createHarnessSession:(0,s3.useMemo)(()=>Xcr(e),[e]),createAssistSession:(0,s3.useMemo)(()=>Zcr(e),[e]),resumeSession:(0,s3.useMemo)(()=>Qcr(e),[e])}}var UG=F(_e(),1);function pur(e,t){let r=(0,UG.useCallback)((a,s)=>{Jcr(e,t.current)(a,s)},[e,t]),n=(0,UG.useCallback)(a=>{eur(e,t.current)(a)},[e,t]),i=(0,UG.useCallback)(a=>{tur(e,t.current)(a)},[e,t]),o=(0,UG.useCallback)(a=>{rur(e,t.current)(a)},[e,t]);return{retrySession:r,restartSession:n,dismissSession:i,discardSession:o}}function mur(e,t,r){let n={...dur(e),sendInput:(0,h1.useMemo)(()=>lur(e),[e]),sendResize:(0,h1.useMemo)(()=>cur(e),[e]),sendPrDecision:(0,h1.useMemo)(()=>fur(e),[e]),setAutoRun:(0,h1.useMemo)(()=>our(e),[e]),setAutoAdvance:(0,h1.useMemo)(()=>aur(e),[e]),setStarred:(0,h1.useMemo)(()=>sur(e),[e]),stopSession:(0,h1.useMemo)(()=>nur(e),[e]),startRun:(0,h1.useMemo)(()=>iur(e),[e])},i=(0,h1.useMemo)(()=>uur(t.current,r.current),[t,r]);return{...n,...pur(e,t),onOutput:i}}var ade=F(_e(),1);function gur(e,t,r){let n=(0,ade.useCallback)(a=>{r(a),e({type:"fetch-transcript",sessionId:a})},[e,r]),i=(0,ade.useCallback)(()=>{r(null)},[r]),o=(0,ade.useCallback)(a=>{r(null),t(a)},[t,r]);return{viewTranscript:n,clearTranscript:i,selectSession:o}}var $x=F(_e(),1);function yur(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 bur=F(_e(),1);function vur(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 xur(e,t,r){let n=ede();(0,bur.useEffect)(()=>{if(n){t(null);return}t(i=>vur(e,i,r))},[e,t,r,n])}var FOe=F(_e(),1);function Tur(){let[e,t]=(0,FOe.useState)({}),[r,n]=(0,FOe.useState)(null);return{activeByRepo:e,setActiveByRepo:t,daemonVersion:r,setDaemonVersion:n}}var l3=F(_e(),1);function Sur(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 Cur(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 wur(){let[e,t]=(0,l3.useState)(new Set),r=(0,l3.useRef)(new Map),n=(0,l3.useCallback)(o=>{t(a=>a.has(o)?a:new Set(a).add(o))},[]),i=(0,l3.useCallback)(o=>{let a=Cur(r.current,o);r.current=new Map(o.map(s=>[s.id,s.startedAt])),a.length&&t(s=>Sur(s,a))},[]);return{initialized:e,markInitialized:n,syncSessions:i}}var ww=F(_e(),1);function _ur(){let[e,t]=(0,ww.useState)(null),[r,n]=(0,ww.useState)(null),[i,o]=(0,ww.useState)(null),a=(0,ww.useCallback)(()=>t(null),[]),s=(0,ww.useCallback)(()=>n(null),[]),l=(0,ww.useCallback)(()=>o(null),[]);return{error:e,setError:t,clearError:a,success:r,setSuccess:n,clearSuccess:s,serverConflict:i,setServerConflict:o,clearServerConflict:l}}var d1=F(_e(),1);function kur(e,t){return[...e,{...t,windows:fC(t.cwd),status:"launching"}]}function sde(e){return e.find(t=>t.status==="launching")}function Eur(e){let t=sde(e);return t?e.filter(r=>r.id!==t.id):e}function Rur(e,t){let r=sde(e);return r?$Oe(e,r.id,t):e}function $Oe(e,t,r){return e.map(n=>n.id===t&&n.status==="launching"?{...n,status:"error",error:r}:n)}function Aur(e,t){return e.filter(r=>r.id!==t)}var Pur=F(_e(),1);var oIn=6e4,aIn="Launch timed out \u2014 the session did not start.";function Lur(e,t){(0,Pur.useEffect)(()=>{let r=e.filter(i=>i.status==="launching");if(r.length===0)return;let n=r.map(i=>setTimeout(()=>t(o=>$Oe(o,i.id,aIn)),Math.max(0,oIn-(Date.now()-i.startedAt))));return()=>n.forEach(clearTimeout)},[e,t])}function Mur(){let[e,t]=(0,d1.useState)([]),r=(0,d1.useRef)([]),n=(0,d1.useCallback)(l=>{r.current=l(r.current),t(r.current)},[]),i=(0,d1.useCallback)(l=>{n(u=>kur(u,{id:crypto.randomUUID(),startedAt:Date.now(),...l}))},[n]),o=(0,d1.useCallback)(()=>{let l=sde(r.current);return n(Eur),l?.named?l.title:void 0},[n]),a=(0,d1.useCallback)(l=>n(u=>Rur(u,l)),[n]),s=(0,d1.useCallback)(l=>n(u=>Aur(u,l)),[n]);return Lur(e,n),{pendingLaunches:e,addPendingLaunch:i,resolvePendingLaunch:o,failPendingLaunch:a,dismissPendingLaunch:s}}var Iur=F(_e(),1);function Dur(e,t){return(0,Iur.useCallback)(r=>{e(r),t(r)},[e,t])}var zOe=F(_e(),1);function Our(){let[e,t]=(0,zOe.useState)(null),[r,n]=(0,zOe.useState)(null);return{transcript:e,setTranscript:t,viewingTranscriptSessionId:r,setViewingTranscriptSessionId:n}}var _w=F(_e(),1);function Nur(e,t){let r=e.sessionId;t.buffers.current?.delete(r),t.handlers.current?.get(r)?.("\x1Bc")}function Bur(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 Fur(e,t){let r=e.message;t.setError(r),t.failPendingLaunch(r)}function $ur(e,t){t.setSuccess({message:e.message,sessionId:null})}function zur(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 Uur(e,t){t.setServerConflict({existing:e.existing,runName:e.runName,cwd:e.cwd,sessionId:e.sessionId,launchedFrom:e.launchedFrom})}function Hur(e,t){let r=e.sessions;t.setSessions(r),e.cwd&&t.setCurrentCwd(e.cwd),t.setActiveByRepo(e.active??{})}function Wur(e,t){switch(e.type){case"sessions":Hur(e,t);break;case"created":Bur(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":Fur(e,t);break;case"notice":$ur(e,t);break;case"run-conflict":Uur(e,t);break;case"limits":t.setRateLimits(e.rateLimits);break;case"clear":Nur(e,t);break;case"output":zur(e,t);break}}function Vur(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=>{Wur(JSON.parse(i.data),e)},n.onclose=()=>t.onClose?.(),n}function Gur(e,t,r,n){let i=!1,o,a=0,s=!1,l=()=>{i||t(Vur(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 qur(e){let t=(0,_w.useRef)(null),[r,n]=(0,_w.useState)(!1),{handleSessions:i,markInitialized:o,buffers:a,handlers:s}=e;(0,_w.useEffect)(()=>{let u=()=>{a.current?.clear();let h=s.current;if(h)for(let d of h.values())d("\x1Bc")},f=Gur({...e,setSessions:i},h=>{t.current=h},u,n);return()=>{f(),t.current?.close()}},[i,o,a,s]);let l=(0,_w.useCallback)(()=>{let u=t.current;u?.readyState===WebSocket.OPEN&&u.send(JSON.stringify({type:"history"}))},[]);return{wsRef:t,requestHistory:l,reconnecting:r}}function jur(){let[e,t]=(0,$x.useState)([]),[r,n]=(0,$x.useState)([]),[i,o]=(0,$x.useState)(null),a=Tur(),s=Our(),[l,u]=(0,$x.useState)(""),f=_ur(),h=Mur(),[d,p]=(0,$x.useState)(null),{initialized:m,markInitialized:g,syncSessions:y}=wur(),v=(0,$x.useRef)(new Map),b=(0,$x.useRef)(new Map),x=Dur(y,t),{wsRef:C,requestHistory:S,reconnecting:w}=qur({handleSessions:x,setHistory:n,setActiveId:o,...a,...s,setCurrentCwd:u,...f,...h,setRateLimits:p,markInitialized:g,buffers:v,handlers:b});return xur(e,o,yur(a.activeByRepo,e)),{sessions:e,history:r,activeId:i,setActiveId:o,...a,...s,currentCwd:l,...f,...h,rateLimits:d,initialized:m,wsRef:C,buffers:v,handlers:b,requestHistory:S,reconnecting:w}}function Yur(){let e=jur(),{wsRef:t,buffers:r,handlers:n,addPendingLaunch:i,activeId:o,sessions:a}=e,s=jcr(t,i),l=mur(s,r,n);Wcr(o,a,e.history,s),Vcr(a,s);let u=gur(s,e.setActiveId,e.setViewingTranscriptSessionId);return{...e,...l,...u}}var c9=F(_e(),1);var Kur="assist:sidebar-collapsed";function Xur(){let[e,t]=(0,c9.useState)(()=>hm(Kur).length>0),r=(0,c9.useCallback)(()=>{t(n=>{let i=!n;return dm(Kur,i?[!0]:[]),i})},[]);return(0,c9.useMemo)(()=>({collapsed:e,onToggleCollapsed:r}),[e,r])}var lde=F(_e(),1);function Zur(){let[e,t]=(0,lde.useState)(!0);return(0,lde.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 Qur(){let e=Yur(),t=sfe(e),r=Ocr(e.currentCwd,e.history,t,e.sessions);Pcr({selectedCwd:r.selectedCwd,selectedCardId:t,sessions:e.sessions,history:e.history,activeByRepo:e.activeByRepo,onSelect:e.selectSession});let{launch:n,viewLaunchedSession:i}=Ucr(e),o=Zur(),a=Xur();return Rcr("shell",{...e,selection:r,launch:n,topBar:o,sidebarCollapse:a}),{socket:e,selection:r,launch:n,viewLaunchedSession:i,topBar:o,sidebarCollapse:a}}var kh=F(W(),1),sIn={zIndex:e=>e.zIndex.drawer+1},lIn={minHeight:48};function Jur({mode:e,toggle:t}){let{socket:r,selection:n,launch:i,viewLaunchedSession:o,topBar:a,sidebarCollapse:s}=Qur();return(0,kh.jsx)(C8e.Provider,{value:a,children:(0,kh.jsx)(X8e.Provider,{value:s,children:(0,kh.jsx)(eF.Provider,{value:n,children:(0,kh.jsxs)(f1e.Provider,{value:i,children:[(0,kh.jsx)(BOe.Provider,{value:r.daemonVersion,children:(0,kh.jsx)(Scr,{mode:e,toggle:t,reconnecting:r.reconnecting})}),(0,kh.jsx)(Ppe,{position:"fixed",elevation:1,sx:sIn,children:(0,kh.jsx)(Zlr,{socket:r,selection:n})}),(0,kh.jsx)(y_,{variant:"dense",sx:lIn}),(0,kh.jsx)(kcr,{socket:r,children:(0,kh.jsx)(Xsr,{socket:r})}),(0,kh.jsx)(flr,{socket:r,onViewLaunchedSession:o})]})})})})}var efr=F(_e(),1);function tfr(){let[e,t]=(0,efr.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 kw=F(W(),1),cIn={MuiButtonBase:{styleOverrides:{root:{cursor:"pointer","&.Mui-disabled":{cursor:"default"}}}},MuiLink:{styleOverrides:{root:{cursor:"pointer"}}}};function uIn(){let{mode:e,toggle:t}=tfr(),r=(0,nfr.useMemo)(()=>e0({palette:{mode:e,...e==="dark"&&{background:{default:"#1e1e1e",paper:"#252526"}}},components:cIn}),[e]);return(0,kw.jsxs)(Kq,{theme:r,children:[(0,kw.jsx)(Fj,{}),(0,kw.jsx)(Jur,{mode:e,toggle:t})]})}var fIn=r1e([{path:"*",element:(0,kw.jsx)(uIn,{})}]);function hIn(){return(0,kw.jsx)(Yye,{router:fIn})}var rfr=document.getElementById("app");rfr&&(0,ifr.createRoot)(rfr).render((0,kw.jsx)(hIn,{}));})();
3974
3974
  /*! Bundled license information:
3975
3975
 
3976
3976
  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.670.0",
9
+ version: "0.672.0",
10
10
  type: "module",
11
11
  main: "dist/index.js",
12
12
  bin: {
@@ -33694,7 +33694,12 @@ async function previewSlackThreadParts({
33694
33694
  console.log(
33695
33695
  `Approved for ${target}. The ${bodies.length} bodies to post, in thread order, are at:`
33696
33696
  );
33697
- for (const path91 of paths) console.log(path91);
33697
+ paths.forEach(
33698
+ (path91, index3) => console.log(`${index3 + 1}/${paths.length} ${path91}`)
33699
+ );
33700
+ console.log(
33701
+ threadTs ? `Post every part as a reply with thread_ts ${threadTs}.` : `Post 1/${paths.length} to ${channel}, then the rest with the thread_ts it returns.`
33702
+ );
33698
33703
  }
33699
33704
 
33700
33705
  // src/commands/slack/postSlackMessage.ts
@@ -33748,7 +33753,7 @@ function registerSlack(program2) {
33748
33753
  parseSlackThreadRef
33749
33754
  ).addHelpText(
33750
33755
  "after",
33751
- "\nThe command does not post: Slack is reachable only over MCP, so it previews the message and hands the approved body back for /slack-post to send.\nIn an assist web session the body is previewed for approve/reject first (with inline comments). On approval the body is written to a working file under ~/.assist/slack/ and its path printed on the last line, preceded by the resolved thread_ts when --thread was given. On rejection nothing is handed back: the command exits non-zero with the reason and any inline comments, leaving the previewed markdown in the working file to revise in place.\n--parts takes the files holding one thread's messages in thread order, each getting its own working file (channel-1.md, channel-2.md, \u2026) and its own preview pane titled with its position in the batch (2/3). The panes pop in sequence and no path is printed until every part is approved; the first rejection halts the batch and exits non-zero naming that part's position, reason, inline comments and working file, with no path handed back. A missing or empty part file, or --parts with --body, is an error before any pane opens.\nOutside a web session there is no preview and the body passes straight through.\nslack_send_message accepts standard markdown as it is \u2014 bold, italic, code, blockquotes, lists, links, code blocks, tables and headers \u2014 capped at 5000 characters."
33756
+ "\nThe command does not post: Slack is reachable only over MCP, so it previews the message and hands the approved body back for /slack-post to send.\nIn an assist web session the body is previewed for approve/reject first (with inline comments). On approval the body is written to a working file under ~/.assist/slack/ and its path printed on the last line, preceded by the resolved thread_ts when --thread was given. On rejection nothing is handed back: the command exits non-zero with the reason and any inline comments, leaving the previewed markdown in the working file to revise in place.\n--parts takes the files holding one thread's messages in thread order, each getting its own working file (channel-1.md, channel-2.md, \u2026) and its own preview pane titled with its position in the batch (2/3). The panes pop in sequence and no path is printed until every part is approved, at which point each path prints prefixed with its position (1/3) under a line naming the target, followed by how to thread them: without --thread part 1 opens the thread and the rest carry the thread_ts it returns, with --thread every part is a reply under the resolved thread_ts. The first rejection halts the batch and exits non-zero naming that part's position, reason, inline comments and working file, with no path handed back. A missing or empty part file, or --parts with --body, is an error before any pane opens.\nOutside a web session there is no preview and the body passes straight through.\nslack_send_message accepts standard markdown as it is \u2014 bold, italic, code, blockquotes, lists, links, code blocks, tables and headers \u2014 capped at 5000 characters."
33752
33757
  ).action(
33753
33758
  async (channel, options2) => {
33754
33759
  await postSlackMessage(channel, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staff0rd/assist",
3
- "version": "0.670.0",
3
+ "version": "0.672.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "bin": {