From 6f5da7d83930795098f1b160dadc2f2087ddf614 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 16 Oct 2026 16:00:51 +0000 Subject: [PATCH] fix(web): skip unchanged transcript rows while a live message streams Streaming updates were rebuilding every history row. Cache each entry's rendered rows and keep those elements memoized so only the live message commits again. Co-authored-by: tt-a1i --- tests/web/transcript-live-row-render.spec.ts | 240 +++++++++++++++ web/dist/app.js | 43 +-- web/ui/src/features/transcript/Transcript.tsx | 274 +++++++++++++++++- 3 files changed, 530 insertions(+), 27 deletions(-) create mode 100644 tests/web/transcript-live-row-render.spec.ts diff --git a/tests/web/transcript-live-row-render.spec.ts b/tests/web/transcript-live-row-render.spec.ts new file mode 100644 index 000000000..8516f2dd8 --- /dev/null +++ b/tests/web/transcript-live-row-render.spec.ts @@ -0,0 +1,240 @@ +// @vitest-environment jsdom + +import { cleanup, render } from "@testing-library/react"; +import { createElement } from "react"; +import { I18nextProvider } from "react-i18next"; +import { afterEach, expect, it } from "vitest"; +import type { WebLiveMessage, WebSnapshot } from "../../web/protocol/types.ts"; +import { + observeTranscriptRowRenders, + Transcript, +} from "../../web/ui/src/features/transcript/Transcript.tsx"; +import { i18n } from "../../web/ui/src/i18n.ts"; + +afterEach(() => { + cleanup(); + observeTranscriptRowRenders(undefined); +}); + +const truncation = { + bytes: 0, + maxBytes: 1024, + messagesTruncated: 0, + messagePartsOmitted: 0, + entriesOmitted: 0, + modelsOmitted: 0, + sessionsOmitted: 0, + workspacesOmitted: 0, + truncated: false, +}; + +const onResend = async () => true; + +function historyMessage( + id: string, + content: string, +): NonNullable["entries"][number] { + const message: WebLiveMessage = { + role: "assistant", + timestamp: Number(id.slice(1)), + content, + stopReason: "stop", + parts: [{ type: "text", text: content }], + }; + return { + id, + parentId: null, + type: "message", + timestamp: "2026-10-16T00:00:00Z", + message, + }; +} + +function snapshot( + entries: NonNullable["entries"], +): WebSnapshot { + return { + protocolVersion: 1, + preferences: { theme: "system" }, + generatedAt: "2026-10-16T00:00:00Z", + cursor: 1, + currentSessionId: "s", + currentSessionPath: "/s.jsonl", + workspaces: [], + sessions: [], + models: [], + truncation, + runtime: { status: "running", capabilities: {} }, + selectedSession: { + id: "s", + path: "/s.jsonl", + cwd: "/", + entries, + bytes: 0, + truncation, + }, + }; +} + +function transcript(state: WebSnapshot, live: string) { + return createElement( + I18nextProvider, + { i18n }, + createElement(Transcript, { + snapshot: state, + liveMessages: [ + { + key: "live-current", + message: { + role: "assistant", + content: live, + parts: [{ type: "text", text: live }], + }, + }, + ], + liveRunning: true, + livePhase: "running", + liveRetry: null, + thinkingStarts: {}, + thinkingDurations: {}, + scrollToBottom: 0, + onResend, + }), + ); +} + +it("keeps history text, selection anchors, and findable copy while a live token updates only the live row", () => { + const entries = [ + historyMessage("e0", "HISTORY_0"), + historyMessage("e1", "HISTORY_1"), + historyMessage("e2", "HISTORY_FIND_ME"), + ]; + const state = snapshot(entries); + const seen: string[] = []; + observeTranscriptRowRenders((key) => { + seen.push(key); + }); + const view = render(transcript(state, "LIVE_0")); + const historyAnchor = view.container.querySelector( + '[data-history-entry="e0-text-0"]', + ); + expect(historyAnchor?.textContent).toContain("HISTORY_0"); + expect(view.container.textContent).toContain("HISTORY_FIND_ME"); + expect(view.container.textContent).toContain("LIVE_0"); + seen.length = 0; + + view.rerender(transcript(state, "LIVE_1")); + + expect(view.container.textContent).toContain("HISTORY_0"); + expect(view.container.textContent).toContain("HISTORY_1"); + expect(view.container.textContent).toContain("HISTORY_FIND_ME"); + expect(view.container.textContent).toContain("LIVE_1"); + expect(view.container.textContent).not.toContain("LIVE_0"); + expect(view.container.querySelector('[data-history-entry="e0-text-0"]')).toBe( + historyAnchor, + ); + expect(seen.filter((key) => key.startsWith("e"))).toEqual([]); + expect(seen.some((key) => key.startsWith("live-current"))).toBe(true); +}); + +it("re-renders only the history row whose message changed", () => { + const kept = historyMessage("e0", "HISTORY_KEEP"); + const edited = historyMessage("e1", "HISTORY_OLD"); + const after = historyMessage("e2", "HISTORY_AFTER"); + const first = snapshot([kept, edited, after]); + const seen: string[] = []; + observeTranscriptRowRenders((key) => { + seen.push(key); + }); + const view = render(transcript(first, "LIVE_0")); + seen.length = 0; + const replacement = historyMessage("e1", "HISTORY_NEW"); + view.rerender( + transcript( + { + ...first, + selectedSession: { + ...first.selectedSession!, + entries: [kept, replacement, after], + }, + }, + "LIVE_0", + ), + ); + expect(view.container.textContent).toContain("HISTORY_KEEP"); + expect(view.container.textContent).toContain("HISTORY_NEW"); + expect(view.container.textContent).toContain("HISTORY_AFTER"); + expect(view.container.textContent).not.toContain("HISTORY_OLD"); + expect(seen.filter((key) => key.startsWith("e0"))).toEqual([]); + expect(seen.filter((key) => key.startsWith("e2"))).toEqual([]); + expect(seen.some((key) => key.startsWith("e1"))).toBe(true); +}); + +it("shows a newly arrived tool result on its call row without re-rendering unrelated history", () => { + const kept = historyMessage("e0", "HISTORY_KEEP"); + const call = historyMessage("e1", ""); + call.message = { + role: "assistant", + timestamp: 1, + content: "", + parts: [ + { + type: "toolCall", + id: "call-1", + name: "read", + arguments: '{"path":"a.ts"}', + }, + ], + }; + const state = snapshot([kept, call]); + const seen: string[] = []; + observeTranscriptRowRenders((key) => { + seen.push(key); + }); + const view = render(transcript(state, "LIVE_0")); + expect(view.container.textContent).toContain("HISTORY_KEEP"); + expect(view.container.textContent).not.toContain("RESULT_BODY"); + seen.length = 0; + + view.rerender( + createElement( + I18nextProvider, + { i18n }, + createElement(Transcript, { + snapshot: state, + liveMessages: [ + { + key: "live-current", + message: { + role: "assistant", + content: "LIVE_0", + parts: [{ type: "text", text: "LIVE_0" }], + }, + }, + { + key: "live-result", + message: { + role: "toolResult", + toolCallId: "call-1", + toolName: "read", + content: "RESULT_BODY", + isError: false, + }, + }, + ], + liveRunning: true, + livePhase: "running", + liveRetry: null, + thinkingStarts: {}, + thinkingDurations: {}, + scrollToBottom: 0, + onResend, + }), + ), + ); + + expect(view.container.textContent).toContain("HISTORY_KEEP"); + expect(view.container.textContent).toContain("RESULT_BODY"); + expect(seen.filter((key) => key.startsWith("e0"))).toEqual([]); + expect(seen.some((key) => key.startsWith("e1"))).toBe(true); +}); diff --git a/web/dist/app.js b/web/dist/app.js index cbbb16d62..1d7930c9a 100644 --- a/web/dist/app.js +++ b/web/dist/app.js @@ -109,33 +109,34 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho `),S=`${e.id}:${x}`,C=s?.source===S?s.status:null,w=`${e.id}:diff:${u.diff}`,T=s?.source===w?s.status:null,E=u.output.split(` `).map((e,t)=>({text:e,number:u.offset+t})),D=u.diff?HL(u.diff):[],O=D.filter(e=>e.kind===`added`).length,k=D.filter(e=>e.kind===`removed`).length,A=u.diff||u.change===`created`?(0,K.jsxs)(`span`,{className:`evidence-summary-meta`,title:o(`toolDiffStatsHelp`),children:[(0,K.jsxs)(`span`,{className:`review-additions`,children:[`+`,O.toLocaleString()]}),(0,K.jsxs)(`span`,{className:`review-deletions`,children:[`−`,k.toLocaleString()]}),u.truncated&&(0,K.jsx)(`span`,{children:o(`gitReviewPartialLabel`)})]}):null,j=u.tests?.failures.map((e,t)=>({text:e,number:t+1}))??[];return(0,K.jsxs)(`details`,{className:`tool-evidence-card evidence-${u.kind}`,"data-state":d,"data-tool":e.name,open:a||void 0,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(`span`,{className:`evidence-icon`,"aria-hidden":`true`,children:(0,K.jsx)(v,{})}),(0,K.jsx)(`span`,{className:`tool-kind`,"aria-hidden":`true`,title:e.name,children:tL(e.name)}),(0,K.jsxs)(`span`,{className:`evidence-target`,title:u.path||y,children:[(0,K.jsx)(`span`,{className:`tool-action`,children:d===`returned`&&u.change===`created`?o(`toolFileChange_created`):eL(o,e.name,d)}),m?(0,K.jsx)(`span`,{className:`evidence-filename`,children:g}):y?(0,K.jsx)(`span`,{className:`evidence-command`,children:y}):null]}),A,(0,K.jsx)(ee,{className:`evidence-chevron`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`evidence-status`,children:f})]}),(0,K.jsxs)(`div`,{className:`evidence-content`,children:[u.path&&!u.diff&&(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:o(`toolRequestedFile`)}),` `,l&&p?(0,K.jsx)(`button`,{className:`artifact-link`,type:`button`,onClick:()=>l.open(p),children:(0,K.jsx)(`code`,{children:p})}):(0,K.jsx)(`code`,{children:p}),i&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`br`,{}),(0,K.jsxs)(`small`,{children:[o(`toolWorkspace`),`: `,i]})]})]}),b&&(0,K.jsxs)(`figure`,{className:`evidence-shell`,"aria-label":o(`toolCallOutput`),children:[(0,K.jsxs)(`figcaption`,{children:[(0,K.jsx)(`span`,{children:`Shell`}),(0,K.jsx)(`button`,{type:`button`,"aria-label":o(C===`copiedCode`?`copiedCode`:`copyCode`),title:o(C===`copiedCode`?`copiedCode`:`copyCode`),onClick:async()=>{let e=await wd(x);c({source:S,status:e?`copiedCode`:`copyCodeFailed`})},children:C===`copiedCode`?(0,K.jsx)(I,{}):(0,K.jsx)(oe,{})})]}),(0,K.jsx)(`pre`,{children:x||o(`noOutput`)}),(0,K.jsxs)(`div`,{className:`evidence-process-meta`,children:[f,u.exitCode===void 0?u.signal?` · ${u.signal}`:``:` · exit ${u.exitCode}`]}),C===`copyCodeFailed`&&(0,K.jsx)(`p`,{role:`status`,className:`evidence-warning`,children:o(C)})]}),u.truncated&&(0,K.jsx)(`p`,{className:`evidence-warning`,children:o(`toolPartialEvidence`)}),u.change&&!u.diff&&(0,K.jsx)(`p`,{children:o(`toolFileChange_${u.change}`)}),u.kind===`change`&&!u.diff&&!u.change&&(0,K.jsx)(`p`,{children:u.evidenceUnavailable??o(`toolChangeUnavailable`)}),u.tests&&(0,K.jsxs)(`figure`,{"aria-label":`Test evidence`,children:[(0,K.jsx)(`figcaption`,{children:(0,K.jsx)(`strong`,{children:o(`toolTestResults`,{format:u.tests.format})})}),(0,K.jsx)(`p`,{children:o(`toolTestCounts`,u.tests)}),(0,K.jsx)(`p`,{children:o(`toolTestCountsHelp`)}),j.map(e=>(0,K.jsx)(UL,{"aria-label":`Failure excerpt ${e.number}`,children:e.text},e.number))]}),b?null:u.diff?(0,K.jsxs)(`figure`,{className:`evidence-diff`,"aria-label":`Change diff`,children:[(0,K.jsxs)(`figcaption`,{children:[l&&p?(0,K.jsx)(`button`,{className:`evidence-diff-file`,type:`button`,title:p,"aria-label":p,onClick:()=>l.open(p),children:g}):(0,K.jsx)(`span`,{className:`evidence-diff-file`,title:p,children:g}),A,(0,K.jsx)(`button`,{className:`evidence-copy`,type:`button`,"aria-label":o(T===`copiedCode`?`copiedCode`:`copyCode`),title:o(T===`copiedCode`?`copiedCode`:`copyCode`),onClick:async()=>{let e=await wd(u.diff??``);c({source:w,status:e?`copiedCode`:`copyCodeFailed`})},children:T===`copiedCode`?(0,K.jsx)(I,{}):(0,K.jsx)(oe,{})})]}),(0,K.jsx)(`pre`,{className:`evidence-diff-lines`,children:D.map(e=>(0,K.jsxs)(`span`,{className:`evidence-diff-row diff-${e.kind}`,children:[(0,K.jsx)(`span`,{className:`evidence-line-number`,"aria-hidden":`true`,children:e.newLine??e.oldLine??``}),(0,K.jsx)(`span`,{className:`evidence-diff-marker`,children:e.marker}),(0,K.jsx)(`span`,{children:e.code}),` `]},e.id))}),T===`copyCodeFailed`&&(0,K.jsx)(`p`,{role:`status`,className:`evidence-warning`,children:o(T)})]}):u.numberLines?(0,K.jsx)(UL,{className:`evidence-lines`,"aria-label":`File content`,children:E.map(e=>(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`span`,{className:`evidence-line-number`,"aria-hidden":`true`,children:e.number}),e.text,` -`]},e.number))}):(0,K.jsx)(UL,{className:`evidence-log`,"aria-label":`Tool output`,children:u.output||o(`noOutput`)}),u.kind===`file`&&u.truncated&&(0,K.jsx)(`p`,{children:o(`toolReadMore`)}),u.recovery&&(0,K.jsxs)(`p`,{children:[o(`toolFullOutputReference`),` `,(0,K.jsx)(`code`,{children:u.recovery})]}),u.readRecovery&&(0,K.jsx)(`p`,{className:`evidence-warning`,children:u.readRecovery}),(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{children:o(`toolRawEvidence`)}),(0,K.jsx)(`p`,{children:(0,K.jsx)(`code`,{children:e.name})}),(0,K.jsx)(`p`,{children:(0,K.jsx)(`strong`,{children:o(`toolCallArguments`)})}),(0,K.jsx)(`pre`,{children:u.rawArguments}),(0,K.jsx)(`p`,{children:(0,K.jsx)(`strong`,{children:o(`toolCallOutput`)})}),(0,K.jsx)(`pre`,{children:u.rawResult})]})]})]})}function GL({changes:e,onReview:t}){let{t:n}=cr(),[r,i]=(0,_.useState)(!1),a=(0,_.useId)();if(e.state===`unavailable`||e.files.length===0)return null;let o=e.state===`partial`,s=e.source===`file-tools`,c=e.fileCount===null,l=r?e.files:e.files.slice(0,3);return(0,K.jsxs)(`section`,{className:`turn-changes`,"aria-label":n(`turnChangesReview`),children:[(0,K.jsxs)(`header`,{className:`turn-changes-header`,children:[(0,K.jsx)(`span`,{className:`turn-changes-icon`,"aria-hidden":`true`,children:(0,K.jsx)(ye,{})}),(0,K.jsxs)(`div`,{className:`turn-changes-summary`,children:[(0,K.jsx)(`strong`,{title:n(s?`turnEditsScope`:`turnChangesScope`),children:n(s?c?`turnEditsPartial`:`turnEdits`:o?`turnChangesPartial`:`turnChanges`,{count:e.fileCount??e.files.length})}),!c&&!e.files.some(e=>e.binary||e.statsUnavailable)&&(0,K.jsxs)(`span`,{className:`turn-changes-totals`,children:[(0,K.jsxs)(`span`,{className:`review-additions`,children:[`+`,e.additions]}),(0,K.jsxs)(`span`,{className:`review-deletions`,children:[`−`,e.deletions]})]}),o&&!s&&(0,K.jsx)(`span`,{className:`turn-changes-warning`,children:n(`turnChangesIncomplete`)})]}),(0,K.jsx)(`button`,{type:`button`,className:`turn-changes-review-button`,"aria-label":n(`turnChangesReview`),disabled:!t,onClick:()=>t?.(e.promptEntryId,e.files[0]?.path),children:n(`reviewChanges`)})]}),(0,K.jsx)(`div`,{className:`turn-changes-list`,id:a,children:l.map(r=>{let i=Math.max(r.path.lastIndexOf(`/`),r.path.lastIndexOf(`\\`));return(0,K.jsxs)(`button`,{type:`button`,className:`turn-changes-file`,title:r.path,disabled:!t,onClick:()=>t?.(e.promptEntryId,r.path),children:[(0,K.jsxs)(`span`,{className:`turn-changes-path`,children:[(0,K.jsx)(`span`,{children:r.path.slice(0,i+1)}),(0,K.jsx)(`strong`,{children:r.path.slice(i+1)})]}),(0,K.jsx)(`span`,{className:`turn-changes-file-stats`,children:r.binary?(0,K.jsx)(`span`,{children:n(`gitReviewBinaryShort`)}):r.statsUnavailable?(0,K.jsx)(`span`,{title:n(`turnEditReason_${r.statsUnavailable}`),children:n(`turnEditStatsUnknown`)}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`span`,{className:`review-additions`,children:[`+`,r.additions]}),(0,K.jsxs)(`span`,{className:`review-deletions`,children:[`−`,r.deletions]})]})})]},r.path)})}),e.files.length>3&&(0,K.jsxs)(`button`,{type:`button`,className:`turn-changes-more`,"aria-expanded":r,"aria-controls":a,onClick:()=>i(e=>!e),children:[n(r?`turnChangesLess`:`turnChangesMore`,{count:e.files.length-3}),(0,K.jsx)(L,{className:r?`up`:``,"aria-hidden":`true`})]})]})}function KL({item:e,position:t,current:n,onNavigate:r,onPreview:i}){let{t:a}=cr(),o=(0,_.useRef)(()=>{}),s=yd({placement:`start`,delay:150,hideDelay:100,touchTrigger:`none`,onShow:(0,_.useCallback)(()=>i(e.entryId,()=>o.current()),[e.entryId,i])});return o.current=s.hide,(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{ref:s.ref,className:`turn-tick`,type:`button`,"data-turn-entry":e.entryId,"aria-label":a(`conversationTurnPosition`,{position:t}),"aria-describedby":s.describedBy,"aria-current":n?`location`:void 0,onClick:()=>{s.hide(),r(e.entryId)},children:(0,K.jsx)(`span`,{className:`turn-tick-mark`,"aria-hidden":`true`})}),s.renderHoverCard((0,K.jsx)(`span`,{className:`turn-preview`,children:e.previewState===`idle`||e.previewState===`loading`?(0,K.jsx)(`span`,{role:`status`,children:a(`turnPreviewLoading`)}):e.previewState===`unavailable`?(0,K.jsx)(`span`,{role:`status`,children:a(`turnPreviewUnavailable`)}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{className:`turn-preview-prompt`,children:e.title}),e.reply&&(0,K.jsx)(`span`,{className:`turn-preview-reply`,children:e.reply})]})}),{className:`turn-preview-layer`})]})}function qL({items:e,viewport:t,onNavigate:n,readingHistory:r,onRequestPreview:i,enabled:a=!0,onHidden:o}){let{t:s}=cr(),c=(0,_.useRef)(null),l=JSON.stringify(e.map(e=>e.entryId)),u=(0,_.useRef)(null),d=(0,_.useRef)(null),f=(0,_.useRef)(!1),p=(0,_.useRef)(0),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)({top:0,height:0,visible:!1,current:[]}),y=(0,_.useCallback)(()=>{u.current?.hide(),u.current=null,d.current&&d.current.captureTarget.hasPointerCapture?.(d.current.pointerId)&&d.current.captureTarget.releasePointerCapture(d.current.pointerId),d.current=null,p.current++,o?.()},[o]),b=(0,_.useCallback)((e,n)=>{if(!a||!t.current||!c.current||c.current.style.visibility===`hidden`||t.current.checkVisibility?.()===!1||c.current.checkVisibility?.()===!1||getComputedStyle(t.current).display===`none`||getComputedStyle(c.current).display===`none`){n();return}u.current?.entryId!==e&&u.current?.hide(),u.current={entryId:e,hide:n},i?.(e)},[a,t,i]),x=(0,_.useCallback)((e,t=!1)=>{u.current?.hide();let r=++p.current;h(!1),Promise.resolve(n(e,t)).then(e=>{p.current===r&&e===!1&&h(!0)})},[n]);return(0,_.useLayoutEffect)(()=>{let e=t.current,n=e?.parentElement,i=JSON.parse(l);if(!e||!n){y();return}let o,s=r?n.querySelector(`.jump-to-latest`):null,u=()=>{o=void 0;let t=e.getBoundingClientRect(),r=n.getBoundingClientRect(),l=new Map;for(let t of e.querySelectorAll(`[data-history-entry]`)){let e=t.dataset.historyEntry;e&&!l.has(e)&&l.set(e,t)}let u=e.querySelector(`.conversation-turn`)??l.values().next().value,d=e.offsetWidth>0?t.width/e.offsetWidth:1,f=a&&t.height>0&&d>0&&!!u&&(t.right-u.getBoundingClientRect().right)/d>=48&&e.checkVisibility?.()!==!1&&getComputedStyle(e).display!==`none`&&(!c.current||getComputedStyle(c.current).display!==`none`);f||y();let p=s?.getBoundingClientRect(),m=Math.min(t.bottom-8,p&&p.height>0?p.top-12:1/0),h=Math.max(0,m-t.top-8),g=i.flatMap(e=>{let n=l.get(e);if(!n)return[];let r=(n.closest(`.conversation-turn`)??n).getBoundingClientRect();return r.bottom>t.top+16&&r.tope.top===_.top&&e.height===_.height&&e.visible===f&&e.current.join(`\0`)===g.join(`\0`)?e:_)},d=()=>{o===void 0&&(o=requestAnimationFrame(u))};u(),e.addEventListener(`scroll`,d),window.addEventListener(`resize`,d);let f=typeof ResizeObserver>`u`?void 0:new ResizeObserver(d);f?.observe(e),f?.observe(n),s&&f?.observe(s);for(let t of e.children)f?.observe(t);let p=new MutationObserver(d);return p.observe(e,{childList:!0,subtree:!0}),()=>{o!==void 0&&cancelAnimationFrame(o),e.removeEventListener(`scroll`,d),window.removeEventListener(`resize`,d),f?.disconnect(),p.disconnect()}},[l,t,r,a,y]),(0,_.useLayoutEffect)(()=>{if(g.height,!g.visible||d.current)return;let e=c.current,t=Array.from(e?.querySelectorAll(`[data-turn-entry]`)??[]),n=t.find(e=>e===document.activeElement)??t.find(e=>e.matches(`:hover`))??t.find(e=>g.current.includes(e.dataset.turnEntry??``));if(!e||!n)return;let r=e.getBoundingClientRect(),i=n.getBoundingClientRect();i.topr.bottom&&(e.scrollTop+=i.bottom-r.bottom)},[g.current,g.height,g.visible,l]),(0,_.useLayoutEffect)(()=>{let n=t.current;if(!n)return;let r=t=>{if(!a||t.defaultPrevented||t.isComposing||!t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||![`ArrowUp`,`ArrowDown`].includes(t.key)||!n.parentElement?.contains(document.activeElement)||n.checkVisibility?.()===!1||getComputedStyle(n).display===`none`||getComputedStyle(n).visibility===`hidden`||n.getBoundingClientRect().height<=0)return;let r=new Map;for(let e of n.querySelectorAll(`[data-history-entry]`)){let t=e.dataset.historyEntry;t&&!r.has(t)&&r.set(t,e)}let i=e.flatMap((e,t)=>{let n=r.get(e.entryId);return n?[{item:e,index:t,top:n.getBoundingClientRect().top}]:[]}),o=n.getBoundingClientRect().top,s;if(t.key===`ArrowDown`){let t=i.findIndex(e=>e.top>o+24);s=i.length===0?e[0]:t<0?e[i.at(-1).index+1]:e[(i[t-1]?.index??-1)+1]}else{for(let t=i.length-1;t>=0;t--){let n=i[t];if(Math.abs(n.top-o)<=24){s=e[n.index-1];break}if(n.tope.top>o+24)&&(s=i[0]?.item),i.length===0&&(s=e.at(-1))}s&&(t.preventDefault(),x(s.entryId))};return document.addEventListener(`keydown`,r),()=>document.removeEventListener(`keydown`,r)},[t,a,e,x]),(0,_.useLayoutEffect)(()=>()=>y(),[y]),e.length<4?null:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`nav`,{ref:c,className:`turn-rail`,"aria-label":s(`conversationTurns`),style:{top:g.top,maxHeight:g.height,visibility:g.visible?`visible`:`hidden`},onClickCapture:e=>{f.current&&=(e.preventDefault(),e.stopPropagation(),!1)},onPointerDown:e=>{if(!e.isPrimary||e.button!==0)return;let t=e.target instanceof Element?e.target.closest(`.turn-tick`):null;!t||!e.currentTarget.contains(t)||(f.current=!1,d.current={pointerId:e.pointerId,captureTarget:t,y:e.clientY,moved:!1},t.setPointerCapture?.(e.pointerId))},onPointerMove:e=>{let t=d.current;if(!t||t.pointerId!==e.pointerId||Math.abs(e.clientY-t.y)<3&&!t.moved)return;t.moved=!0,f.current=!0;let n=Array.from(e.currentTarget.querySelectorAll(`[data-turn-entry]`)).find(t=>{let n=t.getBoundingClientRect();return e.clientY>=n.top&&e.clientY{let t=d.current;d.current=null,t?.captureTarget.hasPointerCapture?.(e.pointerId)&&t.captureTarget.releasePointerCapture(e.pointerId)},onPointerCancel:e=>{let t=d.current;d.current=null,t?.captureTarget.hasPointerCapture?.(e.pointerId)&&t.captureTarget.releasePointerCapture(e.pointerId),f.current=!1},children:e.map((e,t)=>(0,K.jsx)(KL,{item:e,position:t+1,current:g.current.includes(e.entryId),onNavigate:x,onPreview:b},e.entryId))}),m&&(0,K.jsx)(`span`,{className:`turn-navigation-error`,role:`status`,children:s(`turnPreviewUnavailable`)})]})}function JL({message:e,sessionId:t,path:n,entryId:r}){let{t:i}=cr(),[a,o]=(0,_.useState)(null),s=JSON.stringify([t,n,r]),c=e.parts?.filter(e=>e.type===`image`)??[];if(c.length===0)return null;let l=new Map,u=a?.scope===s?a:null,d=()=>o(e=>e?{...e,open:!1}:null);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`section`,{className:`message-attachments`,"aria-label":i(`imageAttachments`),children:c.map(e=>{let a=`${e.mimeType}:${e.name??``}:${e.previewUrl??``}`,c=l.get(a)??0;l.set(a,c+1);let u=`${a}:${c}`,d=t&&n&&r&&typeof e.sourcePartIndex==`number`&&Number.isSafeInteger(e.sourcePartIndex)&&e.sourcePartIndex>=0?{id:`${r}:${e.sourcePartIndex}`,entryId:r,partIndex:e.sourcePartIndex,kind:`image`,name:e.name??i(`attachedImage`)}:null,f=e.previewUrl?(0,K.jsx)(`img`,{src:e.previewUrl,alt:e.name??i(`attachedImage`)},`preview`):d&&t&&n?(0,K.jsx)(`span`,{className:`message-attachment-preview`,children:(0,K.jsx)(PI,{sessionId:t,path:n,source:d,thumbnail:!0})},`preview`):(0,K.jsx)(Ne,{"aria-hidden":`true`},`preview`),p=(0,K.jsx)(`span`,{children:e.name??i(`attachedImage`)},`name`);return d?(0,K.jsxs)(`button`,{className:`message-attachment`,type:`button`,title:d.name,"aria-label":d.name,onClick:()=>o({scope:s,source:d,open:!0}),children:[f,p]},u):(0,K.jsxs)(`div`,{className:`message-attachment`,children:[f,p]},u)})}),t&&n&&u&&(0,K.jsx)(II,{sessionId:t,path:n,source:u.source,open:u.open,onSelect:d,onClose:d})]})}function YL(e,t,n){let r=(0,_.useMemo)(()=>new rf,[]),i=e?.history?.leafEntryId??e?.entries.at(-1)?.id,a=e?.id,o=e?.path,s=JSON.stringify([e?.id,e?.path,i]),c=(0,_.useRef)(s);c.current=s;let[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)({}),p=(0,_.useRef)(new Map),m=(0,_.useMemo)(()=>a&&o&&i?{sessionId:a,sessionPath:o,entryId:i}:null,[a,o,i]);(0,_.useEffect)(()=>{if(u(null),f({}),!n||!m)return;let e=new AbortController,t=async()=>{try{let t=null,n=[],i=new Set;for(let a=0;a<10;a++){let a=await r.sessionPromptHistory(m,t,e.signal);if(e.signal.aborted||c.current!==s||a.sessionId!==m.sessionId||a.sessionPath!==m.sessionPath||a.anchorEntryId!==m.entryId||a.requestedBeforeEntryId!==t||a.entryIds.length>100||a.entryIds.some(e=>!e||i.has(e))||new Set(a.entryIds).size!==a.entryIds.length||a.nextBeforeEntryId!==null&&(a.entryIds.length===0||a.nextBeforeEntryId!==a.entryIds[0]))return;for(let e of a.entryIds)i.add(e);if(n=[...a.entryIds,...n],a.nextBeforeEntryId===null){u({scope:s,ids:n});return}t=a.nextBeforeEntryId}}catch{}},i=typeof window.requestIdleCallback==`function`?window.requestIdleCallback(()=>void t(),{timeout:2e3}):void 0,a=i===void 0?window.setTimeout(()=>void t(),0):void 0;return()=>{e.abort(),i!==void 0&&window.cancelIdleCallback(i),a!==void 0&&window.clearTimeout(a);for(let e of p.current.values())e.abort();p.current.clear()}},[s,n,m,r]);let h=(0,_.useMemo)(()=>{let e=new Map(t.map(e=>[e.entryId,e]));if(l?.scope!==s)return t;let n=new Set(l.ids);return[...l.ids.map(t=>e.get(t)??d[t]??{entryId:t,title:``,previewState:`idle`}),...t.filter(e=>!n.has(e.entryId))]},[l,s,t,d]),g=(0,_.useRef)(h);return g.current=h,{items:h,requestPreview:(0,_.useCallback)(e=>{if(!n||!m||c.current!==s||p.current.has(e))return;let t=g.current.find(t=>t.entryId===e);if(!t||t.previewState===void 0||t.previewState===`ready`)return;let i=new AbortController;p.current.set(e,i),f(t=>({...t,[e]:{entryId:e,title:``,previewState:`loading`}})),r.sessionPromptPreview(m,e,i.signal).then(t=>{if(!(i.signal.aborted||c.current!==s)){if(t.sessionId!==m.sessionId||t.sessionPath!==m.sessionPath||t.anchorEntryId!==m.entryId||t.entryId!==e||typeof t.prompt!=`string`||typeof t.response!=`string`||Array.from(t.prompt).length>240||Array.from(t.response).length>240)throw Error(`Unverified preview`);f(n=>({...n,[e]:{entryId:e,title:t.prompt,reply:t.response,previewState:`ready`}}))}}).catch(()=>{!i.signal.aborted&&c.current===s&&f(t=>({...t,[e]:{entryId:e,title:``,previewState:`unavailable`}}))}).finally(()=>{p.current.get(e)===i&&p.current.delete(e)})},[n,m,s,r])}}var XL=1e3,ZL=Wd*4;function QL(e,t){return t.history?.leafEntryId===e.validatedLeaf||t.history?.anchorEntryId===e.anchor&&t.history.anchorOnBranch===!0}function $L(e,t,n=t.entriesOmitted){let r=e.filter(e=>e.message?.truncation).length,i=e.reduce((e,t)=>e+(t.message?.truncation?.partsOmitted??0),0);return{...t,entriesOmitted:n,messagesTruncated:r,messagePartsOmitted:i,truncated:n>0||r>0||i>0}}function eR(e,t){let n=t.history?.leafEntryId??null;if(n===e.validatedLeaf)return e;let r=t.entries.findIndex(t=>t.id===e.anchor),i=r>=0?t.entries.slice(r+1):t.entries[0]?.parentId===e.anchor?t.entries:null,a=i?.reduce((e,t)=>e+Kd(t)+1,0)??0;return i&&e.session.entries.length+i.length<=XL&&e.session.bytes+a<=ZL?{...e,anchor:n??e.anchor,validatedLeaf:n,session:{...e.session,entries:[...e.session.entries,...i],bytes:e.session.bytes+a,truncation:$L([...e.session.entries,...i],e.session.truncation)}}:{...e,validatedLeaf:n}}function tR(e,t,n,r){let i=(0,_.useMemo)(()=>new rf,[]),a=(0,_.useMemo)(()=>n??new Map,[n]),o=_L(e),s=(0,_.useRef)({scope:o,state:a.get(o)});s.current.scope!==o&&(s.current={scope:o,state:a.get(o)});let c=(0,_.useRef)({selected:e,callbacks:t});c.current={selected:e,callbacks:t};let l=(0,_.useRef)(s.current.state?.window??null),u=(0,_.useRef)(null),d=(0,_.useRef)(null),f=(0,_.useRef)(null),[p,m]=(0,_.useState)(l.current),[h,g]=(0,_.useState)(!1),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(0),S=(0,_.useRef)(o),C=(0,_.useRef)(null),w=r?JSON.stringify([r.sessionId,r.sessionPath,r.entryId,r.revision]):null,T=r&&e&&w!==C.current&&r.sessionId===e.id&&r.sessionPath===e.path&&r.session.id===e.id&&r.session.path===e.path&&r.session.history?.anchorEntryId===r.entryId&&r.session.history.anchorOnBranch===!0&&r.session.entries.some(e=>e.id===r.entryId)?{session:r.session,anchor:r.session.entries.at(-1).id,validatedLeaf:r.session.history?.leafEntryId??null}:null,E=(0,_.useCallback)(e=>{l.current=e,vL(a,_L(e.session),{window:e}),m(e),c.current.callbacks.onAnchorChange?.({sessionId:e.session.id,sessionPath:e.session.path,entryId:e.anchor})},[a]),D=(0,_.useCallback)((e=!1)=>{u.current?.controller.abort(),u.current=null,d.current=null,a.delete(_L(l.current?.session??c.current.selected)),l.current=null,a.persist?.(),m(null),g(!1),y(e?`historyChanged`:null),f.current=null,c.current.callbacks.onAnchorChange?.(null),x(e=>e+1)},[a]),O=(0,_.useCallback)((e=!1)=>{let t=l.current,n=c.current.selected;if(!t||!n)return;let r=JSON.stringify([_L(n),t.anchor,n.history?.leafEntryId]);if(!e&&f.current===r)return;f.current=r,y(null);let i=()=>{f.current===r&&l.current===t&&(u.current?.controller.abort(),u.current=null,g(!1),y(`historyValidationUnavailable`))};c.current.callbacks.onAnchorChange?.({sessionId:t.session.id,sessionPath:t.session.path,entryId:t.anchor});let a=c.current.callbacks.onRefresh?.();if(!a){i();return}a.then(e=>{e||i()}).catch(i)},[]),k=(0,_.useCallback)(e=>{let t=l.current,n=c.current.selected;if(!e.page||!e.consuming||u.current!==e||e.controller.signal.aborted||!t||!n||e.scope!==_L(n)||t.session.history?.beforeEntryId!==e.before||!QL(t,n))return;let r=e.page,i=new Set(t.session.entries.map(e=>e.id)),a=[...r.entries.filter(e=>!i.has(e.id)),...t.session.entries],o=Kd(a);for(;a.length>XL||o>ZL;){let e=a.pop();if(!e)break;o-=Kd(e)+ +!!a.length}c.current.callbacks.beforePrepend(),E({...t,anchor:a.at(-1)?.id??t.anchor,session:{...t.session,entries:a,bytes:o,truncation:$L(a,t.session.truncation,r.truncation.entriesOmitted),history:{...t.session.history,beforeEntryId:r.history?.beforeEntryId??null}}}),u.current=null,g(!1),y(null)},[E]);(0,_.useLayoutEffect)(()=>{if(T&&w!==C.current){S.current=o,u.current?.controller.abort(),u.current=null,d.current=null,f.current=null,g(!1),y(null),C.current=w,E(T);return}S.current!==o&&(S.current=o,u.current?.controller.abort(),u.current=null,d.current=null,l.current=s.current.state?.window??null,m(l.current),g(!1),y(null),f.current=null,x(e=>e+1),l.current||c.current.callbacks.onAnchorChange?.(null));let t=u.current;t&&!t.consuming&&e&&!QL(t.source,e)&&(t.controller.abort(),u.current=null);let n=l.current;if(!(!n||!e)){if(e.history?.anchorEntryId===n.anchor&&e.history.anchorOnBranch===!1){D(!0),c.current.callbacks.onRefresh?.();return}if(!QL(n,e)){O();return}y(e=>e===`historyValidationUnavailable`?null:e),(e.history?.leafEntryId??null)!==n.validatedLeaf&&(n=eR(n,e),E(n)),u.current?.page&&k(u.current)}},[o,e,D,O,E,k,T,w]),(0,_.useLayoutEffect)(()=>{let e=l.current;return e&&(vL(a,o,{...s.current.state,window:e}),c.current.callbacks.onAnchorChange?.({sessionId:e.session.id,sessionPath:e.session.path,entryId:e.anchor})),()=>{u.current?.controller.abort(),u.current=null,d.current=null,c.current.callbacks.onAnchorChange?.(null)}},[o,a]);let A=(0,_.useCallback)(()=>{let e=c.current.selected;return!l.current&&e?.history?.leafEntryId&&E({session:e,anchor:e.history.leafEntryId,validatedLeaf:e.history.leafEntryId}),l.current},[E]),j=(0,_.useCallback)((e,t)=>{let n=c.current.selected;if(!n||u.current)return;let r=e.session.history?.beforeEntryId;if(!r)return;let a={controller:new AbortController,scope:_L(n),before:r,source:e,consuming:t,anchor:{sessionId:n.id,sessionPath:n.path,entryId:e.anchor}};return u.current=a,t&&(g(!0),y(null)),a.done=(async()=>{try{let e=await i.sessionHistory(a.anchor,r,a.controller.signal);if(u.current!==a||a.controller.signal.aborted||a.scope!==_L(c.current.selected))return;if(e.id!==n.id||e.path!==n.path||e.anchorEntryId!==a.anchor.entryId||e.requestedBeforeEntryId!==r||e.history?.anchorEntryId!==a.anchor.entryId||e.history.anchorOnBranch!==!0)throw new tf(`Session history identity changed`,409,`SESSION_HISTORY_CHANGED`);a.page=e,a.consuming&&(k(a),u.current===a&&O())}catch(e){if(u.current!==a||a.controller.signal.aborted||(u.current=null,!a.consuming))return;g(!1),e instanceof tf&&e.code===`SESSION_HISTORY_CHANGED`?(D(!0),c.current.callbacks.onRefresh?.()):y(`historyUnavailable`)}})(),a.done},[k,D,i,O]),M=(0,_.useCallback)(async()=>{let e=c.current.selected;if(!e?.history?.leafEntryId)return;let t=l.current;if(t&&!QL(t,e)){O(!0);return}if(t||=A(),!t)return;let n=u.current;if(n){if(n.scope===_L(e)&&n.before===t.session.history?.beforeEntryId&&QL(n.source,e))return n.consuming=!0,g(!0),y(null),n.page&&k(n),n.done;n.controller.abort(),u.current=null}return j(t,!0)},[k,j,O,A]);(0,_.useEffect)(()=>{if(!t.preload){let e=u.current;e&&!e.consuming&&(e.controller.abort(),u.current=null,d.current=null);return}if(v||u.current||!e||p!==l.current)return;let n=p;if(n&&!QL(n,e))return;let r=n??(e.history?.leafEntryId?{session:e,anchor:e.history.leafEntryId,validatedLeaf:e.history.leafEntryId}:null);if(!r?.session.history?.beforeEntryId)return;let i=JSON.stringify([o,n?r.anchor:`initial`,n?r.session.history.beforeEntryId:null]);d.current!==i&&(d.current=i,j(r,!1))},[t.preload,v,o,e,p,j]);let N=p&&_L(p.session)===o?p:null,P=T??(N&&e&&QL(N,e)?eR(N,e):N),F=(0,_.useCallback)(()=>D(),[D]),I=!!(P&&e&&!QL(P,e));return{session:P?.session??e,engaged:!!P,hasMore:!!(P?.session??e)?.history?.beforeEntryId,hasNewer:!!(P&&P.anchor!==e?.history?.leafEntryId),verifying:I,loading:h,error:v,reset:b,retainReading:A,loadOlder:M,resetToLatest:F}}function nR(e){return e&&typeof e==`object`?e:{}}function rR(e){try{return nR(JSON.parse(e))}catch{return{}}}function iR(e){return e===`running`?`running`:e===`done`||e===`completed`?`done`:[`error`,`failed`,`aborted`,`killed`,`timed_out`].includes(String(e))?`error`:e===`uncertain`?`warn`:`unknown`}function aR(e,t){if(e?.forkSnapshotToolResult)return`unknown`;if(t===`running`)return`running`;if(t===`unknown`||!e)return`unknown`;if(e.isError)return`error`;let n=iR(nR(e.details).status);return n===`unknown`?e.isError===!1?`done`:`unknown`:n}function oR({status:e}){let{t}=cr();return e===`running`?(0,K.jsx)(`span`,{className:`status-mark running`,role:`img`,"aria-label":t(`toolState_running`),children:(0,K.jsx)(`i`,{})}):e===`done`?(0,K.jsx)(I,{className:`status-mark done`,"aria-label":t(`execution_done`)}):e===`error`?(0,K.jsx)(Lt,{className:`status-mark error`,"aria-label":t(`toolState_failed`)}):e===`warn`?(0,K.jsx)(`span`,{className:`status-mark warn`,role:`img`,"aria-label":t(`toolState_unknown`),children:`?`}):null}function sR({label:e,message:t,children:n}){return(0,K.jsxs)(`div`,{className:`execution-error`,role:`alert`,"aria-label":e,children:[(0,K.jsx)(V,{"aria-hidden":`true`}),(0,K.jsxs)(`div`,{className:`execution-error-content`,children:[(0,K.jsx)(`p`,{children:t}),n]})]})}function cR({failed:e,error:t,retryPrompt:n,retryEntryId:r,canRetry:i,onRetry:a}){let{t:o}=cr(),[s,c]=(0,_.useState)(!1);return e?(0,K.jsx)(sR,{label:o(`modelRequestFailed`),message:t||o(`modelFailureUnknown`),children:n!==void 0&&r&&(0,K.jsx)(`div`,{className:`provider-outcome-actions`,children:(0,K.jsxs)(`button`,{type:`button`,disabled:!i||s,onClick:()=>{c(!0),a(n,r).finally(()=>c(!1))},children:[(0,K.jsx)(ft,{"aria-hidden":`true`}),o(s?`retryingPrompt`:`retryPrompt`)]})})}):(0,K.jsx)(`div`,{className:`provider-outcome aborted`,role:`status`,children:o(`modelRequestStopped`)})}function lR({attempts:e,state:t,retry:n,observed:r=!0}){let{t:i}=cr(),a=t===`retrying`&&!r,o=n?.attempt,s=n?.maxAttempts,c=typeof o==`number`&&Number.isSafeInteger(o)&&o>0&&typeof s==`number`&&Number.isSafeInteger(s)&&s>=o,l=e.length>0||!!n?.errorMessage,u=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Pt,{"aria-hidden":`true`}),(0,K.jsxs)(`span`,{role:t===`retrying`?`status`:void 0,children:[i(a?`modelReconnectUnknown`:t===`recovered`?`modelRequestRecovered`:t===`retrying`?n?`modelReconnecting`:`modelEarlierAttempts`:t===`interrupted`?`modelRequestStopped`:`modelEarlierAttempts`),t===`retrying`&&c&&` ${o}/${s}`]}),t!==`retrying`&&(0,K.jsx)(`span`,{children:i(`modelFailedAttempts`,{count:e.length})}),l&&(0,K.jsx)(ee,{className:`reconnect-chevron`,"aria-hidden":`true`})]}),d=`provider-attempts ${t}${a?` unavailable`:``}`;return l?(0,K.jsxs)(`details`,{className:d,children:[(0,K.jsx)(`summary`,{children:u}),(0,K.jsxs)(`ol`,{children:[e.length===0&&(0,K.jsx)(`li`,{children:(0,K.jsx)(`p`,{children:n?.errorMessage})}),e.map(({entry:e,content:t})=>(0,K.jsxs)(`li`,{"data-history-entry":e.entryId??e.key,children:[(0,K.jsx)(`p`,{children:e.message.errorMessage||i(`modelFailureUnknown`)}),t?.map(e=>(0,K.jsx)(_.Fragment,{children:e.content},e.key))]},e.key))]})]}):(0,K.jsx)(`div`,{className:d,children:u})}function uR(e,t){let n=new Set,r=new Map,i=[],a=-1,o=(o,s=!1,c=!1)=>{if(i.length>0){let l=e[a]?.message.stopReason,u=o?.outcome===`cancelled`||l===`aborted`,d=l===`error`&&!u&&!(s&&t)&&!c;d&&n.add(a);let f=d?i.slice(0,-1):i,p=f.at(-1);p!==void 0&&r.set(p,{attempts:f.map(t=>e[t]),state:u?`interrupted`:l===`stop`||l===`length`||l===`toolUse`?`recovered`:s&&t?`retrying`:`earlier`})}i=[],a=-1};return e.forEach((e,t)=>{e.optimistic||(e.timing?o(e.timing):e.forkSnapshotBoundary?o(void 0,!1,!0):e.message.role===`user`||e.message.role===`custom`&&e.message.customType===`openpi-setup-request`?o():e.message.role===`assistant`&&(a=t,e.message.stopReason===`error`&&i.push(t)))}),o(void 0,!0),{finalErrors:n,groups:r}}function dR(e,t){return ej(nL(e,t).split(` -`).find(Boolean),120)}function fR(e){let t=e.split(` -`).map(e=>e.trim()).find(Boolean);return t?ej(t.replace(/^#{1,6}\s+/u,``).replace(/^>\s*/u,``).replace(/[*_~`]+/gu,``).replace(/\[([^\]]+)\]\([^)]*\)/gu,`$1`).trim(),600):``}function pR({body:e,icon:t,name:n,status:r,summary:i,output:a,evidenceState:o,note:s,rawDetails:c,snapshotMissingResult:l=!1,defaultOpen:u=!1}){let{t:d}=cr(),[f,p]=(0,_.useState)(u);(0,_.useEffect)(()=>p(u),[u]);let m=o??(r===`done`?`returned`:r===`error`?`failed`:r===`running`?`running`:`unknown`);return(0,K.jsxs)(`details`,{className:`message-details tool-line ${r}`,"data-tool":n,open:f,onToggle:e=>p(e.currentTarget.open),children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(`span`,{className:`tool-icon`,"aria-hidden":`true`,children:t}),(0,K.jsx)(`span`,{className:`tool-kind`,"aria-hidden":$I(n).action!==`call`,title:n,children:tL(n)}),(0,K.jsxs)(`span`,{className:`details-title`,children:[(0,K.jsx)(`span`,{className:`tool-action`,children:eL(d,n,m)}),i&&(0,K.jsx)(`span`,{className:`tool-summary`,children:i})]}),l&&(0,K.jsx)(`span`,{className:`evidence-status`,children:d(`toolSnapshotMissingResult`)}),(0,K.jsx)(ee,{className:`tool-disclosure`,"aria-hidden":`true`}),(0,K.jsx)(oR,{status:r})]}),s&&(0,K.jsx)(`p`,{className:`evidence-note`,children:s}),a===void 0?(0,K.jsx)(`pre`,{className:`details-body tool-evidence`,children:Fd(e).text}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`figure`,{"aria-label":d(`toolCallArguments`),style:{margin:0},children:(0,K.jsx)(`pre`,{className:`details-body tool-evidence`,children:Fd(e).text})}),(0,K.jsx)(`figure`,{"aria-label":d(`toolCallOutput`),style:{margin:0},children:(0,K.jsx)(`pre`,{className:`details-body tool-evidence`,children:Fd(a).text||d(`noOutput`)})})]}),c!==void 0&&(0,K.jsxs)(`details`,{className:`evidence-raw`,children:[(0,K.jsx)(`summary`,{children:d(`toolRawEvidence`)}),(0,K.jsx)(`pre`,{children:Fd(JSON.stringify(c,null,2)).text})]})]})}function mR({body:e,family:t,meta:n,status:r,title:i,defaultOpen:a=!1}){return(0,K.jsxs)(`details`,{className:`message-details activity-card ${t}`,open:a||void 0,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(`span`,{className:`activity-icon`,"aria-hidden":`true`,children:t===`subagent`?(0,K.jsx)(M,{}):(0,K.jsx)(Ft,{})}),(0,K.jsxs)(`span`,{className:`activity-main`,children:[(0,K.jsx)(`span`,{className:`activity-title`,children:i}),n&&(0,K.jsx)(`span`,{className:`activity-meta`,children:n})]}),(0,K.jsx)(oR,{status:r}),(0,K.jsx)(ee,{className:`tool-disclosure`,"aria-hidden":`true`})]}),(0,K.jsx)(`pre`,{className:`details-body tool-evidence`,children:e})]})}function hR(e,t,n={sessionId:``}){if(t?.forkSnapshotToolResult)return null;let{sessionId:r,subagents:i=[],records:a=[],workflows:o=[],onInspectSubagent:s,liveState:c,defaultOpen:l=!1,observed:u=!0}=n,d=e.name||``,f=rR(e.arguments),p=nR(t?.details),m=aR(t,c),h=!u&&m===`running`?`unknown`:m;if(d===`subagent_spawn`)return(0,K.jsx)(gR,{sessionId:r,id:typeof p.id==`string`?p.id:void 0,title:String(p.title||f.name||`subagent`),body:t?.content||String(f.prompt||e.arguments),activity:i.find(e=>e.id===p.id),saved:a.find(e=>e.id===p.id),spawnFailed:t?.isError===!0,observed:u,defaultOpen:l,onInspect:s});if(d.startsWith(`subagent`)){let n=d.replaceAll(`_`,` `).replace(/^subagent /u,``),r=i.find(e=>e.id===f.id)??a.find(e=>e.id===f.id);return(0,K.jsx)(mR,{family:`subagent`,defaultOpen:l,title:`${n[0]?.toUpperCase()||``}${n.slice(1)} · ${r?.title||f.id||`Subagent`}`,body:t?.content||e.arguments,status:h})}if(d===`workflow`){let n=typeof f.script==`string`?f.script:e.arguments,i=String(p.name||n.match(/\bname:\s*["'`]([^"'`]+)["'`]/u)?.[1]||`unnamed`),a=nR(p.agents),c=o.find(e=>e.runId===p.runId)?.children,l=[p.runId,p.status,a.total?`${Number(a.total)-Number(a.running||0)}/${a.total} agents`:``].filter(Boolean).join(` · `);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(mR,{family:`workflow`,title:`Workflow · ${i}`,meta:l,body:t?.content||n,status:h}),(0,K.jsx)(_R,{sessionId:r,tasks:c,observed:u,onInspect:s})]})}return d.startsWith(`workflow`)?(0,K.jsx)(mR,{family:`workflow`,title:d.replaceAll(`_`,` `),meta:String(f.runId||``),body:t?.content||e.arguments,status:h}):null}function gR({sessionId:e,id:t,title:n,body:r,activity:i,saved:a,spawnFailed:o,onInspect:s,defaultOpen:c=!1,observed:l=!0}){let{t:u}=cr(),d=i?.outcome===`interrupted`?`interrupted`:i?.status??(a?.state===`running`?void 0:a?.state),f=!l&&(d===`running`||!d&&!o)?`unknown`:d,p=u(f===`unknown`?`toolState_unknown`:f?`subagentState_${f}`:o?`subagentSpawnFailed`:t?`subagentStateUnavailable`:`subagentStarting`);return(0,K.jsxs)(`section`,{className:`activity-card subagent subagent-activity`,children:[(0,K.jsx)(TL,{identity:`${e}:${t??n}`,title:n,state:f,label:p,onInspect:t&&s?()=>s(t):void 0}),(c||o)&&(0,K.jsxs)(`details`,{className:`subagent-receipt`,open:c||void 0,children:[(0,K.jsx)(`summary`,{children:u(`subagentSpawnReceipt`)}),(0,K.jsx)(`p`,{children:u(`subagentSpawnReceiptHint`)}),(0,K.jsx)(`pre`,{className:`details-body tool-evidence`,children:r})]})]})}function _R({sessionId:e,tasks:t,observed:n,onInspect:r}){let{t:i}=cr();return(0,K.jsxs)(K.Fragment,{children:[t?.items.map(t=>{let a=t.outcome===`interrupted`?`interrupted`:!n&&t.status===`running`?`unknown`:t.status;return(0,K.jsx)(TL,{identity:`${e}:${t.id}`,title:t.title,state:a,label:i(a===`unknown`?`toolState_unknown`:`subagentState_${a}`),onInspect:r?()=>r(t.id,`workflows`):void 0},t.id)}),!!t?.omitted&&(0,K.jsx)(`p`,{className:`inspection-note`,children:i(`subagentListTruncated`,{count:t?.omitted})})]})}function vR({body:e,duration:t,status:n,level:r,defaultOpen:i,truncated:a,source:o}){let{t:s}=cr(),c=n===`running`,[l,u]=(0,_.useState)(i),[d,f]=(0,_.useState)();(0,_.useEffect)(()=>u(i),[i]);let p=t===void 0?``:nj(0,t),m=fR(e),h=[n===`unknown`?s(`toolState_unknown`):c?r?s(`thinkingActiveLevel`,{level:r}):s(`thinkingActive`):s(`thinkingDone`),p].filter(Boolean).join(` · `);return(0,K.jsxs)(`details`,{className:`message-details tool-line thinking-line ${n}`,open:l,onToggle:e=>u(e.currentTarget.open),children:[(0,K.jsxs)(`summary`,{"aria-label":[h,m].filter(Boolean).join(` · `),title:m,children:[(0,K.jsx)(`span`,{className:`tool-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Le,{})}),(0,K.jsx)(`span`,{className:`details-title`,children:(0,K.jsx)(`span`,{className:`tool-summary`,children:m||h})}),(0,K.jsx)(ee,{className:`tool-disclosure`,"aria-hidden":`true`})]}),l&&(0,K.jsx)(`div`,{className:`details-body thinking-evidence`,children:a&&o&&!c?(0,K.jsx)(FL,{...o,preview:e,markdown:!0,purpose:`thinking`,fullText:d,onComplete:f}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Sk,{children:e}),a&&(0,K.jsx)(`p`,{className:`evidence-warning`,children:s(`thinkingPreviewOnly`)})]})})]})}function yR({content:e,editable:t,copyRequiresFull:n=!1,timestamp:r,onResend:i,onRegenerate:a,onFork:o,canFork:s=!1,forkPending:c=!1}){let{t:l}=cr(),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(!1),g=(0,_.useRef)(0),v=(0,_.useRef)(void 0);(0,_.useEffect)(()=>()=>{g.current+=1,window.clearTimeout(v.current)},[]);let[y,b]=(0,_.useState)(!1),[x,S]=(0,_.useState)(e),[C,w]=(0,_.useState)(!1),T=(0,_.useRef)(null),E=(0,_.useId)();(0,_.useEffect)(()=>{y&&T.current?.focus()},[y]);let D=async()=>{if(!(C||!x.trim()||!t)){w(!0);try{await i(x.trim())&&b(!1)}finally{w(!1)}}};if(y)return(0,K.jsxs)(`div`,{className:`message-editor`,children:[(0,K.jsx)(`textarea`,{ref:T,value:x,"aria-label":l(`editMessage`),"aria-describedby":E,readOnly:C,onChange:e=>S(e.target.value),onKeyDown:e=>{e.nativeEvent.isComposing||C||(e.key===`Escape`&&b(!1),e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),D()))}}),(0,K.jsx)(`p`,{className:`message-edit-hint`,id:E,children:l(`editMessageHint`)}),(0,K.jsxs)(`div`,{className:`message-edit-actions`,children:[(0,K.jsx)(`button`,{type:`button`,disabled:C,onClick:()=>b(!1),children:l(`cancel`)}),(0,K.jsx)(`button`,{type:`button`,className:`confirm`,disabled:C||!x.trim()||!t,onClick:()=>void D(),children:l(`confirmEdit`)})]})]});let O=tj(r);return(0,K.jsxs)(`div`,{className:`message-actions${f?` copy-failed`:``}`,children:[O&&(0,K.jsx)(`time`,{dateTime:r,children:O}),o&&(0,K.jsx)(`button`,{type:`button`,"aria-label":l(`forkMessage`),title:l(c?`forkSessionPending`:s?`forkMessageHint`:`forkSessionUnavailable`),disabled:!s||c,onClick:()=>void o(),children:(0,K.jsx)(Ae,{"aria-hidden":`true`})}),t&&(0,K.jsx)(`button`,{type:`button`,"aria-label":l(`editMessage`),title:l(`editMessage`),onClick:()=>{S(e),b(!0)},children:(0,K.jsx)(at,{})}),a&&(0,K.jsx)(`button`,{type:`button`,"aria-label":l(`regenerateMessage`),title:l(`regenerateMessageHint`),disabled:!s||c,onClick:()=>void a(),children:(0,K.jsx)(ft,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{type:`button`,"aria-label":l(u?`copiedMessage`:`copyMessage`),title:l(n?`messageCopyRequiresFull`:u?`copiedMessage`:`copyMessage`),disabled:m||n,onClick:()=>{let t=++g.current;window.clearTimeout(v.current),h(!0),d(!1),p(!1),wd(e).then(e=>{t===g.current&&(h(!1),d(e),p(!e),e&&(v.current=window.setTimeout(()=>d(!1),1200)))})},children:u?(0,K.jsx)(I,{}):(0,K.jsx)(oe,{})}),f&&(0,K.jsx)(`span`,{className:`copy-error`,role:`status`,children:l(`copyFailed`)})]})}function bR({message:e,fullSubagent:t=!1,sessionId:n,onInspectSubagent:r}){let{t:i}=cr();if(e.customType===`openpi-web-command-feedback`)return(0,K.jsxs)(`div`,{className:`command-feedback`,role:`status`,children:[e.content,e.truncation?.truncated&&(0,K.jsx)(`p`,{children:i(`commandFeedbackTruncated`)})]});let a=nR(e.details);if(e.customType===`openpi-setup-request`||e.customType===`openpi-setup-closed`)return(0,K.jsx)(pR,{body:e.content,icon:(0,K.jsx)(It,{}),name:i(`configureOpenPi`),summary:e.customType===`openpi-setup-closed`?ej(e.content):void 0,status:`unknown`});if(e.customType===`subagent-result`){let o=Array.isArray(a.results)?a.results.map(nR):[a],s=new Set(aj([e]).map(e=>e.id));return(0,K.jsxs)(`section`,{className:`activity-card subagent subagent-activity`,children:[o.map(e=>{let t=typeof e.id==`string`?e.id:``,a=e.outcome===`interrupted`?`interrupted`:e.status===`done`||e.status===`error`||e.status===`running`?e.status:`unknown`;return(0,K.jsx)(TL,{identity:`${n}:${t}`,title:String(e.title||t||i(`subagentDetails`)),state:a,label:i(a===`unknown`?`unknownState`:`subagentState_${a}`),onInspect:r&&s.has(t)?()=>r(t):void 0},t||JSON.stringify(e))}),(0,K.jsxs)(`details`,{className:`subagent-result-evidence`,open:t||void 0,children:[(0,K.jsx)(`summary`,{children:i(`subagentBackgroundResult`,{count:o.length})}),(0,K.jsx)(`pre`,{className:`details-body tool-evidence`,children:!t&&typeof a.displayContent==`string`?a.displayContent:e.content})]})]})}if(e.customType===`workflow-result`){let t=Array.isArray(a.entries)?a.entries.map(nR):[],n=t.map(e=>iR(e.status)),r=n.includes(`error`)?`error`:n.includes(`warn`)?`warn`:n.length>0&&n.every(e=>e===`done`)?`done`:n.includes(`running`)?`running`:`unknown`,i=t.length?t.map(e=>`${e.status===`completed`?`✓`:`✗`} ${String(e.summary||e.runId||`run`)}${e.resultPreview?`\nResult: ${e.resultPreview}`:``}`).join(` -`):e.content;return(0,K.jsx)(mR,{family:`workflow`,title:t.length>1?`Workflow results · ${t.length} runs`:`Workflow ${String(t[0]?.runId||`result`)}`,body:i,status:r})}return null}function xR(e){return[``,`[]`,`{}`,`null`].includes(e.trim())}function SR(e){if(e.role===`toolResult`&&e.toolCallId)return`tool-result-${e.toolCallId}`;if(e.timestamp!==void 0)return`message-${e.role}-${e.timestamp}`}function CR(e){return[`assistant`,`toolResult`].includes(e.role??``)&&!e.truncation?.truncated?JSON.stringify(e):null}function wR(e){return JSON.stringify([e.role,e.content,(e.parts??[]).filter(t=>e.role!==`user`||t.type!==`text`).map(t=>t.type===`image`?[t.type,t.mimeType,e.role===`user`?void 0:t.name]:t.type),e.stopReason,e.errorMessage,e.toolCallId])}function TR(e){return e.role===`user`?wR(e):JSON.stringify({...e,timestamp:void 0})}var ER=new WeakMap;function DR(e,t){let n=ER.get(e),r=n?.get(t);if(r&&r.length===e.length&&r.head===e[0]&&r.tail===e[e.length-1])return r.projection;let i=new Map(e.map(e=>[e.id,e])),a=new Map;for(let t of e){let e=t.message&&CR(t.message);if(!e)continue;let n=a.get(e)??[];n.push(t),a.set(e,n)}let o=e.flatMap(e=>{if(e.forkSnapshotBoundary)return[{key:e.id,entryId:e.id,timestamp:e.timestamp,forkSnapshotBoundary:!0,message:{role:`custom`,content:``}}];if(e.type===`compaction`)return[{key:e.id,entryId:e.id,timestamp:e.timestamp,compaction:!0,message:{role:`custom`,content:``}}];if(`turnTiming`in e&&e.turnTiming&&e.turnTiming.sessionId===t)return[{key:e.id,timestamp:e.timestamp,timing:e.turnTiming,message:{role:`custom`,content:``}}];if(e.type!==`message`||!e.message)return[];let n=SL(e.message),r=CL(e,e=>i.get(e));return wL(e.message,r)?[]:[{key:e.id,entryId:e.id,timestamp:e.timestamp,message:n}]}),s=new Map,c=new Map;o.forEach((e,t)=>{if(e.entryId&&s.set(e.entryId,t),e.timing||e.compaction||e.forkSnapshotBoundary)return;let n=SR(e.message)??e.entryId??e.key,r=c.get(n)??[];r.push(t),c.set(n,r)});let l=new Map,u=0;for(let t of e){if(t.message?.role!==`custom`||t.message.truncation?.truncated)continue;let e=TR(t.message),n=l.get(e)??[];n.push(u),l.set(e,n),u++}let d=o.map(e=>({identity:SR(e.message),signature:TR(e.message)})),f=new Map,p=new Map;d.forEach((e,t)=>{let n=p.get(e.signature)??[];if(n.push(t),p.set(e.signature,n),e.identity===void 0)return;let r=f.get(e.identity)??[];r.push(t),f.set(e.identity,r)});let m=new Map(e.map((e,t)=>[e.id,t])),h=o.filter(e=>e.message.role===`user`).map(e=>({key:e.entryId??e.key,position:m.get(e.entryId??e.key),parentId:i.get(e.entryId??e.key)?.parentId,signature:wR(e.message)})),g=new Map;for(let e of h){let t=g.get(e.signature)??[];t.push(e),g.set(e.signature,t)}let _={nativeById:i,exactNative:a,baseEntries:o,indexById:s,lookupIndexes:c,customIndexes:l,nativeByIdentity:f,nativeByLegacySignature:p,nativeMessages:d,promptCandidates:h,promptsBySignature:g,commandInputs:new Map(o.flatMap(e=>e.message.role===`user`&&e.message.customType===`openpi-web-command-input`&&e.message.commandId?[[e.message.commandId,e.entryId??e.key]]:[])),persistedPositions:m};return n||(n=new Map,ER.set(e,n)),n.set(t,{projection:_,length:e.length,head:e[0],tail:e[e.length-1]}),_}function OR(e,t){if(!e)return-1;for(let n of e)if(!t.has(n))return n;return-1}function kR(e,t){let n=[e.timingKey,e.key,e.entryId,SR(e.message)];for(let e of n){if(!e)continue;let n=t[e];if(n!==void 0)return n}}function AR(e,t,n){let r=e.selectedSession,i=DR(r?.entries??[],r?.id);for(let e of n.keys())i.nativeById.has(e)||n.delete(e);let a=new Map;for(let e of t){if(e.optimistic)continue;let t=CR(e.message);if(!t)continue;let n=a.get(t)??[];n.push(e),a.set(t,n)}let o=new Set(n.values());for(let[e,t]of i.exactNative){let r=a.get(e);if(t.length!==1||r?.length!==1)continue;let s=t[0].id,c=r[0].key;n.has(s)||o.has(c)||i.nativeById.has(c)||(n.set(s,c),o.add(c))}let s=new Map;for(let e of t){let t=SR(e.message)??e.key,n=i.lookupIndexes.get(t);if(n)for(let t of n)s.set(t,e.key)}let c=new Set(t.flatMap(e=>e.optimistic?.projectedEntryId?[e.optimistic.projectedEntryId]:[])),l=[],u=[],d=e.selectedExecution?.sessionId===r?.id&&e.selectedExecution?.sessionPath===r?.path?e.selectedExecution:void 0,f=d?.pendingFollowUps??0,p=Math.max(0,t.filter(e=>e.optimistic?.admitted&&!e.optimistic.projectedEntryId&&!i.commandInputs.has(e.optimistic.commandId)).length-f),m=0,h=new Set,g=new Set,_=new Set,v=[];for(let e of t){if(e.optimistic?.projectedEntryId)continue;if(e.message.role===`custom`&&!e.message.truncation?.truncated){let t=TR(e.message),n=OR(i.customIndexes.get(t),g);if(n>=0){g.add(n);continue}}let n=e.optimistic?.commandId??(e.key.startsWith(`optimistic-`)?e.key.slice(11):void 0),a=n?i.commandInputs.get(n):void 0;if(a){e.optimistic&&l.push({key:e.key,entryId:a});continue}let o=SL(e.message);if(o.role===`user`&&e.optimistic){let t=e.optimistic.afterEntryId===null?-1:i.persistedPositions.get(e.optimistic.afterEntryId),n=!e.optimistic.admitted||m>=p?void 0:i.promptsBySignature.get(wR(o))?.find(n=>n.position!==void 0&&(t===void 0?n.parentId===e.optimistic?.afterEntryId:n.position>t)&&!c.has(n.key));if(n){c.add(n.key),l.push({key:e.key,entryId:n.key}),m++;continue}}else{let e=o.role===`user`?t.find(e=>e.optimistic?.admitted&&!e.optimistic.projectedEntryId&&!h.has(e.key)&&!l.some(t=>t.key===e.key)&&e.optimistic.sessionId===r?.id&&e.optimistic.sessionPath===r?.path&&wR(SL(e.message))===wR(o)):void 0;if(e){h.add(e.key);continue}let n=SR(o),a=TR(o),s=n===void 0?OR(i.nativeByLegacySignature.get(a),_):(i.nativeByIdentity.get(n)??[]).find(e=>!_.has(e)&&i.nativeMessages[e]?.signature===a)??-1;if(s>=0){_.add(s);continue}}let s={key:e.key,timingKey:e.key,timestamp:e.timestamp??new Date().toISOString(),message:o,optimistic:e.optimistic};o.role===`user`&&e.optimistic?u.push(s):v.push(s)}let y=new Map;for(let e of d?.queuedMessages??[])y.set(e,(y.get(e)??0)+1);let b=u.filter(e=>{if(!e.optimistic?.admitted||e.optimistic.commandId===d?.activeTurn?.commandId)return!0;let t=y.get(e.message.content)??0;return!t||(y.set(e.message.content,t-1),!1)}),x=new Map(t.flatMap(e=>e.optimistic?.projectedEntryId?[[e.optimistic.projectedEntryId,e.key]]:[]));for(let e of l)x.set(e.entryId,e.key);let S=i.baseEntries,C=(e,t)=>{S===i.baseEntries&&(S=i.baseEntries.slice()),S[e]=t};for(let[e,t]of s){let n=S[e];!n||n.timingKey===t||C(e,{...n,timingKey:t})}for(let[e,t]of n){let n=i.indexById.get(e);if(n===void 0)continue;let r=S[n];!r||r.key===t||C(n,{...r,key:t})}for(let[e,t]of x){let n=i.indexById.get(e);if(n===void 0)continue;let r=S[n];!r||r.key===t||C(n,{...r,key:t})}return{entries:S.concat(v,b),projectedPrompts:l}}function jR(e){let[t,n]=(0,_.useState)(()=>({row:e,since:Date.now()}));return(0,_.useEffect)(()=>{if(e?.key===t.row?.key)return;if(!e||!t.row){n({row:e,since:Date.now()});return}let r=window.setTimeout(()=>n({row:e,since:Date.now()}),Math.max(0,1e3-(Date.now()-t.since)));return()=>window.clearTimeout(r)},[e,t]),!e||e.key===t.row?.key?e:t.row??e}function MR({rows:e,active:t}){let{t:n}=cr(),r,[i,a]=(0,_.useState)(t),o=e.length===1,s=(0,_.useRef)(o),c=(0,_.useRef)(null),l=(0,_.useRef)(!0),u=(0,_.useRef)(0),d=(0,_.useRef)(void 0),[f,p]=(0,_.useState)({above:!1,below:!1}),m=(0,_.useCallback)(()=>{let e=c.current;if(!e)return;let t=e.scrollTop>1,n=e.scrollHeight-e.clientHeight-e.scrollTop>1;p(e=>e.above===t&&e.below===n?e:{above:t,below:n})},[]);(0,_.useEffect)(()=>a(t),[t]),(0,_.useLayoutEffect)(()=>{let n=c.current,r=s.current&&!o;s.current=o,!(!n||o||!i||e.length===0)&&(!r&&n.scrollTop!==u.current&&n.scrollHeight-n.clientHeight-n.scrollTop>24&&(l.current=!1),r&&!l.current&&(n.scrollTop=u.current),t&&l.current&&(n.scrollTop=n.scrollHeight,u.current=n.scrollTop),m())},[e,t,i,o,m]),(0,_.useEffect)(()=>{let e=c.current,n=e?.firstElementChild;if(!e||!n||o||typeof ResizeObserver>`u`)return;let r=new ResizeObserver(()=>{i&&t&&l.current&&(e.scrollTop=e.scrollHeight,u.current=e.scrollTop),m()});return r.observe(e),r.observe(n),()=>r.disconnect()},[t,i,o,m]);let h=e.filter(e=>e.processType===`thinking`).length,g=e.filter(e=>e.processType===`tool`).length,v=e.filter(e=>e.processType===`activity`).length,y=[h?n(`processThinkingCount`,{count:h}):``,g?n(`processToolCount`,{count:g}):``,v?n(`processActivityCount`,{count:v}):``].filter(Boolean),b=[...e].reverse().find(e=>e.processStatus===`running`),x=jR(b),S=x?.processPreview??(t?[...e].reverse():e).find(e=>e.processPreview)?.processPreview,C=x?.processToolName&&[`read`,`write`,`edit`].includes(x.processToolName)?S?.slice(Math.max(S.lastIndexOf(`/`),S.lastIndexOf(`\\`))+1):S,w=e.some(e=>e.error||e.processStatus===`error`),T=b?`running`:w?`error`:e.some(e=>e.processStatus===`warn`)?`warn`:e.every(e=>e.processStatus===`done`)?`done`:`unknown`,E=e.flatMap(e=>e.processToolName?[e.processToolName]:[]),D=[...new Set(E.map(e=>$I(e).action))],O=D.map(e=>n(`toolActionGroup_${e}`)),k=D.length?n(`toolGroup_${T===`done`?`done`:T===`running`?`running`:`unknown`}`,{actions:O.join(n(`toolGroupSeparator`))}):n(T===`running`?`processRunning`:`processDetails`),A=x?.processToolName?eL(n,x.processToolName,`running`):x?.processType===`thinking`?n(`thinkingActive`):k,j=x?.processToolName??E[0],M=x?.processType===`thinking`?Le:j?$I(j).Icon:It;return(0,K.jsxs)(`details`,{className:`process-sequence ${o?`single-process `:``}${T}`,open:o||i,"data-status":T,"data-running":T===`running`?`true`:void 0,"data-history-entry":e[0]?.key,onToggle:e=>{o||a(e.currentTarget.open)},children:[(0,K.jsxs)(`summary`,{hidden:o,"aria-label":[A,b?S:``,...y].filter(Boolean).join(` · `),children:[(0,K.jsx)(`span`,{className:`tool-icon`,"aria-hidden":`true`,children:(0,K.jsx)(M,{})}),(0,K.jsx)(`span`,{className:`process-sequence-title`,title:[O.join(n(`toolGroupSeparator`)),...y].filter(Boolean).join(` · `),children:(0,K.jsx)(`strong`,{children:A})}),S&&(b||!D.length)&&(0,K.jsx)(`span`,{className:`process-sequence-preview`,title:S,children:C}),(0,K.jsx)(`span`,{className:`process-sequence-counts`,children:y.join(` · `)}),(0,K.jsx)(ee,{className:`tool-disclosure`,"aria-hidden":`true`}),(0,K.jsx)(oR,{status:T})]}),(0,K.jsx)(`section`,{ref:c,className:`process-sequence-scroll`,"aria-label":o?void 0:[n(`processDetails`),...y].join(` · `),tabIndex:o?void 0:0,"data-scroll-above":f.above||void 0,"data-scroll-below":f.below||void 0,onScrollCapture:e=>{let t=e.target;if(o&&t instanceof HTMLElement&&t.classList.contains(`thinking-evidence`)){let n=t.getBoundingClientRect().top-e.currentTarget.getBoundingClientRect().top+t.scrollTop,r=n>u.current;u.current=n,l.current=(l.current||r)&&t.scrollHeight-t.clientHeight-t.scrollTop<=24}},onScroll:e=>{if(o)return;let t=e.currentTarget,n=t.scrollTop>u.current;u.current=t.scrollTop,l.current=(l.current||n)&&t.scrollHeight-t.clientHeight-t.scrollTop<=24,m()},onWheel:e=>{!e.defaultPrevented&&!e.ctrlKey&&!e.metaKey&&e.deltaY<0&&(o||VR(e.nativeEvent,e.currentTarget))&&(l.current=!1)},onKeyDown:e=>{let t=e.target;!e.defaultPrevented&&!e.altKey&&!e.metaKey&&(!e.ctrlKey||e.key===`Home`)&&([`ArrowUp`,`PageUp`,`Home`].includes(e.key)||e.key===` `&&e.shiftKey)&&t instanceof HTMLElement&&!t.isContentEditable&&!t.closest(`input, textarea, select`)&&!(e.key===` `&&t.closest(`button, summary`))&&(o||VR(e.nativeEvent,e.currentTarget))&&(l.current=!1)},onTouchStart:e=>{d.current=e.touches[0]?.clientY},onTouchMove:e=>{let t=e.touches[0]?.clientY;t!==void 0&&d.current!==void 0&&t>d.current&&(o||VR(e.nativeEvent,e.currentTarget))&&(l.current=!1),d.current=t},children:(0,K.jsx)(`div`,{className:`process-sequence-body`,children:e.map(e=>{e.processType===`thinking`?r=e.processMessageKey:e.processMessageKey!==r&&(r=void 0);let t=r!==void 0&&e.processType!==`thinking`;return(0,K.jsx)(`div`,{className:`process-step ${o?`single-tool-step `:``}${t?`thought-tool-step `:``}${e.processStatus??`unknown`}`,"data-status":e.processStatus??`unknown`,children:e.content},e.key)})})})]})}function NR(e,t){let n=[];for(let t of e){let e=n.at(-1),r=t.kind===`process`;r&&e?.process?e.rows.push(t):n.push({process:r,rows:[t]})}return n.flatMap((e,r)=>{let i=`${e.process?`process`:`rows`}-${e.rows[0]?.key}`;return e.process?(0,K.jsx)(MR,{rows:e.rows,active:t&&r===n.length-1},i):e.rows.map(e=>(0,K.jsx)(_.Fragment,{children:e.content},e.key))})}function PR({rows:e,timing:t,active:n,timedTurn:r}){let{t:i}=cr(),a=(0,_.useId)(),[o,s]=(0,_.useState)(t?.outcome!==`completed`),c=(0,_.useRef)(t?.outcome);(0,_.useEffect)(()=>{c.current!==t?.outcome&&t?.outcome===`completed`&&s(!1),c.current=t?.outcome},[t?.outcome]);let l=!!(t||r),u=[];for(let r of e){if(r.content===null)continue;let e=t?.resultEntryId?r.responseEntryId===t.resultEntryId&&r.final!==!1:!n&&r.final,i=r.kind!==`prompt`&&!e,a=u.at(-1);i&&a?.foldable?a.rows.push(r):u.push({foldable:i,rows:[r]})}let d=u.filter(e=>e.foldable),f=e=>e===0?a:`${a}-${e}`,p=d.length>0,m=t?(0,K.jsx)(OL,{timing:t}):r?(0,K.jsx)(DL,{elapsedMs:r.elapsedMs},JSON.stringify([r.sessionId,r.sessionPath,r.commandId,r.epoch,r.startedAt])):null;return(0,K.jsxs)(K.Fragment,{children:[l&&(0,K.jsxs)(`header`,{className:`turn-duration`,"data-outcome":t?.outcome,children:[p?(0,K.jsxs)(`button`,{type:`button`,className:`turn-duration-toggle`,"aria-expanded":o,"aria-controls":d.map((e,t)=>f(t)).join(` `),onClick:()=>s(e=>!e),children:[m,(0,K.jsx)(ee,{"aria-hidden":`true`})]}):m,t&&t.outcome!==`completed`&&(0,K.jsx)(`span`,{className:`turn-duration-outcome`,children:i(`turnElapsedOutcome_${t.outcome}`)})]}),l?u.map(e=>e.foldable?(0,K.jsx)(`div`,{className:`turn-response-body`,id:f(d.indexOf(e)),hidden:!o,children:NR(e.rows,n&&e===d.at(-1))},e.rows[0].key):(0,K.jsx)(_.Fragment,{children:NR(e.rows,!1)},e.rows[0].key)):NR(e,n)]})}function FR({id:e,rows:t,active:n,observed:r=!0,changes:i,session:a,timedTurn:o,onReviewTurn:s}){let{t:c}=cr(),l=[...t].reverse().find(e=>e.outcome||e.timing),u=l?.timing?.outcome??l?.outcome,d=t.some(e=>e.kind===`response`),f=t.find(e=>e.kind===`prompt`),p=!!(f?.promptEntryId&&t.some(e=>e.commandHandledInputId===f.promptEntryId&&e.commandHandledCommandId===f.promptCommandId)),m=t.some(e=>e.forkSnapshotBoundary),h=m?`forked`:n?r?`running`:`unknown`:u===`failed`?`failed`:u===`interrupted`||u===`cancelled`?`interrupted`:u===`completed`||d||p?`complete`:`waiting`,g=h===`failed`?`error`:h===`interrupted`?`warning`:h===`running`?`accent`:h===`complete`?`success`:`neutral`,v=c(h===`unknown`?`toolState_unknown`:`turnState_${h}`),y=t.some(e=>e.timing&&e.timing.commandId===o?.commandId&&e.timing.epoch===o?.epoch)?void 0:o,b=[],x=[],S=0,C=(e,t=!1)=>{b.push((0,K.jsx)(PR,{rows:x,timing:e,active:n&&t,timedTurn:t?y:void 0},`run-${S++}`)),x=[]};for(let e of t)e.kind===`prompt`?x.length?x.push(e):b.push((0,K.jsx)(_.Fragment,{children:e.content},e.key)):e.timing?C(e.timing):x.push(e);(x.length||y)&&C(void 0,!0);let w=!!(o||t.some(e=>e.timing));return(0,K.jsxs)(`section`,{className:`conversation-turn${e===0?` prelude`:``}`,"data-turn":e,children:[e>0&&h!==`complete`&&(!w||m)&&(0,K.jsxs)(`header`,{className:`turn-heading`,children:[(0,K.jsx)(`span`,{className:`sr-only`,children:c(`turnLabel`,{number:e})}),(0,K.jsxs)(`span`,{className:`turn-state ${h}`,children:[(0,K.jsx)(xL,{variant:g,label:v,isPulsing:h===`running`,icon:h===`failed`||h===`interrupted`?(0,K.jsx)(Lt,{"aria-hidden":`true`}):h===`forked`?(0,K.jsx)(Ae,{"aria-hidden":`true`}):void 0}),v]})]}),b,i&&a&&(0,K.jsx)(GL,{changes:i,onReview:s},`${a.id}:${a.path}:${i.promptEntryId}`)]})}function IR(e,t,n,r){let i=new Map;for(let t=0;t{if(!t)return;let r=i.get(t);if(!(r===void 0||r>=n)){for(let t=r+1;te.rows.some(e=>e.promptCommandId===n||r?.promptEntryId&&e.promptEntryId===r.promptEntryId)):void 0,l=s.length-1;for(;l>=0&&s[l].id!==0&&!s[l].rows.some(e=>e.kind===`prompt`&&!e.pendingPrompt);)l--;return{turns:s,activeTurn:c?.id??s[l]?.id}}function LR(e,t,n,r,i,a,o,s=!0){let{turns:c,activeTurn:l}=IR(e,t,n,a);return c.map(e=>(0,K.jsx)(FR,{id:e.id,rows:e.rows,active:t&&e.id===l&&!e.rows.some(e=>e.forkSnapshotBoundary),observed:s,changes:r?.get(e.rows.find(e=>e.kind===`prompt`&&!e.pendingPrompt)?.promptEntryId??``),session:i,timedTurn:t&&e.id===l&&!e.rows.some(e=>e.forkSnapshotBoundary)?a:void 0,onReviewTurn:o},`turn-group-${e.rows[0]?.key}`))}function RR(e,t,n){let r=e.getBoundingClientRect(),i=r.top,a=Array.from(e.querySelectorAll(`[data-history-entry], [data-history-message], [data-history-result]`)).filter(t=>{let n=t.getBoundingClientRect(),i=Math.max(n.top,r.top),a=Math.min(n.bottom,r.bottom);for(let n=t;n&&n!==e;n=n.parentElement){if(n.hidden||n instanceof HTMLDetailsElement&&!n.open&&n!==t&&!n.querySelector(`:scope > summary`)?.contains(t))return!1;if(n===t)continue;let e=getComputedStyle(n);if(!/^(auto|scroll|overlay|hidden|clip)$/.test(e.overflowY))continue;let r=n.getBoundingClientRect();i=Math.max(i,r.top),a=Math.min(a,r.bottom)}return a>i}),o=a.find(e=>!a.some(t=>t!==e&&e.contains(t))),s=o?.dataset.historyResult??o?.dataset.historyEntry??o?.dataset.historyMessage,c=o?.dataset.historyResult??o?.dataset.historyMessage,l=n?.entries.find(e=>e.id===c||e.id===s)?.id;if(!l&&s)for(let e of n?.entries??[])s.startsWith(`${e.id}-`)&&(!l||e.id.length>l.length)&&(l=e.id);return{key:l?s:void 0,entryId:l,offset:(o?.getBoundingClientRect().top??i)-i,scrollTop:e.scrollTop,pinned:t}}function zR(e,t){let n=!1;for(let r=e.parentElement;r&&r!==t;r=r.parentElement)if(r instanceof HTMLDetailsElement&&(r.open=!0),r.classList.contains(`turn-response-body`)&&r.hidden){let e=Array.from(t.querySelectorAll(`button[aria-controls]`)).find(e=>e.getAttribute(`aria-controls`)?.split(` `).includes(r.id));e&&(e.click(),n=!0)}return n}function BR(e,t,n){if(e.scrollIntoView?.({block:`nearest`,inline:`nearest`,behavior:`instant`}),n){t.scrollTop=n.scrollTop;for(let r=e.parentElement;r&&r!==t;r=r.parentElement)!/^(auto|scroll|overlay)$/.test(getComputedStyle(r).overflowY)||r.scrollHeight<=r.clientHeight||(r.scrollTop+=e.getBoundingClientRect().top-t.getBoundingClientRect().top-n.offset)}return Math.max(0,t.scrollTop+e.getBoundingClientRect().top-t.getBoundingClientRect().top-(n?.offset??24))}function VR(e,t){for(let n of e.composedPath()){if(n===t)return!0;if(!(n instanceof HTMLElement))continue;let e=getComputedStyle(n);if(/^(auto|scroll|overlay)$/.test(e.overflowY)&&(n.scrollTop>0||/^(contain|none)$/.test(e.overscrollBehaviorY)))return!1}return!1}function HR(e){let{t}=cr(),n=(0,_.useRef)(null),r=(0,_.useRef)(null),i=(0,_.useRef)(!0),a=(0,_.useRef)(0),o=(0,_.useRef)(void 0),s=(0,_.useRef)(0),c=(0,_.useRef)(e.readingRestorePending);c.current=e.readingRestorePending;let[l,u]=(0,_.useState)(!1),d=(0,_.useRef)(null),f=e.activityObserved!==!1&&e.resultExposureEnabled!==!1,p=(0,_.useCallback)(()=>{d.current?.abort(),d.current=null},[]),m=(0,_.useRef)(void 0),h=(0,_.useRef)(e.scrollToBottom),g=(0,_.useRef)(null),v=(0,_.useMemo)(()=>e.readingCache??new Map,[e.readingCache]),y=e.historyNavigation,b=y?JSON.stringify([y.sessionId,y.sessionPath,y.entryId,y.revision]):null,x=(0,_.useRef)(null),[S,C]=(0,_.useState)(null),T=tR(e.snapshot.selectedSession,{onAnchorChange:e.onHistoryAnchorChange,onRefresh:e.onRefreshHistory,preload:e.activityObserved!==!1&&e.resultExposureEnabled!==!1,beforePrepend:()=>{let e=n.current;e&&(g.current={...RR(e,!1,D.current),scrollHeight:e.scrollHeight},i.current=!1)}},v,y),E=T.session,D=(0,_.useRef)(E);D.current=E;let O=E?.id,k=E?.path,A=E?.cwd,j=S&&S.sessionId===O&&S.sessionPath===k?S.entryId:void 0,M=JSON.stringify([O,k]),N=JSON.stringify([e.snapshot.selectedSession?.id,e.snapshot.selectedSession?.path,e.snapshot.selectedSession?.history?.leafEntryId??e.snapshot.selectedSession?.entries.at(-1)?.id]);(0,_.useLayoutEffect)(()=>(f||p(),p),[N,b,f,p]),(0,_.useLayoutEffect)(()=>{let e=n.current;if(!e||!O||!k)return;let t=()=>{c.current||vL(v,M,{position:RR(e,i.current,D.current)})};window.addEventListener(`pagehide`,t);let r=()=>{document.visibilityState===`hidden`&&t()};return document.addEventListener(`visibilitychange`,r),()=>{window.clearTimeout(s.current),window.removeEventListener(`pagehide`,t),document.removeEventListener(`visibilitychange`,r),t()}},[M,v,O,k]);let P=(0,_.useRef)(M),[F,I]=(0,_.useState)({});(0,_.useLayoutEffect)(()=>{P.current!==M&&(P.current=M,I({}))},[M]);let L=(0,_.useMemo)(()=>new Map((E?.entries??[]).flatMap(e=>e.turnChanges&&e.turnChanges.sessionId===E?.id?[[e.turnChanges.promptEntryId,e.turnChanges]]:[])),[E?.entries,E?.id]),R=(0,_.useRef)(T.reset),ee=T.hasNewer||T.verifying,z=rj(e.snapshot,E),B=e.snapshot.selectedExecution?.sessionId===E?.id&&e.snapshot.selectedExecution?.sessionPath===E?.path?e.snapshot.selectedExecution:void 0,V=z&&e.liveActiveTurn!==void 0?e.liveRunning:z&&e.liveRunning||(B?B.status===`running`:z&&e.snapshot.runtime.status===`running`),H=!ee&&V?B?B.retry:z?e.liveRetry??void 0:void 0:void 0,te=(0,_.useRef)({scope:M,keys:new Map});te.current.scope!==M&&(te.current={scope:M,keys:new Map});let{entries:ne,projectedPrompts:re}=(0,_.useMemo)(()=>AR({...e.snapshot,selectedSession:E},ee?[]:e.liveMessages.filter(e=>e.optimistic?e.optimistic.sessionId===E?.id&&e.optimistic.sessionPath===E?.path:z),te.current.keys),[e.snapshot,E,z,ee,e.liveMessages]);(0,_.useEffect)(()=>{E&&re.length>0&&e.onPromptProjection?.(E.id,E.path,re)},[E,re,e.onPromptProjection]),(0,_.useEffect)(()=>{let e=n.current;if(!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(()=>{i.current&&(typeof e.scrollTo==`function`?e.scrollTo({top:e.scrollHeight,behavior:`instant`}):e.scrollTop=e.scrollHeight,a.current=e.scrollTop)});return t.observe(e),r.current&&t.observe(r.current),()=>t.disconnect()},[]);let{rows:ie,turns:ae}=(0,_.useMemo)(()=>{let n=aj(ne.map(e=>e.message)),r=uR(ne,V&&!ee),i=[...r.finalErrors].at(-1),a=-1;for(let e=ne.length-1;e>=0;e--)if(ne[e].message.role===`assistant`){a=e;break}let o=new Map,s,c=new Map,l=new Set,u=z?e.snapshot.runtime.liveTools??[]:[],d=B?.liveTools??[],f=ee?[]:[...u,...d.filter(e=>!u.some(t=>t.call.id===e.call.id))];ne.forEach(e=>{let{message:t}=e;t.role===`toolResult`&&t.toolCallId&&c.set(t.toolCallId,e),t.parts?.forEach(e=>{e.type===`toolCall`&&e.id&&![`ask_user`,`human_handoff`].includes(e.name)&&l.add(e.id)})});let p=[],m=0,h,g=-1,_=-1;for(let e=ne.length-1;e>=0;e--){if(ne[e]?.message.role===`user`){_=e;break}if(ne[e]?.message.role===`custom`&&ne[e]?.message.customType===`openpi-setup-request`)break}let v=new Set,y=-1;ne.forEach(({message:e},t)=>{e.role===`user`||e.role===`custom`&&e.customType===`openpi-setup-request`?(y>=0&&v.add(y),y=-1):e.role===`assistant`&&e.content.trim()&&(y=t)}),y>=0&&v.add(y);let b=ne.flatMap((u,d)=>{let y=u.message;if(u.forkSnapshotBoundary)return[{key:u.key,turn:m,kind:`custom`,forkSnapshotBoundary:!0,content:null}];if(u.timing)return[{key:u.key,turn:m,kind:`custom`,timing:u.timing,content:null}];if(u.compaction)return[{key:u.key,turn:m,kind:`custom`,content:(0,K.jsx)(kL,{compaction:{state:`completed`}})}];if(y.role===`custom`){if(y.customType===`openpi-web-command-handled`){let e=y.details;return e&&typeof e==`object`&&`inputEntryId`in e&&typeof e.inputEntryId==`string`?[{key:u.key,turn:m,kind:`custom`,commandHandledInputId:e.inputEntryId,commandHandledCommandId:`commandId`in e&&typeof e.commandId==`string`?e.commandId:void 0,content:null}]:[]}return y.display===!1||![`openpi-web-command-feedback`,`openpi-setup-request`,`openpi-setup-closed`,`subagent-result`,`workflow-result`].includes(y.customType??``)?[]:(y.customType===`openpi-setup-request`&&(h=void 0,g=-1,m++),[{key:u.key,turn:m,kind:`custom`,content:(0,K.jsx)(`article`,{className:`message-row assistant detail-only`,"data-history-entry":u.entryId??u.key,tabIndex:-1,children:(0,K.jsx)(`div`,{className:`message-content`,children:(0,K.jsx)(bR,{message:y,sessionId:O??``,onInspectSubagent:e.onInspectSubagent,fullSubagent:e.snapshot.preferences.subagentResultDisplay===`full`})})})}])}if(y.role===`user`){h=y.content,g=d,m++,p.push({entryId:u.entryId??u.key,title:Array.from((y.content||t(`attachedImage`)).replace(/\s+/g,` `).trim()).slice(0,240).join(``)});let n=u.entryId?JSON.stringify([O,k,u.entryId]):``,r=F[n],i=!!(y.truncation?.visibleText&&r===void 0);return[{key:u.key,turn:m,kind:`prompt`,pendingPrompt:!!u.optimistic,promptCommandId:u.optimistic?.commandId??y.commandId,promptEntryId:u.entryId,content:(0,K.jsxs)(`article`,{className:`message-row user`,id:`turn-${m}`,"data-history-entry":u.entryId??u.key,"data-history-highlighted":j&&u.entryId===j||void 0,tabIndex:-1,children:[(0,K.jsxs)(`div`,{className:`message-content`,children:[(0,K.jsx)(JL,{message:y,sessionId:O,path:k,entryId:u.entryId}),(y.content||y.truncation?.visibleText)&&(u.entryId&&O&&k&&y.truncation?.visibleText?(0,K.jsx)(FL,{preview:y.content,sessionId:O,sessionPath:k,entryId:u.entryId,markdown:!1,fullText:r,onComplete:e=>I(t=>({...t,[n]:e}))},`${O}:${k}:${u.entryId}`):(0,K.jsx)(PL,{content:y.content}))]}),(0,K.jsx)(yR,{content:r??y.content,editable:z&&!V&&!!(e.forkAvailable&&e.onEdit&&u.entryId&&O&&k&&!u.optimistic)&&!i,copyRequiresFull:i,timestamp:u.timestamp,onResend:t=>e.onEdit&&u.entryId&&O&&k?e.onEdit({sessionId:O,sessionPath:k,entryId:u.entryId},t):Promise.resolve(!1),onFork:u.entryId&&O&&k&&e.onFork&&!u.optimistic?()=>e.onFork({sessionId:O,sessionPath:k,entryId:u.entryId}):void 0,canFork:z&&!V&&e.forkAvailable,forkPending:e.forkPending})]})}]}if(y.role===`assistant`){let b=p.at(-1);b&&y.content.trim()&&(b.reply=Array.from(y.content.replace(/\s+/g,` `).trim()).slice(0,240).join(``));let x=[],S=y.parts??[],C=y.webSearch??[],w=e=>Math.min(S.length,e.beforePartIndex??0),T=e=>{for(let[t,n]of C.entries()){if(w(n)!==e)continue;let r=n.status===`completed`?`done`:n.status===`failed`?`error`:`warn`;x.push({key:`${u.key}-native-search-${t}`,turn:m,kind:`process`,processType:`tool`,processMessageKey:u.key,processToolName:`web_search`,processPreview:n.query,processStatus:r,error:n.status===`failed`,content:(0,K.jsx)(`article`,{className:`message-row assistant detail-only`,"data-history-entry":`${u.entryId??u.key}-native-search-${t}-body`,"data-history-message":u.entryId??u.key,tabIndex:-1,children:(0,K.jsx)(`div`,{className:`message-content`,children:(0,K.jsx)(pR,{body:n.query,icon:(0,K.jsx)(je,{}),name:`web_search`,summary:n.query,status:r})})})})}},E=S.reduce((e,t,n)=>(t.type===`thinking`||t.type===`text`)&&!t.text.trim()?e:n,-1),D=S.reduce((e,t,n)=>t.type===`text`?n:e,-1),M=!!(u.entryId&&O&&k&&y.truncation?.visibleText),N=y.content,P=u.entryId?JSON.stringify([O,k,u.entryId]):``,L=F[P],R=!!(y.truncation?.visibleText&&L===void 0),te=(t,n,r)=>{M&&!r||!M&&!t.trim()||x.push({key:n,turn:m,kind:`response`,responseEntryId:u.entryId,final:r&&(y.stopReason===`stop`||y.stopReason===`length`),content:(0,K.jsxs)(`article`,{className:`message-row assistant response${r&&v.has(d)?` final-response`:``}`,"data-history-message":u.entryId??u.key,"data-history-highlighted":j&&u.entryId===j||void 0,tabIndex:-1,"data-history-entry":u.entryId?`${u.entryId}-${n.slice(u.key.length+1)}`:n,children:[(0,K.jsx)(`div`,{className:`message-content`,children:M&&O&&k&&u.entryId?(0,K.jsx)(FL,{preview:N,sessionId:O,sessionPath:k,entryId:u.entryId,markdown:!0,fullText:L,onComplete:e=>I(t=>({...t,[P]:e}))},`${O}:${k}:${u.entryId}`):(0,K.jsx)(Sk,{children:t})}),r&&v.has(d)&&(0,K.jsx)(yR,{content:L??y.content,editable:!1,copyRequiresFull:R,timestamp:u.timestamp,onResend:e.onResend,onRegenerate:b?.entryId&&O&&k&&e.onRegenerate&&!u.optimistic&&!y.isError&&(y.stopReason===`stop`||y.stopReason===`length`)?()=>e.onRegenerate({sessionId:O,sessionPath:k,entryId:b.entryId}):void 0,onFork:u.entryId&&O&&k&&e.onFork?()=>e.onFork({sessionId:O,sessionPath:k,entryId:u.entryId}):void 0,canFork:z&&!V&&e.forkAvailable,forkPending:e.forkPending})]})})};y.parts?.forEach((r,i)=>{if(T(i),r.type===`text`&&(S[i-1]?.type!==`text`||C.some(e=>w(e)===i))){let e=r.text,t=i+1;for(;S[t]?.type===`text`&&!C.some(e=>w(e)===t);){let n=S[t];n?.type===`text`&&(e+=n.text),t++}te(e,`${u.key}-text-${i}`,t>D)}if(r.type===`thinking`&&r.text.trim()){let t=!ee&&!H&&!y.stopReason&&B?.compaction?.state!==`running`&&V&&d===ne.length-1&&i===E?e.activityObserved===!1?`unknown`:`running`:`done`;x.push({key:`${u.key}-thinking-${i}`,turn:m,kind:`process`,processType:`thinking`,processMessageKey:u.key,processPreview:fR(r.text),processStatus:t,content:(0,K.jsx)(`article`,{className:`message-row assistant detail-only`,"data-history-entry":`${u.entryId??u.key}-thinking-${i}-body`,"data-history-message":u.entryId??u.key,"data-history-highlighted":j&&u.entryId===j||void 0,tabIndex:-1,children:(0,K.jsx)(`div`,{className:`message-content`,children:(0,K.jsx)(vR,{body:r.text,truncated:r.textTruncated,source:u.entryId&&O&&k&&r.sourcePartIndex!==void 0?{sessionId:O,sessionPath:k,entryId:u.entryId,partIndex:r.sourcePartIndex}:void 0,status:t,level:t===`running`?e.snapshot.thinking?.level:void 0,duration:kR(u,e.thinkingDurations),defaultOpen:e.snapshot.preferences.expandThinking===!0},JSON.stringify([O,k,u.key,i]))})})})}if(r.type===`toolCall`){let a=r,o=f.find(e=>e.call.id===a.id),s=a.id?c.get(a.id):void 0,d=s?.message??o?.result,p=AL(a,d,f,s?void 0:o?.state),h=p?[...p.children.map(e=>({call:e.call,child:e})),...p.showWrapper?[{call:a}]:[]]:[{call:a}];for(let[r,{call:o,child:g}]of h.entries()){let _=o.name.startsWith(`subagent`)?e.snapshot.preferences.subagentResultDisplay===`full`:o.name===`bash`?e.snapshot.preferences.bashToolDisplay===`full`:o.name===`write`||o.name===`edit`?e.snapshot.preferences.fileMutationDisplay===`full`:!1,v=o.id?f.find(e=>e.call.id===o.id):void 0,y=g?s:o.id?c.get(o.id):void 0,b=g?void 0:y?.message,S=g?g.result:b??v?.result,C=g?g.state:b?void 0:v?.state,w=g?g.state===`returned`?`done`:g.state===`failed`?`error`:g.state===`cancelled`||g.state===`timed_out`?`warn`:g.state:aR(S,C),T=e.activityObserved===!1&&w===`running`?`unknown`:w,E=o.name===`plan_ready`&&S&&IL(S)?(0,K.jsx)(LL,{result:S,sessionId:O,sessionPath:k,entryId:y?.entryId},`${u.key}-${o.id||i}-plan`):Ld(o.name)&&!g?.outputMissing?(0,K.jsx)(WL,{call:o,result:S,liveState:C,observed:e.activityObserved,cwd:A,defaultOpen:_},`${u.key}-${o.id||i}-evidence`):g?.outputMissing?null:hR(o,S,{sessionId:O??``,subagents:z?e.snapshot.runtime.capabilities.subagents?.items:void 0,workflows:z?e.snapshot.runtime.capabilities.workflows?.items:void 0,records:n,onInspectSubagent:e.onInspectSubagent,liveState:C,defaultOpen:_,observed:e.activityObserved!==!1}),D=rR(o.arguments),{Icon:M,action:N}=$I(o.name),P=(0,K.jsx)(M,{},`${u.key}-${o.id||i}-icon`);x.push({key:`${u.key}-tool-${o.id||i}`,turn:m,kind:o.name===`plan_ready`&&S&&IL(S)?`response`:E&&(o.name===`subagent_spawn`||o.name===`workflow`)?`custom`:`process`,processType:/^(subagent|workflow)/u.test(o.name)?`activity`:`tool`,processMessageKey:u.key,processToolName:o.name,processPreview:nL(o.name,D).split(` -`).find(Boolean),processStatus:T,error:T===`error`,content:(0,K.jsx)(`article`,{className:`message-row assistant detail-only`,"data-history-message":u.entryId??u.key,"data-history-result":y?.entryId,"data-history-highlighted":j&&(u.entryId===j||y?.entryId===j)||void 0,tabIndex:-1,children:(0,K.jsxs)(`div`,{className:`message-content`,children:[E||(0,K.jsx)(pR,{body:o.name===`bash`&&typeof D.command==`string`?D.command:o.arguments,icon:P,name:o.name||`tool`,summary:N===`search`&&typeof D.path==`string`?t(`toolSearchTarget`,{path:D.path,pattern:dR(o.name,D)}):dR(o.name,D),output:g?g.error??S?.content:o.id&&l.has(o.id)?S?.content:void 0,status:T,evidenceState:e.activityObserved===!1&&g?.state===`running`?`unknown`:g?.state,rawDetails:p?.showWrapper&&o.id===a.id?d?.details:void 0,note:g?.outputMissing?t(g.argumentsOmitted?`toolNestedArgumentsMissing`:`toolNestedOutputMissing`):void 0,snapshotMissingResult:S?.forkSnapshotToolResult,defaultOpen:_}),p?.incomplete&&r===h.length-1&&(0,K.jsx)(`p`,{className:`evidence-note`,role:`status`,children:t(`toolNestedIncomplete`)}),p&&r===h.length-1&&!p.showWrapper&&(0,K.jsxs)(`details`,{className:`evidence-raw`,children:[(0,K.jsx)(`summary`,{children:t(`toolCodemodeDetails`)}),(0,K.jsx)(`pre`,{children:Fd(a.arguments).text}),(0,K.jsx)(`pre`,{children:Fd(d?.content??``).text})]})]})})})}}}),T(S.length),D<0&&te(y.content,`${u.key}-answer`,!0),y.stopReason===`error`&&!r.finalErrors.has(d)&&(o.set(u.key,[...x]),x.length=0);let re=r.groups.get(d);if(re&&(re.state===`retrying`&&H&&(s=`${re.attempts[0].key}-attempts`),x.push({key:`${re.attempts[0].key}-attempts`,turn:m,kind:`outcome`,outcome:re.state===`interrupted`?`interrupted`:void 0,content:(0,K.jsx)(`article`,{className:`message-row assistant outcome-row`,children:(0,K.jsx)(lR,{state:re.state,retry:re.state===`retrying`?H:void 0,observed:e.activityObserved!==!1&&B?.status!==`unknown`,attempts:re.attempts.map(e=>({entry:e,content:o.get(e.key)}))})})})),r.finalErrors.has(d)||y.stopReason===`aborted`){let t=y.stopReason===`error`,n=g===_&&d===i&&d===a?h:void 0;x.push({key:`${u.key}-outcome`,turn:m,kind:`outcome`,error:t,outcome:t?`failed`:`interrupted`,content:(0,K.jsx)(`article`,{className:`message-row assistant outcome-row`,children:(0,K.jsx)(cR,{failed:t,error:y.errorMessage,retryPrompt:n,retryEntryId:u.entryId,canRetry:z&&!ee&&!V,onRetry:e.onResend})})})}else(y.stopReason===`stop`||y.stopReason===`length`)&&x.push({key:`${u.key}-completed`,turn:m,kind:`outcome`,outcome:`completed`,content:null});return x}if(y.role===`toolResult`){if(y.toolCallId&&l.has(y.toolCallId))return[];if(IL(y))return[{key:u.key,turn:m,kind:`response`,content:(0,K.jsx)(`article`,{className:`message-row assistant detail-only`,"data-history-message":u.entryId??u.key,"data-history-highlighted":j&&u.entryId===j||void 0,tabIndex:-1,children:(0,K.jsx)(`div`,{className:`message-content`,children:(0,K.jsx)(LL,{result:y,sessionId:O,sessionPath:k,entryId:u.entryId})})})}];let n=y.toolName?.startsWith(`subagent`)?`subagent`:y.toolName?.startsWith(`workflow`)?`workflow`:null,r=aR(y),i=e.activityObserved===!1&&r===`running`?`unknown`:r,a=y.toolName||`tool`,o=n===`subagent`?e.snapshot.preferences.subagentResultDisplay===`full`:a===`bash`?e.snapshot.preferences.bashToolDisplay===`full`:a===`write`||a===`edit`?e.snapshot.preferences.fileMutationDisplay===`full`:!1,{Icon:s}=$I(a),c=(0,K.jsx)(s,{},`${u.key}-icon`),d=n&&!y.forkSnapshotToolResult?(0,K.jsx)(mR,{family:n,title:`${a.replaceAll(`_`,` `)} · ${ej(y.content)}`,body:y.content,status:i,defaultOpen:o},`${u.key}-card`):xR(y.content)&&!y.forkSnapshotToolResult?(0,K.jsxs)(`div`,{className:`tool-line-empty`,children:[(0,K.jsx)(`span`,{className:`tool-icon`,children:c}),(0,K.jsx)(`span`,{className:`tool-name`,children:a}),(0,K.jsx)(`span`,{className:`tool-summary`,children:t(`noOutput`)}),(0,K.jsx)(oR,{status:i})]},`${u.key}-empty`):(0,K.jsx)(pR,{body:y.content,icon:c,name:a,summary:ej(y.content),status:i,snapshotMissingResult:y.forkSnapshotToolResult,defaultOpen:o},`${u.key}-evidence`);return[{key:u.key,turn:m,kind:a===`ask_user`||a===`human_handoff`?`response`:`process`,processType:n?`activity`:`tool`,processToolName:a,processStatus:i,error:i===`error`,content:(0,K.jsx)(`article`,{className:`message-row assistant detail-only`,"data-history-entry":`${u.entryId??u.key}-body`,"data-history-message":u.entryId??u.key,"data-history-highlighted":j&&u.entryId===j||void 0,tabIndex:-1,children:(0,K.jsx)(`div`,{className:`message-content`,children:d})})}]}return[]}),x=b.length;for(;x>0&&b[x-1].pendingPrompt;)x--;let S=b.length-x,C=b[x-1]?.turn??0;H&&!s&&(s=`native-retry`,b.splice(x,0,{key:`native-retry`,turn:C,kind:`outcome`,content:(0,K.jsx)(`article`,{className:`message-row assistant outcome-row`,children:(0,K.jsx)(lR,{attempts:[],state:`retrying`,retry:H,observed:e.activityObserved!==!1&&B?.status!==`unknown`})})}));let w=!ee&&B?.compaction;if(w&&w.state!==`completed`){let n=b.findIndex(e=>e.key===s),r={key:`native-compaction-${w.startedAt??w.state}`,turn:b[n]?.turn??C,kind:`custom`,content:(0,K.jsx)(kL,{compaction:w,observed:e.activityObserved!==!1&&B?.status!==`unknown`})};b.splice(n<0?x:n,0,r),w.state===`failed`&&w.errorMessage&&b.splice(b.length-S,0,{key:`native-compaction-error`,turn:r.turn,kind:`custom`,content:(0,K.jsx)(`article`,{className:`message-row assistant outcome-row`,children:(0,K.jsx)(sR,{label:t(`compactionFailed`),message:w.errorMessage})})})}return{rows:b,turns:p}},[z,V,B,H,e.activityObserved,ee,ne,e.onResend,e.onEdit,e.onRegenerate,e.onFork,e.forkAvailable,e.forkPending,e.onInspectSubagent,e.snapshot.runtime.capabilities.subagents,e.snapshot.runtime.capabilities.workflows?.items,e.snapshot.preferences.expandThinking,e.snapshot.preferences.subagentResultDisplay,e.snapshot.preferences.bashToolDisplay,e.snapshot.preferences.fileMutationDisplay,e.snapshot.thinking?.level,e.thinkingDurations,e.snapshot.runtime.liveTools,O,k,A,F,j,t]),U=YL(e.snapshot.selectedSession,ae,f),oe=(0,_.useCallback)(async(t,r=!1)=>{if(p(),!f||!O||!k)return!1;let o=n.current,s=Array.from(o?.querySelectorAll(`[data-history-entry]`)??[]).find(e=>e.dataset.historyEntry===t);if(o&&s){i.current=!1,u(!0),C({sessionId:O,sessionPath:k,entryId:t});let e=Math.max(0,o.scrollTop+s.getBoundingClientRect().top-o.getBoundingClientRect().top-16),n=window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches;return o.scrollTo?.({top:e,behavior:r||n?`instant`:`smooth`}),typeof o.scrollTo!=`function`&&(o.scrollTop=e),a.current=o.scrollTop,s.focus({preventScroll:!0}),!0}if(r)return;if(!e.onNavigateToMessage)return!1;let c=new AbortController;d.current=c;let l=await e.onNavigateToMessage({sessionId:O,sessionPath:k,entryId:t},c.signal);if(!(c.signal.aborted||d.current!==c))return d.current=null,l},[p,f,O,k,e.onNavigateToMessage]);(0,_.useLayoutEffect)(()=>{let t=n.current;if(!t||!E)return;let r=_L(E),o=m.current!==r,s=R.current!==T.reset,l=o||s;R.current=T.reset;let d=h.current!==e.scrollToBottom;if(h.current=e.scrollToBottom,y&&b!==x.current&&y.sessionId===E.id&&y.sessionPath===E.path){i.current=!1,g.current=null,m.current=r;return}if(d&&T.engaged){g.current=null,T.resetToLatest();return}let f=o&&!s&&!d?v.get(r)?.position:void 0,p=f?.key&&Array.from(t.querySelectorAll(`[data-history-entry], [data-history-message], [data-history-result]`)).some(e=>e.dataset.historyEntry===f.key||e.dataset.historyMessage===f.key||e.dataset.historyResult===f.key),_=g.current??(f&&!f.pinned&&(!c.current||p)?{...f,scrollHeight:t.scrollHeight}:null);if(g.current=null,_&&(!l||f)&&!d){let e=Array.from(t.querySelectorAll(`[data-history-entry], [data-history-message], [data-history-result]`)),n=_.key===void 0?void 0:e.find(e=>e.dataset.historyEntry===_.key)??e.reverse().find(e=>e.dataset.historyMessage===_.key||e.dataset.historyResult===_.key);i.current=!1,u(!0),m.current=r;let o=()=>{if(n&&!t.contains(n))return;g.current===_&&(g.current=null);let e=n?BR(n,t,_):_.scrollTop+t.scrollHeight-_.scrollHeight;typeof t.scrollTo==`function`?t.scrollTo({top:e,behavior:`instant`}):t.scrollTop=e,a.current=t.scrollTop};if(n&&zR(n,t)){g.current=_;let e=requestAnimationFrame(o);return()=>cancelAnimationFrame(e)}o();return}(l||d||i.current)&&(i.current=!0,u(!1),typeof t.scrollTo==`function`?t.scrollTo({top:t.scrollHeight,behavior:`instant`}):t.scrollTop=t.scrollHeight,a.current=t.scrollTop),m.current=r},[E,ne,T.reset,T.engaged,T.resetToLatest,e.scrollToBottom,v,y,b]),(0,_.useLayoutEffect)(()=>{let e=n.current;if(!e||!E||!y||b===x.current||y.sessionId!==E.id||y.sessionPath!==E.path)return;let t=Array.from(e.querySelectorAll(`[data-history-entry], [data-history-message], [data-history-result]`)),r=t.filter(e=>e.dataset.historyEntry===y.entryId||e.dataset.historyMessage===y.entryId||e.dataset.historyResult===y.entryId),o=y.restorePosition?.key?t.find(e=>e.dataset.historyEntry===y.restorePosition.key)??[...t].reverse().find(e=>e.dataset.historyMessage===y.restorePosition.key||e.dataset.historyResult===y.restorePosition.key):void 0,s=o??r.find(e=>e.classList.contains(`response`))??r.find(e=>e.dataset.historyMessage===y.entryId||e.dataset.historyResult===y.entryId)??r[0];if(!s)return;zR(s,e);let c=()=>{if(!e.contains(s)||y.restorePosition&&x.current===b)return;let t=BR(s,e,o?y.restorePosition:void 0);e.scrollTo?.({top:t,behavior:`instant`}),typeof e.scrollTo!=`function`&&(e.scrollTop=t),a.current=e.scrollTop,y.restorePosition||s.focus({preventScroll:!0}),i.current=!1,u(!0),y.restorePosition||C(y),x.current=b,vL(v,_L(E),{position:RR(e,!1,E)})},l=document.querySelector(`dialog[open]`),d,f=()=>{d=requestAnimationFrame(c)};return l?l.addEventListener(`close`,f,{once:!0}):f(),()=>{l?.removeEventListener(`close`,f),d!==void 0&&cancelAnimationFrame(d)}},[E,y,b,v]);let se=z?e.liveRetry?`${t(`modelRetrying`)} (${e.liveRetry.attempt}/${e.liveRetry.maxAttempts})`:e.livePhase===`preparing`?t(`modelPreparing`):t(`modelRunning`):t(`backgroundSessionRunning`),ce=z?0:B?.liveTools.filter(e=>e.state===`running`).length??0,le=z&&e.liveActiveTurn!==void 0?e.liveActiveTurn:B?B.activeTurn:z?e.snapshot.runtime.activeTurn:void 0,ue=V&&le&&E&&le.sessionId===E.id&&le.sessionPath===E?.path&&typeof le.startedAt==`number`&&Number.isFinite(le.startedAt)&&typeof le.elapsedMs==`number`&&Number.isFinite(le.elapsedMs)&&le.elapsedMs>=0?le:void 0,de=!T.verifying&&ue&&(!ee||ue.promptEntryId&&ie.some(e=>e.promptEntryId===ue.promptEntryId))?ue:void 0,fe=t=>{T.hasMore&&!T.error&&!T.verifying&&e.activityObserved!==!1&&e.resultExposureEnabled!==!1&&t.scrollTop<=Math.max(t.clientHeight,160)&&T.loadOlder()},pe=()=>{i.current=!1,u(!0),T.retainReading()};return(0,K.jsxs)(`div`,{className:`transcript-surface`,children:[(0,K.jsx)(`div`,{ref:n,className:`conversation`,role:`log`,"aria-label":`Conversation`,tabIndex:0,onPointerDownCapture:()=>{y?.restorePosition&&(x.current=b)},onTouchStartCapture:e=>{o.current=e.touches[0]?.clientY,y?.restorePosition&&(x.current=b)},onTouchMove:e=>{let t=e.touches[0]?.clientY;t!==void 0&&o.current!==void 0&&t>o.current&&VR(e.nativeEvent,e.currentTarget)&&pe(),o.current=t},onScroll:e=>{let t=e.currentTarget,n=t.scrollTopa.current;a.current=t.scrollTop;let o=t.scrollTop+t.clientHeight>=t.scrollHeight-48;i.current=i.current?!n||o:r&&o,i.current||T.retainReading(),u(!i.current),window.clearTimeout(s.current),s.current=window.setTimeout(()=>{!c.current&&O&&k&&t.isConnected&&vL(v,M,{position:RR(t,i.current,D.current)})},200),n&&fe(t)},onWheel:e=>{y?.restorePosition&&(x.current=b),!e.defaultPrevented&&!e.ctrlKey&&!e.metaKey&&e.deltaY<0&&VR(e.nativeEvent,e.currentTarget)&&(pe(),fe(e.currentTarget))},onKeyDown:e=>{y?.restorePosition&&[`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `].includes(e.key)&&(x.current=b);let t=e.target;!e.defaultPrevented&&!e.altKey&&!e.metaKey&&(!e.ctrlKey||e.key===`Home`)&&([`ArrowUp`,`PageUp`,`Home`].includes(e.key)||e.key===` `&&e.shiftKey)&&t instanceof HTMLElement&&!t.isContentEditable&&!t.closest(`input, textarea, select`)&&!(e.key===` `&&t.closest(`button, summary`))&&VR(e.nativeEvent,e.currentTarget)&&(pe(),fe(e.currentTarget))},children:(0,K.jsxs)(`div`,{ref:r,className:`conversation-content`,children:[E?.rerun&&e.onOpenOriginal&&(0,K.jsxs)(`div`,{className:`message-branch-origin`,children:[(0,K.jsxs)(`button`,{type:`button`,onClick:()=>void e.onOpenOriginal(E.rerun.source),children:[(0,K.jsx)(Ae,{"aria-hidden":`true`}),` `,t(`openOriginalConversation`)]}),(0,K.jsx)(`span`,{children:t(`messageRerunWorkspaceHint`)})]}),(T.hasMore||T.error||T.verifying)&&(0,K.jsxs)(`div`,{className:`conversation-history`,children:[T.error&&(0,K.jsx)(`p`,{role:`alert`,children:t(T.error)}),T.error&&T.error!==`historyChanged`&&(0,K.jsx)(`button`,{type:`button`,className:`secondary`,disabled:T.loading,onClick:()=>void T.loadOlder(),children:t(`retryAdmissionCheck`)}),T.loading&&(0,K.jsx)(`p`,{role:`status`,children:t(`historyLoading`)}),T.verifying&&!T.error&&!T.loading&&(0,K.jsx)(`p`,{role:`status`,children:t(`historyVerifying`)}),T.hasMore&&(0,K.jsx)(`span`,{children:t(`historyOmitted`,{count:E?.truncation.entriesOmitted??0})})]}),LR(ie,V&&(!ee||!!de)&&B?.compaction?.state!==`running`,le?.commandId,L,E,e.activityObserved===!1?void 0:de,e.onReviewTurn,e.activityObserved!==!1),V&&e.activityObserved!==!1&&B?.compaction?.state!==`running`&&(0,K.jsxs)(`div`,{className:`conversation-execution-status sr-only`,role:`status`,"aria-live":`polite`,children:[(0,K.jsx)(`span`,{children:se}),ce>0&&(0,K.jsx)(`span`,{children:t(`observedSessionTools`,{count:ce})}),(B?.pendingFollowUps??0)>0&&(0,K.jsx)(`span`,{children:t(`pendingFollowUpsHint`,{count:B.pendingFollowUps})})]})]})}),(l||T.hasNewer)&&ie.length>0&&(0,K.jsx)(`button`,{className:`jump-to-latest`,type:`button`,"aria-label":t(`jumpToLatest`),title:t(`jumpToLatest`),onClick:()=>{let e=n.current;e&&(i.current=!0,u(!1),C(null),T.resetToLatest(),e.scrollTo({top:e.scrollHeight,behavior:`smooth`}),queueMicrotask(()=>{n.current===e&&(Array.from(e.querySelectorAll(`.message-row[tabindex="-1"]`)).reverse().find(e=>!e.closest(`[hidden], details:not([open])`))??e).focus({preventScroll:!0})}))},children:V&&e.activityObserved!==!1?(0,K.jsxs)(`span`,{className:`latest-activity-dots`,"aria-hidden":`true`,children:[(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{})]}):(0,K.jsx)(w,{"aria-hidden":`true`})}),(0,K.jsx)(qL,{items:U.items,viewport:n,enabled:f,onHidden:p,onRequestPreview:U.requestPreview,readingHistory:l||T.hasNewer,onNavigate:oe},N)]})}function UR(){(0,_.useEffect)(()=>{let e=new rf,t=new AbortController,n,r=async r=>{let i=r.data;if(!(r.source!==window||r.origin!==location.origin||i?.source!==`openpi-browser-extension`||i.type!==`connector-hello`||typeof i.bridgeId!=`string`||!/^[\da-f-]{36}$/.test(i.bridgeId)||!tF(i.browser)||n===i.bridgeId)){n=i.bridgeId;try{let r=await e.request(`/api/browser/connections`,{method:`POST`,signal:t.signal,body:JSON.stringify({browser:i.browser,profileId:i.profileId,extensionId:i.extensionId,extensionOrigin:i.extensionOrigin,version:i.version})});!t.signal.aborted&&n===i.bridgeId&&window.postMessage({source:`openpi-browser-ui`,type:`connector-authorize`,...r},location.origin)}catch{n===i.bridgeId&&(n=void 0)}}},i=()=>window.postMessage({source:`openpi-browser-ui`,type:`connector-probe`},location.origin);window.addEventListener(`message`,r),i();let a=setInterval(i,5e3);return()=>{t.abort(),clearInterval(a),window.removeEventListener(`message`,r)}},[])}function WR(e,t){let n=e.trim();if(!n||n.length>16384)return null;let r=/^[a-z][a-z\d+.-]*:\/\//iu.test(n);try{let e=new URL(r?n:`https://${n}`);return!r&&(e.hostname===`localhost`||e.hostname.endsWith(`.localhost`)||e.hostname===`[::1]`||/^127(?:\.\d{1,3}){3}$/u.test(e.hostname))&&(e=new URL(`http://${n}`)),![`http:`,`https:`].includes(e.protocol)||e.username||e.password||e.origin===t?null:e.href}catch{return null}}function GR(){return document.documentElement.dataset.openpiBrowserExtension===`ready`?[...document.querySelectorAll(`iframe[data-openpi-browser-document]`)].map(e=>({id:e.dataset.openpiBrowserPage,document:e.dataset.openpiBrowserDocument,url:e.dataset.openpiBrowserUrl,title:e.dataset.openpiBrowserTitle||``})):[]}function KR(e,t,n){let r=(0,_.useRef)(n),i=(0,_.useRef)(0);r.current=n,(0,_.useEffect)(()=>{if(!e||!t)return;let n=new rf,a=new AbortController,o,s,c,l=e=>window.postMessage({source:`openpi-browser-ui`,...e},location.origin),u=()=>{c?.(),c=void 0,s&&l({type:`control-cancel`,requestId:s}),s=void 0},d=(r,i,o)=>{r===s&&(c?.(),c=void 0,s=void 0,n.request(`/api/browser/control`,{method:`POST`,signal:a.signal,body:JSON.stringify({sessionId:e,sessionPath:t,requestId:r,result:i,error:o,pages:GR()})}).catch(()=>{}))},f=e=>{let t=e.data;e.source===window&&e.origin===location.origin&&t?.source===`openpi-browser-extension`&&(t.type===`connector-hello`?i.current=Date.now():t.type===`control-result`&&d(t.requestId,t.result,t.error))},p=async(e,t)=>{let n=WR(t||``,location.origin);if(!n){d(e,void 0,`Invalid internal browser URL.`);return}let i=new AbortController;c=()=>i.abort();let o=await r.current(n,AbortSignal.any([a.signal,i.signal]));if(a.signal.aborted||s!==e)return;if(!o){d(e,void 0,`The internal browser has reached its page limit.`);return}let l=()=>{let t=document.getElementById(o)?.querySelector(`iframe[data-openpi-browser-document]`),n=t&&GR().find(e=>e.id===t.dataset.openpiBrowserPage);n&&d(e,{root:n.id})},u=new MutationObserver(l);u.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`data-openpi-browser-document`]});let f=setTimeout(()=>d(e,void 0,`The internal page did not bind. Inspect the browser's loading or embedding error.`),1e4);c=()=>{i.abort(),u.disconnect(),clearTimeout(f)},l()},m=async()=>{if(Date.now()-i.current>15e3&&document.documentElement.dataset.openpiBrowserExtension!==`ready`){u(),a.signal.aborted||(o=setTimeout(()=>void m(),1e3));return}try{let{pending:r}=await n.request(`/api/browser/control`,{method:`POST`,signal:a.signal,body:JSON.stringify({sessionId:e,sessionPath:t,pages:GR()})});s&&s!==r?.requestId&&u(),r&&!r.running&&r.request&&!s&&(s=r.requestId,r.request.operation===`open`?p(r.requestId,r.request.url).catch(()=>d(r.requestId,void 0,`The embedded browser could not open.`)):r.page?l({type:`control`,id:r.page.id,document:r.page.document,requestId:r.requestId,request:r.request}):d(r.requestId,void 0,`The embedded page is unavailable.`))}catch{u()}a.signal.aborted||(o=setTimeout(()=>void m(),250))};return window.addEventListener(`message`,f),m(),()=>{clearTimeout(o),a.abort(),u(),window.removeEventListener(`message`,f)}},[e,t])}function qR({usage:e,workspace:t,sessionId:n}){let{t:r,i18n:i}=cr(),[a,o]=(0,_.useState)(!1);if(!e)return null;let s=e.context,c=e=>new Intl.NumberFormat(i.resolvedLanguage).format(e),l=e=>new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:0}).format(e).toLowerCase(),u=s?.percent==null?r(`usageUnknown`):`${Math.round(s.percent)}%`,d=s?.percent==null?r(`usageUnknown`):`${new Intl.NumberFormat(i.resolvedLanguage,{maximumFractionDigits:1}).format(s.percent)}%`,f=s?l(s.contextWindow):r(`usageUnknown`);return(0,K.jsx)(`div`,{className:`session-usage`,children:(0,K.jsx)(gd,{isOpen:a,onOpenChange:o,placement:`below`,alignment:`end`,width:`min(360px, calc(100vw - 24px))`,label:r(`sessionUsage`),isModal:!1,hasCloseButton:!1,content:(0,K.jsxs)(`div`,{className:`session-usage-details`,children:[(0,K.jsxs)(`div`,{className:`usage-details-heading`,children:[(0,K.jsx)(`h2`,{children:r(`sessionOverview`)}),(0,K.jsx)(`button`,{className:`icon-button`,type:`button`,"aria-label":r(`close`),onClick:()=>o(!1),children:(0,K.jsx)(Lt,{"aria-hidden":`true`})})]}),(0,K.jsxs)(`section`,{className:`usage-section`,children:[(0,K.jsxs)(`div`,{className:`usage-context-heading`,children:[(0,K.jsx)(`h3`,{children:r(`usageContextLabel`)}),(0,K.jsx)(`span`,{children:d})]}),(0,K.jsxs)(`p`,{className:`usage-context-value`,children:[(0,K.jsx)(`strong`,{children:s?.tokens==null?r(`usageUnknown`):c(s.tokens)}),s&&(0,K.jsxs)(`span`,{children:[` / `,c(s.contextWindow),` tokens`]})]}),s?.percent!=null&&(0,K.jsx)(`progress`,{value:Math.max(0,Math.min(100,s.percent)),max:100,"aria-label":r(`sessionContextUsage`)}),(0,K.jsx)(`p`,{className:`usage-help`,children:r(`usageContextHelp`)})]}),(0,K.jsxs)(`section`,{className:`usage-section`,children:[(0,K.jsx)(`h3`,{children:r(`usageSessionTotals`)}),(0,K.jsxs)(`dl`,{className:`usage-metrics`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:r(`usageInputLabel`)}),(0,K.jsx)(`dd`,{children:c(e.input)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:r(`usageOutputLabel`)}),(0,K.jsx)(`dd`,{children:c(e.output)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:r(`usageTotalLabel`)}),(0,K.jsx)(`dd`,{children:c(e.total)})]})]}),(0,K.jsx)(`p`,{className:`usage-help`,children:r(`usageTotalsHelp`)})]}),t&&(0,K.jsxs)(`dl`,{className:`usage-workspace`,children:[(0,K.jsx)(`dt`,{children:r(`usageWorkspaceLabel`)}),(0,K.jsx)(`dd`,{children:t})]}),n&&(0,K.jsxs)(`details`,{className:`usage-identity`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(`span`,{children:r(`usageSessionId`)}),(0,K.jsx)(L,{"aria-hidden":`true`})]}),(0,K.jsx)(`code`,{children:n})]})]}),children:t=>(0,K.jsxs)(`button`,{...t,className:`session-usage-trigger`,type:`button`,"aria-label":r(`usageOpenDetails`,{input:l(e.input),output:l(e.output),percent:u,capacity:f}),children:[(0,K.jsxs)(`span`,{className:`usage-stat`,title:`${r(`sessionInputTokens`)}: ${c(e.input)}`,children:[(0,K.jsx)(k,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:l(e.input)})]}),(0,K.jsxs)(`span`,{className:`usage-stat`,title:`${r(`sessionOutputTokens`)}: ${c(e.output)}`,children:[(0,K.jsx)(w,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:l(e.output)})]}),(0,K.jsxs)(`span`,{className:`usage-stat`,title:`${r(`sessionContextUsage`)}: ${d}`,children:[(0,K.jsx)(ke,{"aria-hidden":`true`}),(0,K.jsxs)(`span`,{children:[u,s&&(0,K.jsxs)(`span`,{className:`usage-capacity`,children:[` / `,f]})]})]})]})})})}function JR(e,t){return new Promise((n,r)=>{let i=new FileReader,a=e=>{t.removeEventListener(`abort`,o),e?r(e):typeof i.result==`string`?n(i.result.slice(i.result.indexOf(`,`)+1)):r(Error(`File read failed`))},o=()=>{i.abort(),a(new DOMException(`File read cancelled`,`AbortError`))};i.onload=()=>a(),i.onerror=()=>a(Error(`File read failed`)),t.addEventListener(`abort`,o,{once:!0}),t.aborted?o():i.readAsDataURL(e)})}function YR({name:e,kind:t=`file`,expanded:n=!1}){let r=t===`directory`?`folder`:t===`symlink`?`link`:/\.(?:md|markdown)$/iu.test(e)?`markdown`:/\.(?:csv|tsv|xlsx?)$/iu.test(e)?`sheet`:/\.(?:png|jpe?g|gif|webp|svg|bmp|ico)$/iu.test(e)?`image`:/\.(?:pdf|docx?|pptx?)$/iu.test(e)?`document`:/\.(?:[cm]?[jt]sx?|json|html?|css|py|rs|go|sh|ya?ml|toml|xml)$/iu.test(e)?`code`:`file`;return(0,K.jsx)(r===`folder`?n?G:De:r===`link`?Re:r===`sheet`?yt:r===`image`?be:r===`markdown`||r===`document`?Se:r===`code`?ve:Ce,{className:`file-icon file-icon-${r}`,"aria-hidden":`true`})}function XR({sessionId:e,sessionPath:t,cwd:n,canWrite:r,active:i,selected:a,onSelect:o,dropTarget:s,onShowTree:c,onRemoved:l}){let{t:u}=cr(),d=(0,_.useContext)(fk),f=wk(),p=(0,_.useMemo)(()=>new rf,[]),[m,h]=(0,_.useState)(f?.files?.query??``),[g,v]=(0,_.useState)(f?.files?.expanded??[`.`]),[y,b]=(0,_.useState)({}),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(null),[T,E]=(0,_.useState)(!1),[D,O]=(0,_.useState)(0),[k,A]=(0,_.useState)(a.includes(`/`)?a.slice(0,a.lastIndexOf(`/`)):`.`),[j,M]=(0,_.useState)(null),[N,P]=(0,_.useState)(``),[F,I]=(0,_.useState)(null),[R,z]=(0,_.useState)(!1),[B,V]=(0,_.useState)(!1),[H,te]=(0,_.useState)([]),[ne,re]=(0,_.useState)(!1),[ie,ae]=(0,_.useState)([]),[U,oe]=(0,_.useState)(null),[se,ce]=(0,_.useState)(`.`),[le,ue]=(0,_.useState)(``),[de,fe]=(0,_.useState)([]),[pe,me]=(0,_.useState)(!1),[he,ge]=(0,_.useState)([]),[_e,ve]=(0,_.useState)(0),[ye,be]=(0,_.useState)(!1),[Se,Ce]=(0,_.useState)(),we=(0,_.useRef)(0),[G,De]=(0,_.useState)([]),[Oe,ke]=(0,_.useState)(!1),[Ae,je]=(0,_.useState)(``),Me=(0,_.useRef)(null),Ne=(0,_.useRef)(null),Pe=(0,_.useRef)(null),Fe=(0,_.useRef)(null),Ie=(0,_.useRef)(null),Le=(0,_.useRef)(!1),Re=(0,_.useRef)(0),Be=(0,_.useRef)(null),Ve=(0,_.useRef)(void 0),He=JSON.stringify([e,t,n]),Ue=(0,_.useRef)(He);Ue.current=He;let We=(0,_.useRef)(r);We.current=r;let Ge=(0,_.useRef)(null);(0,_.useEffect)(()=>(Ue.current=He,()=>{Ue.current=``,Ge.current?.abort(),clearTimeout(Ve.current)}),[He]),(0,_.useEffect)(()=>{Ne.current?.setAttribute(`webkitdirectory`,``)},[]),(0,_.useEffect)(()=>{if(!pe||!i)return;we.current++;let n=new AbortController;return be(!0),p.workspaceTrash(e,t,n.signal).then(r=>{!n.signal.aborted&&r.sessionId===e&&r.sessionPath===t&&(ge(r.entries),ve(r.unavailable??0),Ce(r.nextCursor))}).catch(e=>{n.signal.aborted||(z(!0),I(e instanceof Error?e.message:u(`filesReadFailed`)))}).finally(()=>{n.signal.aborted||be(!1)}),()=>n.abort()},[p,e,t,i,pe,D,u]),(0,_.useEffect)(()=>{U&&(Fe.current?.focus(),Fe.current?.select())},[U]),(0,_.useEffect)(()=>{j&&Pe.current?.focus()},[j]);let Ke=(0,_.useRef)(null),qe=(0,_.useRef)(f?.files?.treeScroll??0);(0,_.useLayoutEffect)(()=>{f?.files&&Object.assign(f.files,{query:m,expanded:g})},[f,m,g]),(0,_.useLayoutEffect)(()=>{!i||!(x||y[`.`])||qe.current!==null&&Ke.current&&(Ke.current.scrollTop=qe.current,qe.current=null)},[i,x,y]);let Je=(0,_.useRef)(y);Je.current=y;let Ye=(0,_.useRef)(x);Ye.current=x;let Xe=(0,_.useRef)(``),Ze=(0,_.useRef)(null),Qe=(0,_.useRef)(new Set),$e=(0,_.useRef)(!1),[et,tt]=(0,_.useState)(!1),nt=!!m.trim();(0,_.useLayoutEffect)(()=>{let e=Be.current;if(!e||!i)return;let t=[...Ke.current?.querySelectorAll(`[data-file-row]`)??[]].find(t=>t.dataset.fileRow===e);t&&(t.focus({preventScroll:!0}),Be.current=null)});let rt=e=>e instanceof tf&&e.code===`ARTIFACT_EXISTS`?u(`filesNameExists`):e instanceof Error?e.message:u(`filesMutationFailed`),it=e=>{h(``);let t=e.path.split(`/`),n=e.kind===`directory`?t.length:t.length-1;v(e=>[...new Set([...e,`.`,...t.slice(0,n).map((e,n)=>t.slice(0,n+1).join(`/`))])]),Be.current=e.path,O(e=>e+1),e.kind===`file`&&(e.bytes??0)<=20971520&&(o(e.path),d?.open(encodeURI(e.path)))},at=()=>{Le.current||(M(null),I(null),Ie.current?.focus({preventScroll:!0}))},ot=async n=>{if(n.preventDefault(),!j||!We.current||Le.current)return;if(!N||N===`.`||N===`..`||/[\\/\u0000-\u001f\u007f]/u.test(N)){z(!0),I(u(`filesNameInvalid`)),Pe.current?.focus();return}Le.current=!0,V(!0),I(null);let r=He;try{let n=await p.mutateWorkspaceFile(e,t,{kind:j,directory:k,name:N});if(Ue.current!==r||n.sessionId!==e||n.sessionPath!==t)return;M(null),P(``),z(!1),I(u(`filesCreated`,{path:n.path})),it(n)}catch(e){Ue.current===r&&(z(!0),I(rt(e)),Pe.current?.focus())}finally{Ue.current===r&&(Le.current=!1,V(!1))}},st=async n=>{if(!We.current||Le.current)return;let r=He;Le.current=!0,V(!0);let i=new AbortController;Ge.current=i;let a=(e,t)=>te(n=>n.map(n=>n.id===e.id?{...n,...t}:n));try{for(let o of n){if(Ue.current!==r)return;if(!We.current){a(o,{state:`error`,message:u(`filesWriteUnavailable`)});continue}if(!(!o.file&&o.kind!==`directory`)){a(o,{state:`running`,message:void 0});try{if(o.kind===`directory`){try{await p.mutateWorkspaceFile(e,t,{kind:`create-directory`,directory:o.directory,name:o.name})}catch(n){if(!(n instanceof tf)||n.code!==`ARTIFACT_EXISTS`)throw n;await p.workspaceFiles(e,t,[o.directory===`.`?``:o.directory,o.name].filter(Boolean).join(`/`),``,i.signal)}if(Ue.current!==r)return;a(o,{state:`done`,message:u(`filesImported`)}),O(e=>e+1);continue}if(!o.file)continue;if(o.file.size>52428800)throw Error(u(`filesImportTooLarge`));let n=await JR(o.file,i.signal);if(Ue.current!==r)return;if(!We.current){a(o,{state:`error`,message:u(`filesWriteUnavailable`)});continue}let s=await p.mutateWorkspaceFile(e,t,{kind:`import-file`,directory:o.directory,name:o.name,data:n,...o.createParents?{createParents:!0}:{}});if(Ue.current!==r||s.sessionId!==e||s.sessionPath!==t)return;a(o,{state:`done`,file:void 0,message:(s.bytes??0)>20971520?u(`filesImportedNoPreview`):u(`filesImported`)}),it(s)}catch(e){if(Ue.current!==r)return;a(o,{state:`error`,message:rt(e)})}}}}finally{Ge.current===i&&(Ge.current=null),Ue.current===r&&(Le.current=!1,V(!1))}},ct=(e,t=[],n=new Map,r=[])=>{if(!We.current||Le.current)return;if(e.length+r.length>2e3){z(!0),I(u(`filesImportFolderLimit`));return}c(!0);let i=[...[...new Set(r)].sort((e,t)=>e.split(`/`).length-t.split(`/`).length).map(e=>({id:++Re.current,name:e.split(`/`).at(-1),directory:[k===`.`?``:k,...e.split(`/`).slice(0,-1)].filter(Boolean).join(`/`)||`.`,kind:`directory`,state:`pending`})),...e.map(e=>{let t=n.get(e)??e.webkitRelativePath;return{id:++Re.current,name:e.name,directory:t?[k===`.`?``:k,...t.split(`/`).slice(0,-1)].filter(Boolean).join(`/`)||`.`:k,createParents:!!t,file:e,state:`pending`}})];te(e=>[...e,...t.map(e=>({id:++Re.current,name:e,directory:k,state:`error`,message:u(`filesImportDirectoryUnsupported`)})),...i]),st(i)},lt=async(n,r)=>{if(!We.current||Le.current)return;let i=He,s=r.filter(e=>!r.some(t=>t.kind===`directory`&&e.path.startsWith(`${t.path}/`)));Le.current=!0,V(!0),fe([]);let c=[],f=new Set;try{for(let r of s){if(Ue.current!==i||!We.current)return;try{if(!r.identity)throw Error(u(`filesRefreshBeforeOrganizing`));let s=await p.mutateWorkspaceFile(e,t,n===`trash`?{kind:n,path:r.path,identity:r.identity}:{kind:n,path:r.path,identity:r.identity,directory:se,name:U?.rename?le:r.name});if(Ue.current!==i||s.sessionId!==e||s.sessionPath!==t)return;if(f.add(r.path),s.trashed&&c.push(s.trashed),s.moved&&Lk(e,t,s.moved.from,s.moved.to),r.kind===`directory`){let e=e=>e===r.path||e.startsWith(`${r.path}/`);if(v(t=>n===`trash`?t.filter(t=>!e(t)):t.map(t=>e(t)?`${s.path}${t.slice(r.path.length)}`:t)),A(t=>e(t)?n===`move`?`${s.path}${t.slice(r.path.length)}`:r.path.split(`/`).slice(0,-1).join(`/`)||`.`:t),n===`move`&&e(a)){let e=`${s.path}${a.slice(r.path.length)}`;o(e),d?.open(encodeURI(e))}}n===`move`&&it(s),fe(e=>[...e,{path:r.path}])}catch(e){if(Ue.current!==i)return;fe(t=>[...t,{path:r.path,error:rt(e)}])}}De(c),n===`trash`&&l([...f]),ae(e=>e.filter(e=>![...f].some(t=>t===e.path||e.path.startsWith(`${t}/`)))),oe(null),O(e=>e+1)}finally{Ue.current===i&&(Le.current=!1,V(!1))}},ut=async n=>{if(!We.current||Le.current)return;let r=He;Le.current=!0,V(!0),fe([]);try{for(let i of n){if(Ue.current!==r||!We.current)return;try{let n=await p.mutateWorkspaceFile(e,t,{kind:`restore`,id:i.id,identity:i.identity});if(Ue.current!==r||n.sessionId!==e||n.sessionPath!==t)return;De(e=>e.filter(e=>e.id!==i.id)),ge(e=>e.filter(e=>e.id!==i.id)),fe(e=>[...e,{path:i.path}]),it(n)}catch(e){if(Ue.current!==r)return;fe(t=>[...t,{path:i.path,error:rt(e)}])}}O(e=>e+1)}finally{Ue.current===r&&(Le.current=!1,V(!1))}},ft=async()=>{if(!Se||ye)return;let n=we.current,r=He;be(!0);try{let i=await p.workspaceTrash(e,t,void 0,Se);if(n!==we.current||Ue.current!==r||i.sessionId!==e||i.sessionPath!==t)return;ge(e=>[...new Map([...e,...i.entries].map(e=>[e.id,e])).values()]),ve(e=>e+(i.unavailable??0)),Ce(i.nextCursor)}catch(e){n===we.current&&Ue.current===r&&(z(!0),I(rt(e)))}finally{n===we.current&&Ue.current===r&&be(!1)}},pt=e=>ae(t=>t.some(t=>t.path===e.path)?t.filter(t=>t.path!==e.path):[...t,e]),mt=(e,t=!1)=>{oe({entries:e,rename:t});let n=e[0]?.path??``;ce(t?n.split(`/`).slice(0,-1).join(`/`)||`.`:k),ue(e[0]?.name??``),I(null)},gt=(0,_.useRef)(ct);gt.current=ct,(0,_.useEffect)(()=>{let e=s.current;if(!e)return;let t=e=>{if(!e.dataTransfer?.types.includes(`Files`))return;e.preventDefault();let t=We.current&&!Le.current;e.dataTransfer.dropEffect=t?`copy`:`none`,ke(t)},n=t=>{(!(t.relatedTarget instanceof Node)||!e.contains(t.relatedTarget))&&ke(!1)},r=e=>{let t=e.dataTransfer;if(!t?.types.includes(`Files`)||(e.preventDefault(),ke(!1),!We.current||Le.current))return;let n=[],r=[],i=[];for(let e of t.items){if(e.kind!==`file`)continue;let t=e.webkitGetAsEntry?.();if(t?.isDirectory&&`createReader`in t)i.push(t);else if(t?.isDirectory)r.push(t.name);else{let t=e.getAsFile();t&&n.push(t)}}if(i.length){let e=Ue.current,t=new Map,a=[],o=0,s=async(r,i)=>{if(Ue.current!==e||!We.current)throw new DOMException(`Import cancelled`,`AbortError`);if(++o>2e3||i.split(`/`).length>64)throw Error(u(`filesImportFolderLimit`));let c=i?`${i}/${r.name}`:r.name;if(r.isDirectory){a.push(c);let e=r.createReader();for(;;){let t=await new Promise((t,n)=>e.readEntries(t,n));if(!t.length)break;for(let e of t)await s(e,c)}}else if(r.isFile){let e=await new Promise((e,t)=>r.file(e,t));t.set(e,c),n.push(e)}};Le.current=!0,V(!0),(async()=>{try{for(let e of i)await s(e,``);if(Ue.current!==e||!We.current)return;Le.current=!1,V(!1),gt.current(n,r,t,a)}catch(t){Ue.current===e&&(z(!0),I(t instanceof Error?t.message:u(`filesMutationFailed`)))}finally{Ue.current===e&&!Ge.current&&(Le.current=!1,V(!1))}})();return}gt.current(t.items.length?n:[...t.files],r)};return e.addEventListener(`dragover`,t),e.addEventListener(`dragleave`,n),e.addEventListener(`drop`,r),()=>{e.removeEventListener(`dragover`,t),e.removeEventListener(`dragleave`,n),e.removeEventListener(`drop`,r)}},[s,u]);let _t=async(e,t)=>{let r=He,i=n.includes(`\\`)?`\\`:`/`,a=await wd(t?`${n.replace(/[\\/]$/u,``)}${i}${e.split(`/`).join(i)}`:e);Ue.current===r&&(clearTimeout(Ve.current),je(u(a?`filesPathCopied`:`copyFailed`,{path:e})),Ve.current=setTimeout(()=>je(``),3e3))};(0,_.useEffect)(()=>{if(!i)return;let n=new AbortController;Ze.current=n;let r;Xe.current!==m.trim()&&(Xe.current=m.trim(),Ye.current=null,S(null)),r=setTimeout(async()=>{if(document.visibilityState!==`hidden`){E(!0);try{let r=async(r,i,a)=>{let o=await p.workspaceFiles(e,t,r,i,n.signal);for(o.nextCursor&&Qe.current.add(o.nextCursor);o.nextCursor&&o.entries.length{document.visibilityState!==`hidden`&&O(e=>e+1)};return window.addEventListener(`focus`,a),document.addEventListener(`visibilitychange`,a),()=>{n.abort(),clearTimeout(r),window.removeEventListener(`focus`,a),document.removeEventListener(`visibilitychange`,a);for(let e of Qe.current)p.releaseFileListing(e).catch(()=>void 0);Qe.current.clear(),$e.current=!1,tt(!1)}},[i,p,g,m,nt,e,t,D,u]);let vt=e=>v(t=>t.includes(e)?t.filter(t=>t!==e&&!t.startsWith(`${e}/`)):[...t,e]),yt=async n=>{let r=nt?Ye.current:Je.current[n],i=Ze.current;if(!(!r?.nextCursor||!i||i.signal.aborted||$e.current||T)){$e.current=!0,tt(!0),w(null);try{let a=await p.workspaceFiles(e,t,n,nt?m.trim():``,i.signal,r.nextCursor);if(Qe.current.delete(r.nextCursor),a.nextCursor&&Qe.current.add(a.nextCursor),i.signal.aborted)return;let o=[...new Map([...r.entries,...a.entries].map(e=>[e.path,e])).values()],s={...a,entries:o};nt?S(s):b(e=>({...e,[n]:s}))}catch(e){i.signal.aborted||w(e instanceof Error?e.message:u(`filesReadFailed`))}finally{i.signal.aborted||($e.current=!1,tt(!1))}}},bt=(e,t)=>t?.nextCursor?(0,K.jsxs)(`li`,{className:`file-tree-more`,children:[(0,K.jsx)(`button`,{type:`button`,disabled:T||et,onClick:()=>void yt(e),children:u(et?`loading`:`filesLoadMore`)}),(0,K.jsx)(`small`,{children:u(`filesLoaded`,{count:t.entries.length})})]}):null,xt=e=>{let t=[...Ke.current?.querySelectorAll(`button[data-file-row]:not(:disabled)`)??[]],n=t.indexOf(document.activeElement),r=t[n];if(!r)return;let i;if(e.key===`ArrowDown`)i=t[Math.min(n+1,t.length-1)];else if(e.key===`ArrowUp`)i=t[Math.max(n-1,0)];else if(e.key===`Home`)i=t[0];else if(e.key===`End`)i=t.at(-1);else if(e.key===`ArrowRight`&&r.getAttribute(`aria-expanded`)===`false`)r.click();else if(e.key===`ArrowLeft`)r.getAttribute(`aria-expanded`)===`true`?r.click():i=t.find(e=>e.dataset.fileRow===r.dataset.fileRow?.split(`/`).slice(0,-1).join(`/`));else return;e.preventDefault(),i?.focus()},St=(e,t=0)=>e.map(e=>{let n=e.kind===`directory`,i=g.includes(e.path),s=r&&!!e.identity&&!e.path.split(`/`).some(e=>[`.git`,`.pi`,`.openpi-trash`].includes(e.toLowerCase()))&&(n||e.kind===`file`);return(0,K.jsxs)(`li`,{children:[(0,K.jsxs)(`div`,{className:`file-tree-item`,children:[ne&&(0,K.jsx)(`input`,{type:`checkbox`,className:`file-tree-check`,"aria-label":u(`filesSelectItem`,{name:e.name}),checked:ie.some(t=>t.path===e.path),disabled:!s||B,onChange:()=>pt(e)}),(0,K.jsxs)(`button`,{type:`button`,"data-file-row":e.path,className:`file-tree-row`,style:{paddingInlineStart:10+t*16},"aria-expanded":n?i:void 0,"aria-current":!n&&a===e.path?`true`:void 0,disabled:e.kind===`symlink`||e.kind===`other`,title:e.kind===`symlink`?u(`filesSymlink`):e.path,onClick:t=>{if(s&&(t.metaKey||t.ctrlKey)){re(!0),pt(e);return}n?(A(e.path),nt?(h(``),v([`.`,...e.path.split(`/`).map((e,t,n)=>n.slice(0,t+1).join(`/`))])):vt(e.path)):(A(e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)):`.`),o(e.path),d?.open(encodeURI(e.path),void 0,t.currentTarget))},children:[n?i?(0,K.jsx)(L,{className:`file-chevron`,"aria-hidden":`true`}):(0,K.jsx)(ee,{className:`file-chevron`,"aria-hidden":`true`}):(0,K.jsx)(`span`,{className:`file-chevron`}),(0,K.jsx)(YR,{name:e.name,kind:e.kind,expanded:i}),(0,K.jsxs)(`span`,{className:`file-tree-name`,children:[e.name,nt&&(0,K.jsx)(`small`,{children:e.path})]})]}),(0,K.jsx)(jA,{button:{label:u(`filesPathActions`,{name:e.name}),icon:(0,K.jsx)(W,{"aria-hidden":`true`}),isIconOnly:!0,size:`sm`,variant:`ghost`,className:`file-path-actions`},items:[{label:u(`filesCopyRelativePath`),onClick:()=>void _t(e.path,!1)},{label:u(`filesCopyAbsolutePath`),onClick:()=>void _t(e.path,!0)},{label:u(`filesRename`),isDisabled:!s||B,onClick:()=>mt([e],!0)},{label:u(`filesMove`),isDisabled:!s||B,onClick:()=>mt([e])},{label:u(`filesTrashAction`),isDisabled:!s||B,onClick:()=>void lt(`trash`,[e])}],menuWidth:200,alignment:`end`,hasChevron:!1})]}),!nt&&n&&i&&(0,K.jsxs)(`ul`,{children:[y[e.path]?St(y[e.path].entries,t+1):(0,K.jsx)(`li`,{className:`file-tree-note`,children:u(`loading`)}),bt(e.path,y[e.path])]})]},e.path)});return(0,K.jsxs)(`aside`,{className:`file-explorer`,"aria-label":u(`filesExplorer`),"data-drag-over":Oe||void 0,children:[(0,K.jsxs)(`div`,{className:`file-search`,children:[(0,K.jsx)(ht,{"aria-hidden":`true`}),(0,K.jsx)(`input`,{value:m,onChange:e=>h(e.currentTarget.value.slice(0,200)),placeholder:u(`filesSearch`),"aria-label":u(`filesSearch`)}),(0,K.jsx)(`span`,{className:`file-search-progress`,"aria-hidden":`true`,"data-loading":T||void 0}),(0,K.jsx)(`button`,{type:`button`,className:`icon-button`,"aria-label":u(`refreshFiles`),title:u(`refreshFiles`),onClick:()=>O(e=>e+1),disabled:T,children:(0,K.jsx)(dt,{"aria-hidden":`true`})})]}),(0,K.jsxs)(`div`,{className:`file-create-toolbar`,children:[(0,K.jsxs)(`fieldset`,{className:`file-write-actions`,"aria-label":u(`filesWorkspaceActions`),children:[(0,K.jsx)(jA,{button:{ref:Ie,label:u(`filesCreateMenu`),variant:`ghost`,className:`file-toolbar-button`,tooltip:r&&!B?u(`filesCreateMenu`):void 0,isDisabled:!r||B},items:[`create-file`,`create-directory`].map(e=>({label:u(e===`create-file`?`filesNewFile`:`filesNewDirectory`),icon:e===`create-file`?(0,K.jsx)(xe,{"aria-hidden":`true`}):(0,K.jsx)(Ee,{"aria-hidden":`true`}),isDisabled:!r||B,onClick:()=>{M(e),P(``),I(null)}})),menuWidth:190}),(0,K.jsx)(jA,{button:{label:u(`filesImportMenu`),variant:`ghost`,className:`file-toolbar-button`,tooltip:r&&!B?u(`filesImportMenu`):void 0,isDisabled:!r||B},items:[{label:u(`filesImport`),icon:(0,K.jsx)(Mt,{"aria-hidden":`true`}),isDisabled:!r||B,onClick:()=>Me.current?.click()},{label:u(`filesImportFolder`),icon:(0,K.jsx)(Te,{"aria-hidden":`true`}),isDisabled:!r||B,onClick:()=>Ne.current?.click()}],menuWidth:190}),(0,K.jsx)(`input`,{ref:Me,type:`file`,multiple:!0,hidden:!0,"aria-label":u(`filesImportChoose`),onChange:e=>{ct([...e.currentTarget.files??[]]),e.currentTarget.value=``}}),(0,K.jsx)(`input`,{ref:Ne,type:`file`,multiple:!0,hidden:!0,"aria-label":u(`filesImportFolderChoose`),onChange:e=>{ct([...e.currentTarget.files??[]]),e.currentTarget.value=``}}),(0,K.jsxs)(jA,{button:{label:u(`filesMoreMenu`),variant:`ghost`,className:`file-toolbar-button`,tooltip:u(`filesMoreMenu`)},menuWidth:210,children:[(0,K.jsx)(XA,{label:u(`filesSelectMultiple`),icon:(0,K.jsx)(ze,{"aria-hidden":`true`}),value:ne,isDisabled:!r||B,hasCloseOnSelect:!0,onChange:e=>{re(e),ae([])}}),(0,K.jsx)(XA,{label:u(`filesTrash`),icon:(0,K.jsx)(kt,{"aria-hidden":`true`}),value:pe,hasCloseOnSelect:!0,onChange:me})]})]}),(0,K.jsxs)(`p`,{className:`file-write-directory`,title:k,children:[(0,K.jsxs)(`span`,{children:[u(`filesTargetDirectory`),`:`,` `,k===`.`?u(`filesWorkspaceRoot`):k]}),k!==`.`&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>A(`.`),children:u(`filesWorkspaceRoot`)})]})]}),ne&&(0,K.jsxs)(`div`,{className:`file-organization-bar`,children:[(0,K.jsx)(`span`,{children:u(`filesSelectedCount`,{count:ie.length})}),(0,K.jsx)(`button`,{type:`button`,disabled:!ie.length||B||!r,onClick:()=>mt(ie),children:u(`filesMove`)}),(0,K.jsx)(`button`,{type:`button`,disabled:!ie.length||B||!r,onClick:()=>void lt(`trash`,ie),children:u(`filesTrashAction`)})]}),U&&(0,K.jsxs)(`form`,{className:`file-create-form`,onSubmit:e=>{e.preventDefault(),(!U.rename||le.trim())&<(`move`,U.entries)},children:[(0,K.jsxs)(`label`,{children:[u(U.rename?`filesRename`:`filesMoveDestination`),(0,K.jsx)(`input`,{ref:Fe,value:U.rename?le:se,"aria-label":u(U.rename?`filesNewName`:`filesMoveDestination`),disabled:B,onChange:e=>U.rename?ue(e.currentTarget.value):ce(e.currentTarget.value)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`button`,{type:`submit`,disabled:B||!r,children:u(U.rename?`filesRename`:`filesMove`)}),(0,K.jsx)(`button`,{type:`button`,disabled:B,onClick:()=>oe(null),children:u(`cancel`)})]})]}),de.length>0&&(0,K.jsxs)(`div`,{className:`file-import-results`,children:[(0,K.jsx)(`ol`,{"aria-label":u(`filesOrganizationResults`),"aria-live":`polite`,children:de.map(e=>(0,K.jsxs)(`li`,{children:[(0,K.jsx)(`span`,{children:e.path}),(0,K.jsx)(`small`,{role:e.error?`alert`:void 0,children:e.error??u(`filesOperationDone`)})]},e.path))}),G.length>0&&(0,K.jsx)(`button`,{type:`button`,disabled:B||!r,onClick:()=>void ut(G),children:u(`filesUndoTrash`)})]}),pe&&(0,K.jsxs)(`section`,{className:`file-trash-list`,"aria-label":u(`filesTrash`),children:[(0,K.jsx)(`p`,{children:u(`filesTrashDetail`)}),_e>0&&(0,K.jsx)(`p`,{role:`alert`,children:u(`filesTrashUnavailable`,{count:_e})}),ye&&he.length===0?(0,K.jsx)(`p`,{children:u(`loading`)}):he.length===0?(0,K.jsx)(`p`,{children:u(`filesTrashEmpty`)}):(0,K.jsx)(`ul`,{children:he.map(e=>(0,K.jsxs)(`li`,{children:[(0,K.jsx)(`span`,{title:e.path,children:e.path}),(0,K.jsx)(`button`,{type:`button`,disabled:!r||B,"aria-label":u(`filesRestoreItem`,{name:e.path}),onClick:()=>void ut([e]),children:u(`filesRestore`)})]},e.id))}),Se&&(0,K.jsx)(`button`,{type:`button`,disabled:ye,onClick:()=>void ft(),children:u(`filesLoadMore`)})]}),j&&(0,K.jsxs)(`form`,{className:`file-create-form`,onSubmit:e=>void ot(e),onKeyDown:e=>{e.key===`Escape`&&!e.nativeEvent.isComposing&&(e.preventDefault(),e.stopPropagation(),at())},children:[(0,K.jsxs)(`label`,{children:[u(j===`create-file`?`filesFileName`:`filesDirectoryName`),(0,K.jsx)(`input`,{ref:Pe,value:N,maxLength:255,disabled:B,"aria-invalid":!!(F&&R),onChange:e=>P(e.currentTarget.value)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`button`,{type:`submit`,disabled:!r||B,children:u(B?`filesCreating`:`filesCreate`)}),(0,K.jsx)(`button`,{type:`button`,disabled:B,onClick:at,children:u(`cancel`)})]})]}),F&&(0,K.jsx)(`p`,{className:`file-tree-note${R?` evidence-warning`:``}`,role:R?`alert`:`status`,children:F}),H.length>0&&(0,K.jsxs)(`div`,{className:`file-import-results`,children:[(0,K.jsx)(`p`,{children:u(`filesImportLimit`)}),(0,K.jsx)(`ol`,{"aria-label":u(`filesImportResults`),"aria-live":`polite`,children:H.map(e=>(0,K.jsxs)(`li`,{"data-import-state":e.state,children:[(0,K.jsx)(`span`,{title:`${e.directory}/${e.name}`,children:e.name}),(0,K.jsx)(`small`,{children:e.message??u(e.state===`running`?`filesImporting`:`filesImportPending`)}),e.state===`error`&&(e.file||e.kind===`directory`)&&(0,K.jsx)(`button`,{type:`button`,disabled:!r||B,onClick:()=>void st([e]),children:u(`filesRetryImport`)})]},e.id))}),(0,K.jsx)(`button`,{type:`button`,disabled:B,onClick:()=>te(e=>e.filter(e=>e.state!==`done`)),children:u(`filesClearImported`)})]}),(0,K.jsx)(`span`,{className:`sr-only`,role:`status`,children:Ae}),C&&(0,K.jsx)(`p`,{className:`file-tree-note evidence-warning`,role:`alert`,children:C}),(0,K.jsxs)(`section`,{className:`file-tree`,"aria-label":u(`filesExplorer`),ref:Ke,onKeyDown:xt,onScroll:e=>{f?.files&&(f.files.treeScroll=e.currentTarget.scrollTop)},"aria-busy":T,children:[(0,K.jsxs)(`ul`,{children:[St(nt?x?.entries??[]:y[`.`]?.entries??[]),bt(`.`,nt?x:y[`.`])]}),(nt?x?.truncated:y[`.`]?.truncated)&&(0,K.jsx)(`p`,{className:`file-tree-note`,children:u(`filesTruncated`)}),!T&&!C&&(nt?x?.entries.length===0:y[`.`]?.entries.length===0)&&(0,K.jsx)(`p`,{className:`file-tree-note`,children:u(nt?`filesNoMatches`:`filesEmpty`)})]})]})}function ZR({sessionId:e,sessionPath:t,cwd:n,active:r,canWrite:i=!0}){let{t:a}=cr(),o=wk(),[s,c]=(0,_.useState)(o?.files?.selected??``),[l,u]=(0,_.useState)(o?.files?.treeVisible??!0),d=(0,_.useRef)(null),f=(0,_.useRef)(null);return(0,_.useLayoutEffect)(()=>{o&&(o.files={query:``,expanded:[`.`],treeScroll:0,...o.files,selected:s,treeVisible:l})},[o,s,l]),(0,K.jsx)(`div`,{ref:d,className:`files-workspace`,"data-tree-visible":l,"data-preview-open":!!s,children:(0,K.jsxs)(Bk,{ref:f,sessionId:e,sessionPath:t,embedded:!0,active:r,onClose:()=>{c(``),u(!0)},children:[(0,K.jsx)(Cd,{content:a(l?`filesHideTree`:`filesShowTree`),placement:`below`,children:(0,K.jsx)(`button`,{type:`button`,className:`files-tree-toggle icon-button`,"aria-label":a(l?`filesHideTree`:`filesShowTree`),"aria-pressed":l,onClick:()=>u(e=>!e),children:l?(0,K.jsx)(G,{"aria-hidden":`true`}):(0,K.jsx)(De,{"aria-hidden":`true`})})}),!s&&(0,K.jsxs)(`div`,{className:`files-empty-header`,title:n,children:[(0,K.jsx)(G,{"aria-hidden":`true`}),n.split(/[\\/]/u).filter(Boolean).at(-1)||n]}),!s&&(0,K.jsxs)(`div`,{className:`files-preview-empty`,children:[(0,K.jsx)(Se,{"aria-hidden":`true`}),(0,K.jsx)(`h3`,{children:a(`filesChoose`)}),(0,K.jsx)(`p`,{children:a(`filesChooseDetail`)})]}),(0,K.jsx)(`div`,{className:`files-tree-container`,hidden:!l,children:(0,K.jsx)(XR,{sessionId:e,sessionPath:t,cwd:n,canWrite:i,active:r&&l,selected:s,onSelect:c,dropTarget:d,onShowTree:u,onRemoved:e=>{e.some(e=>e===s||s.startsWith(`${e}/`))&&f.current?.close({restoreFocus:!1})}},JSON.stringify([e,t,n]))})]})})}var QR=(0,_.createContext)(null);QR.displayName=`CollapsibleGroupContext`;var $R=(0,_.createContext)(null);$R.displayName=`CollapsibleGroupPresentationContext`;function ez(e){let{isCollapsible:t,value:n}=e,r=(0,_.use)(QR),i=r!=null&&n!=null,a=t===!0?{}:t||null,o=a!=null,[s,c]=(0,_.useState)(()=>i?!0:a?.isOpen===void 0?a?.defaultIsOpen??!0:a.isOpen),l;return l=i&&n!=null?r.isOpen(n):a?.isOpen===void 0?s:a.isOpen,{isEnabled:o,isOpen:l,toggle:()=>{if(i&&n!=null){r.toggle(n);return}let e=!l;a?.isOpen===void 0&&c(e),a?.onOpenChange?.(e)}}}var tz={info:`info`,warning:`warning`,error:`error`,success:`success`},nz={info:`status`,warning:`alert`,error:`alert`,success:`status`},rz=`status`,iz={info:`accent`,warning:`warning`,error:`error`,success:`success`},az={root:{k1xSpc:`x78zum5`,kXwgrk:`xdt5ytf`,kMv6JI:`xjb2p0i`,$$css:!0},rootElevatedCard:{kaIpWk:`x1vf2byn`,$$css:!0},header:{k1xSpc:`x78zum5`,kGNEyG:`x1cy8zhl`,kwnvtZ:`x1a02dak`,k1C7PZ:`xak3so`,khm7nJ:`x4olc9o`,k8WAf4:`x8o8v82`,kg3NbH:`x1pzlopt`,$$css:!0},headerCardStandalone:{kaIpWk:`x1vf2byn`,$$css:!0},headerCardWithContent:{krdFHd:`xwxb7qi`,kfmiAY:`x13nour3`,kVL7Gh:`xbiv7yw`,kT0f0o:`x16uus16`,$$css:!0},headerCentered:{kGNEyG:`x6s0dn4`,$$css:!0},endArea:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,kwnvtZ:`x1a02dak`,kjj79g:`x13a6bvl`,kOIVth:`x1txdalj`,kmuXW:`x2lah0s`,ks0D6T:`x193iq5w`,keTefX:`xvc5jky`,kqGvvJ:`x81ka23`,$$css:!0},chevron:{k1ekBW:`x11xpdln`,kIyJzY:`xuedmi6 x12w9bfk`,kAMwcw:`xlr8y92`,$$css:!0},chevronExpanded:{k3aq6I:`x19jd1h0`,$$css:!0}},oz={info:{kWkggS:`xgcxg3y`,$$css:!0},warning:{kWkggS:`x24i8r5`,$$css:!0},error:{kWkggS:`x1pritpl`,$$css:!0},success:{kWkggS:`xu13z74`,$$css:!0}};function sz(e){return Object.prototype.hasOwnProperty.call(oz,e)}var cz={none:{kGVxlE:`x1gnnqk1`,$$css:!0},low:{kGVxlE:`x1i5ehqx`,$$css:!0},med:{kGVxlE:`x14hfi27`,$$css:!0},high:{kGVxlE:`x1kcpxr7`,$$css:!0}};function lz({status:e,title:t,description:n,icon:r,isDismissable:i=!1,onDismiss:a,dismissLabel:o,endContent:s,container:c=`card`,elevation:l=`none`,collapsible:u=!0,children:d,xstyle:f,className:p,style:m,ref:h,onFocusCapture:g,onPointerDownCapture:v,...y}){let b=Rc(),[x,S]=(0,_.useState)(!1),C=typeof u==`object`&&u?u:{},{isEnabled:w,isOpen:T,toggle:E}=ez({isCollapsible:u!==!1&&{...C,defaultIsOpen:C.defaultIsOpen??!1}}),D=(0,_.useRef)(null),O=(0,_.useId)(),k=tz[e],A=nz[e]??rz,j=iz[e],M=Ea(d),N=b(`@astryx.banner.dismiss`),P=o??N,F=o??(typeof t==`string`?b(`@astryx.banner.dismissTitled`,{dismiss:N,title:t}):N);if(x)return null;let I=(e,t)=>{e instanceof HTMLElement&&e!==document.body&&!t.contains(e)&&(D.current=e)},L=e=>{I(e.relatedTarget,e.currentTarget)},R=e=>{I(document.activeElement,e.currentTarget)},ee=()=>{let e=D.current;S(!0),a?.(),e?.isConnected&&e.focus()},z=w&&M,B=Ea(s)||i||z,V=Ea(s)||i,H=!Ea(n)&&V,te=M&&(!w||T),ne=c===`card`;return(0,K.jsxs)(`div`,{ref:h,role:A,onFocusCapture:ca(g,L),onPointerDownCapture:ca(v,R),...oa(Sr(az.root,cz[l],ne&&l!==`none`&&az.rootElevatedCard,f),p,m),...y,children:[(0,K.jsxs)(`div`,{...oa(ba(`banner`,{container:c,status:e}),Sr(az.header,H&&az.headerCentered,sz(e)&&oz[e],ne&&(te?az.headerCardWithContent:az.headerCardStandalone))),children:[(0,K.jsx)(`div`,{...Ea(r)?oa(ba(`banner-icon`,{status:e}),{className:`x78zum5 x6s0dn4 x2lah0s`}):{className:`x78zum5 x6s0dn4 x2lah0s`},"aria-hidden":`true`,children:Ea(r)?r:k==null?null:(0,K.jsx)(xu,{icon:k,size:`md`,color:j,...ba(`banner-icon`,{status:e})})}),(0,K.jsxs)(`div`,{...{0:{className:`x78zum5 xdt5ytf xxhr3t x98rzlu xeuugli`},1:{className:`x78zum5 xdt5ytf xxhr3t x98rzlu xeuugli xgualba`}}[!!Ea(s)<<0],children:[(0,K.jsx)(`div`,{className:`x1ghz6dp xjb2p0i xcr08ib x2mo6ok x1kq96og x1tgivj0 xj0a0fe`,children:t}),Ea(n)&&(0,K.jsx)(`div`,{className:`x1ghz6dp xjb2p0i x141an7d x1sodnla x1ltkj2j xv1l7n4 xj0a0fe`,children:n})]}),B&&(0,K.jsxs)(`div`,{...Sr(az.endArea,rs.inset(Br[`--spacing-2`])),children:[s,z&&(0,K.jsx)(qc,{variant:`ghost`,size:`sm`,label:b(T?`@astryx.banner.collapse`:`@astryx.banner.expand`),tooltip:b(T?`@astryx.banner.collapse`:`@astryx.banner.expand`),icon:(0,K.jsx)(xu,{icon:`chevronDown`,size:`sm`,color:`inherit`,xstyle:[az.chevron,T&&az.chevronExpanded]}),onClick:E,"aria-expanded":T,"aria-controls":te?O:void 0,isIconOnly:!0}),i&&(0,K.jsx)(qc,{variant:`ghost`,size:`sm`,label:F,tooltip:P,icon:(0,K.jsx)(xu,{icon:`close`,size:`sm`,color:`inherit`}),onClick:ee,isIconOnly:!0})]})]}),te&&(0,K.jsx)(`div`,{id:z?O:void 0,...oa(ba(`banner-content`,{container:c,status:e}),{0:{className:`x1de1mus x8o8v82 x1pzlopt xgbv0en xw8tdv1 x92x3c3 x1t7ytsu x18b5jzi x1q0q8m5 x1j92z86 x1gejf6u xw8gpjh`},1:{className:`x1de1mus x8o8v82 x1pzlopt xgbv0en xw8tdv1 x92x3c3 x1t7ytsu x18b5jzi x1q0q8m5 x1j92z86 x1gejf6u xw8gpjh x1k5g1gk x1eprgri`}}[!!ne<<0]),children:d})]})}lz.displayName=`Banner`;var uz={container:{k1xSpc:`x78zum5`,kXwgrk:`xdt5ytf`,kGNEyG:`x6s0dn4`,kjj79g:`xl56j7k`,k9WMMc:`x2b8uid`,kOIVth:`x18g69wz`,k8WAf4:`xmfvnks`,kg3NbH:`xm7rs69`,$$css:!0},containerCompact:{kOIVth:`x1txdalj`,k8WAf4:`x1na6nto`,kg3NbH:`x1pzlopt`,$$css:!0}};function dz({title:e,description:t,icon:n,actions:r,headingLevel:i=3,isCompact:a=!1,xstyle:o,className:s,style:c,ref:l,...u}){let d=`h${i}`;return(0,K.jsxs)(`div`,{ref:l,...u,role:`status`,...oa(ba(`empty-state`,{variant:a?`compact`:null}),Sr(uz.container,a&&uz.containerCompact,o),s,c),children:[n!=null&&(0,K.jsx)(`div`,{"aria-hidden":`true`,children:n}),(0,K.jsxs)(`div`,{className:`x78zum5 xdt5ytf x6s0dn4 xxc7z9f`,children:[(0,_.createElement)(d,oa(ba(`empty-state-title`,{variant:a?`compact`:null}),{0:{className:`x1ghz6dp xjb2p0i x18juvz8 x2mo6ok xf74fhv x1tgivj0`},1:{className:`x1ghz6dp xjb2p0i x2mo6ok xf74fhv x1tgivj0 xcr08ib`}}[!!a<<0]),e),t!=null&&(0,K.jsx)(`div`,{...oa(ba(`empty-state-description`,{variant:a?`compact`:null}),{0:{className:`x1ghz6dp xjb2p0i xjm74w1 x1sodnla xw6l6zx xv1l7n4`},1:{className:`x1ghz6dp xjb2p0i x1sodnla xw6l6zx xv1l7n4 x141an7d`}}[!!a<<0]),children:t})]}),r!=null&&(0,K.jsx)(`div`,{...{0:{className:`x78zum5 x1q0g3np x6s0dn4 x1txdalj xcsaf9d`},1:{className:`x78zum5 x6s0dn4 x1txdalj xcsaf9d xdt5ytf`}}[!!a<<0],children:r})]})}dz.displayName=`EmptyState`;var fz=1e3,pz=100,mz={root:{kWkggS:`xprdx6m x1j0df82 x1o55y2u`,kSiTet:`xvpkmg4 x1tbh5bv`,$$css:!0},animate:{kILWW9:`xpz12be`,k44tkh:`xqgcaz`,ko0y90:`xa4qsjk`,kKVMdj:`xeuoslp x1aquc0h`,kyAemX:`x193epu2`,$$css:!0}},hz={0:{kaIpWk:`xwksslw`,$$css:!0},1:{kaIpWk:`xx3sua9`,$$css:!0},2:{kaIpWk:`xh6dtrn`,$$css:!0},3:{kaIpWk:`x1hviunn`,$$css:!0},4:{kaIpWk:`x1hviunn`,$$css:!0},none:{kaIpWk:`x2u8bby`,$$css:!0},rounded:{kaIpWk:`xjspbzw`,$$css:!0}},gz={kKxzle:`xvo38ju`,$$css:!0},_z={animationDelay:e=>[gz,{"--x-animationDelay":(e=>typeof e==`number`?e+`ms`:e??void 0)(`${fz+pz*e}ms`)}],dimensions:(e,t)=>[{kzqmXN:(typeof e==`number`?`${e}px`:e)==null?typeof e==`number`?`${e}px`:e:`x5lhr3w`,kZKoxP:(typeof t==`number`?`${t}px`:t)==null?typeof t==`number`?`${t}px`:t:`x16ye13r`,$$css:!0},{"--x-width":(e=>typeof e==`number`?e+`px`:e??void 0)(typeof e==`number`?`${e}px`:e),"--x-height":(e=>typeof e==`number`?e+`px`:e??void 0)(typeof t==`number`?`${t}px`:t)}]};function vz({width:e=`100%`,height:t=`100%`,radius:n=3,index:r=0,"data-testid":i,xstyle:a,className:o,style:s,ref:c,...l}){return(0,K.jsx)(`div`,{ref:c,"aria-hidden":`true`,"data-testid":i,...oa(ba(`skeleton`),Sr(mz.root,mz.animate,hz[n],_z.dimensions(e,t),_z.animationDelay(r),a),o,s),...l})}vz.displayName=`Skeleton`;function yz({branches:e,value:t,loading:n,onChange:r}){let{t:i}=cr(),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(!1),l=(0,_.useRef)(null),u=(0,_.useRef)([]),d=(0,_.useRef)(null),f=(0,_.useId)(),p=e.options.filter(e=>`${e.label} ${e.ref}`.toLocaleLowerCase().includes(a.toLocaleLowerCase()));(0,_.useEffect)(()=>{if(!s)return;let e=requestAnimationFrame(()=>l.current?.focus());return()=>cancelAnimationFrame(e)},[s]),(0,_.useEffect)(()=>{if(!s)return;let e=e=>{let t=e.target;d.current=t instanceof Element&&!t.closest(`.review-base-picker, .review-base-popup`)?t.closest(`button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select:not(:disabled), a[href], [tabindex], [contenteditable='true']`):null};return document.addEventListener(`pointerdown`,e,!0),()=>document.removeEventListener(`pointerdown`,e,!0)},[s]);let m=e.options.find(e=>e.ref===t)?.label??t;return(0,K.jsx)($M,{className:`review-base-picker`,label:i(`gitReviewBaseBranch`),isLabelHidden:!0,value:t??``,triggerLabel:(0,K.jsx)(`span`,{className:`review-base-label`,title:t,children:m||i(`gitReviewChooseBase`)}),variant:`ghost`,size:`sm`,isDisabled:e.options.length===0,isLoading:n,onOpenChange:e=>{c(e),e||(o(``),d.current?.isConnected&&d.current.focus({preventScroll:!0}),d.current=null)},children:(s,c,d)=>(0,K.jsxs)(`div`,{className:`review-base-popup`,children:[(0,K.jsxs)(`label`,{className:`review-base-search`,children:[(0,K.jsx)(ht,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`sr-only`,children:i(`gitReviewSearchBranches`)}),(0,K.jsx)(`input`,{ref:l,type:`search`,value:a,"aria-controls":f,placeholder:i(`gitReviewSearchBranches`),onChange:e=>o(e.currentTarget.value),onKeyDown:e=>{e.nativeEvent.isComposing||e.keyCode===229||(e.key===`Escape`?(e.preventDefault(),e.stopPropagation(),d()):e.key===`ArrowDown`&&p.length&&!n&&(e.preventDefault(),u.current[0]?.focus()))}})]}),e.truncated&&(0,K.jsx)(`p`,{role:`status`,children:i(`gitReviewBranchesTruncated`)}),(0,K.jsxs)(`div`,{id:f,role:`listbox`,"aria-label":i(`gitReviewBaseBranch`),className:`review-base-options`,children:[p.map((e,a)=>(0,K.jsxs)(`button`,{type:`button`,disabled:n,role:`option`,"aria-selected":t===e.ref,title:e.ref,ref:e=>{u.current[a]=e},onClick:()=>{r(e.ref),d()},onKeyDown:e=>{if(!(e.nativeEvent.isComposing||e.keyCode===229)){if(e.key===`Escape`)e.preventDefault(),e.stopPropagation(),d();else if(e.key===`ArrowDown`||e.key===`ArrowUp`||e.key===`Home`||e.key===`End`){e.preventDefault();let t=e.key===`Home`?0:e.key===`End`?p.length-1:(a+(e.key===`ArrowDown`?1:p.length-1))%p.length;u.current[t]?.focus()}}},children:[(0,K.jsxs)(`span`,{children:[e.label,(0,K.jsx)(`small`,{children:e.ref.startsWith(`refs/heads/`)?i(`gitReviewLocalBranch`):i(`gitReviewRemoteBranch`)})]}),t===e.ref&&(0,K.jsx)(I,{"aria-hidden":`true`})]},e.ref)),!p.length&&(0,K.jsx)(`p`,{role:`status`,children:i(`gitReviewNoMatchingBranches`)})]})]})})}function bz(e,t){return{path:e,name:t,directories:new Map,files:[]}}function xz({files:e,selectedPath:t,collapsed:n,searching:r,onToggle:i,onSelect:a,viewed:o,onViewedChange:s,viewedLimitReached:c=!1}){let{t:l}=cr(),u=(0,_.useMemo)(()=>{let t=bz(``,``);for(let n of e){let e=t;for(let t of n.path.split(`/`).slice(0,-1)){let n=e.path?`${e.path}/${t}`:t,r=e.directories.get(t);r||(r=bz(n,t),e.directories.set(t,r)),e=r}e.files.push(n)}return t},[e]),d=(e,u)=>(0,K.jsxs)(`ul`,{children:[[...e.directories.values()].map(e=>{let t=e,a=t.name;for(;t.files.length===0&&t.directories.size===1;){let e=t.directories.values().next().value;if(!e)break;t=e,a+=`/${t.name}`}let o=t.path,s=r||!n.has(o);return(0,K.jsxs)(`li`,{children:[(0,K.jsxs)(`button`,{type:`button`,className:`review-tree-directory`,style:{paddingLeft:8+u*16},title:o,"aria-expanded":s,disabled:r,onClick:()=>i(o),children:[(0,K.jsx)(ee,{"aria-hidden":`true`,"data-open":s}),(0,K.jsx)(`span`,{children:a})]}),s&&d(t,u+1)]},e.path)}),e.files.map(e=>{let n=e.path.split(`/`).at(-1)??e.path,r=/\.(png|jpe?g|gif|webp|svg)$/iu.test(n)?Ne:/\.(md|txt|log)$/iu.test(n)?Se:ve;return(0,K.jsxs)(`li`,{className:`review-tree-file-row`,children:[(0,K.jsxs)(`button`,{className:`session-review-file review-tree-file`,type:`button`,style:{paddingLeft:8+u*16},"data-review-file":e.path,title:e.path,"aria-label":e.path,"aria-description":l(`gitFileStatus_${e.status}`),"aria-current":t===e.path?`true`:void 0,onClick:()=>a(e.path),children:[(0,K.jsx)(r,{"aria-hidden":`true`,className:`review-tree-icon`}),(0,K.jsx)(`span`,{className:`review-tree-name`,children:n}),(0,K.jsx)(`span`,{className:`review-tree-status`,"aria-hidden":`true`,children:l(`gitFileStatus_${e.status}`)}),(0,K.jsx)(`span`,{className:`session-review-stats`,"aria-hidden":`true`,children:e.binary?(0,K.jsx)(`span`,{children:l(`gitReviewBinaryShort`)}):e.statsUnavailable?(0,K.jsx)(`span`,{title:l(`turnEditStatsUnknown`),children:`—`}):(0,K.jsxs)(K.Fragment,{children:[e.additions>0&&(0,K.jsxs)(`span`,{className:`review-additions`,children:[`+`,e.additions]}),e.deletions>0&&(0,K.jsxs)(`span`,{className:`review-deletions`,children:[`-`,e.deletions]})]})})]}),s&&(0,K.jsx)(`label`,{className:`review-viewed-control`,title:l(`gitReviewMarkViewed`,{path:e.path}),children:(0,K.jsx)(`input`,{type:`checkbox`,"aria-label":l(`gitReviewMarkViewed`,{path:e.path}),checked:o?.has(e.path)??!1,disabled:c&&!o?.has(e.path),onChange:t=>s(e.path,t.currentTarget.checked)})})]},e.path)})]});return(0,K.jsx)(`div`,{className:`session-review-list review-file-tree`,children:d(u,0)})}var Sz=20,Cz=200,wz=[0,1,2,3];function Tz(e){return e.split(/[\\/]/u).at(-1)||e}function Ez(e,t){return e?e.reason===`not_git_repository`?t(`gitReviewNotRepository`):e.reason===`unborn_repository`?t(`gitReviewUnborn`):e.reason===`baseline_unavailable`?t(`gitReviewBaselineUnavailable`):e.reason===`base_branch_unavailable`?t(`gitReviewBaseUnavailable`):e.reason===`invalid_base_branch`?t(`gitReviewBaseInvalid`):t(`gitReviewFailed`):null}function Dz({review:e,initialFilePath:t,onClose:n,onOpenTools:r,embedded:i=!1,active:a=!0,onOpenFiles:o,readingScope:s,onReferenceLine:c}){let{t:l}=cr(),u=wk(),d=(0,_.useRef)(void 0);e.result?.branches?d.current=e.result.branches:e.result&&!e.loading&&(d.current=void 0);let f=e.result?.branches??(e.loading?d.current:void 0),p=`${s??e.source??`unstaged`}:${e.baseRef??``}`,m=u?.review?.scope===p?u.review:void 0,h=(0,_.useRef)(JSON.stringify([p,t])),g=(0,_.useRef)(null),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(new Set(m?.collapsedDirectories));(0,_.useEffect)(()=>{let e=g.current;if(!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(([e])=>{e&&y(e.contentRect.width>=720)});return t.observe(e),()=>t.disconnect()},[]);let S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=(0,_.useRef)(null),E=(0,_.useRef)(!0),D=(0,_.useRef)(!1),O=(0,_.useRef)(m?.listScroll??null),k=(0,_.useRef)(null),[A,j]=(0,_.useState)(m?.visibleFiles??Sz),[M,N]=(0,_.useState)(m?.query??``),[P,F]=(0,_.useState)(null),[I,L]=(0,_.useState)(m?m.selected:t??null),[R,ee]=(0,_.useState)(()=>m?.viewed?{scope:p,revision:m.viewed.revision,paths:new Set(m.viewed.paths.slice(0,Cz))}:null),z=(0,_.useRef)(m?{list:m.listScroll,preview:m.previewScroll}:null);(0,_.useLayoutEffect)(()=>{u&&(u.review={source:e.source??`unstaged`,baseRef:e.baseRef,scope:p,selected:I,query:M,collapsedDirectories:[...b],visibleFiles:A,listScroll:u.review?.scope===p?u.review.listScroll:0,previewScroll:u.review?.scope===p?u.review.previewScroll:0,viewed:R?.scope===p?{revision:R.revision,paths:[...R.paths].slice(0,Cz)}:void 0})},[u,e.source,e.baseRef,p,I,M,b,A,R]);let[B,V]=(0,_.useState)(null),[H,te]=(0,_.useState)(null),[ne,re]=(0,_.useState)(0),[ie,ae]=(0,_.useState)(()=>window.matchMedia?.(`(max-width: 1100px)`).matches??!1);(0,_.useEffect)(()=>{let e=window.matchMedia?.(`(max-width: 1100px)`);if(!e)return;let t=()=>ae(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,_.useEffect)(()=>{let e=JSON.stringify([p,t]);h.current!==e&&(h.current=e,E.current=!!t||!(document.activeElement instanceof Element&&document.activeElement.closest(`.review-base-picker, .review-base-popup`)),O.current=null,L(t??null),N(``),x(new Set),F(null),ee(null))},[t,p]);let U=i?`section`:ie?`main`:`aside`,oe=e.result?.ok?e.result.snapshot:null,se=!e.historical&&I&&P&&P.comparison===(e.source??oe?.comparison)?oe?.revision===P.revision?oe:P:oe,ce=!!(I&&se&&oe&&se.revision!==oe.revision);(0,_.useEffect)(()=>{I&&!P&&oe&&F(oe)},[I,P,oe]);let le=e.source??se?.comparison??`unstaged`,ue=Ez(e.result&&!e.result.ok?e.result:null,l),de=se?.files.find(e=>e.path===I),fe=B?.source===le&&B?.revision===se?.revision&&B?.file.path===I?B.file:de,pe=se?.revision,me=R?.scope===p&&R.revision===pe?R.paths:new Set;(0,_.useEffect)(()=>{pe&&R&&(R.scope!==p||R.revision!==pe)&&ee(null)},[pe,p,R]);let W=(e,t)=>{!pe||!se?.files.some(t=>t.path===e)||ee(n=>{let r=new Set(n?.scope===p&&n.revision===pe?n.paths:[]);if(t){if(r.size>=Cz)return n;r.add(e)}else r.delete(e);return{scope:p,revision:pe,paths:r}})};(0,_.useLayoutEffect)(()=>{!a||!se||!z.current||I&&fe?.diffLoaded===!1||(C.current&&(C.current.scrollTop=z.current.list),w.current&&(w.current.scrollTop=z.current.preview),z.current=null)},[a,se,I,fe?.diffLoaded]);let he=H?.source===le&&H?.path===I&&H?.revision===pe&&de?.diffLoaded===!1?H.message:null;(0,_.useEffect)(()=>{let t=de?.path;if(!a||!t||de?.diffLoaded!==!1||!e.readFile||!pe)return;let n=new AbortController;return te(null),e.readFile(t,n.signal,pe).then(e=>{n.signal.aborted||(e?V({source:le,revision:pe,file:e}):te({source:le,path:t,revision:pe,message:l(`gitReviewFileMissing`)}))},e=>{n.signal.aborted||te({source:le,path:t,revision:pe,message:e instanceof Error?e.message:l(`gitReviewFailed`)})}),()=>n.abort()},[de?.path,a,de?.diffLoaded,pe,le,e.readFile,ne,l]);let ge=(0,_.useMemo)(()=>(se?.files??[]).filter(e=>e.path.toLocaleLowerCase().includes(M.toLocaleLowerCase())).sort((e,t)=>e.path.localeCompare(t.path,`en`,{numeric:!0})),[se?.files,M]),_e=v?ge:ge.slice(0,A);(0,_.useEffect)(()=>{!v||I||!se?.files.length||(E.current=!1,L(se.files[0].path))},[v,I,se]);let be=Math.max(0,ge.length-_e.length),xe=se?.listComplete===!1||se?.listComplete===void 0&&se?.truncated,Se=xe||se?.nextOffset!==void 0,Ce=e.historical?l(se?.evidenceSource===`file-tools`?`turnEditsScope`:`turnChangesScope`):se?se.comparison===`session`?l(`gitReviewSessionSnapshot`):se.comparison===`unstaged`?l(`gitReviewUnstaged`):se.comparison===`staged`?l(`gitReviewStaged`):se.baseBranch?l(`gitReviewComparison`,{current:se.currentBranch??l(`gitReviewDetached`),base:se.baseBranch.replace(/^refs\/(?:heads|remotes)\//u,``)}):l(`gitReviewWorkingTree`):null;(0,_.useEffect)(()=>{let e=a&&!D.current;D.current=a,a&&(!e&&!E.current||(E.current=!1,I?w.current?.focus():i?C.current?.focus():S.current?.focus()))},[a,i,I]);let we=e=>{O.current=C.current?.scrollTop??null,e!==I&&(z.current={list:O.current??0,preview:0},w.current&&(w.current.scrollTop=0),u?.review?.scope===p&&(u.review.previewScroll=0)),E.current=!v,F(se),L(e)};(0,_.useLayoutEffect)(()=>{let e=k.current;if(I||!e||!a)return;k.current=null;let t=C.current;if(!t?.isConnected||t.closest(`[hidden], [inert]`))return;let n=[...t.querySelectorAll(`[data-review-file]`)].find(t=>t.dataset.reviewFile===e);O.current!==null&&(t.scrollTop=O.current),n?n.focus({preventScroll:O.current!==null}):i?t.focus():S.current?.focus()},[a,i,I]);let Te=()=>{let e=I,t=ge.findIndex(t=>t.path===e);t>=A&&j(Math.ceil((t+1)/Sz)*Sz),E.current=!1,k.current=e,L(null),F(null)};return(0,K.jsxs)(U,{ref:g,className:`review-panel${i?` embedded`:``}${v?` review-wide`:``}`,"aria-label":l(`changeEvidence`),"aria-busy":e.loading||void 0,onKeyDown:e=>{e.key!==`Escape`||e.nativeEvent.isComposing||e.keyCode===229||e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.defaultPrevented||(!I||v)&&i||(e.preventDefault(),e.stopPropagation(),I&&!v?Te():i||n())},children:[(0,K.jsxs)(`div`,{className:`review-source-picker`,children:[e.setSource&&(0,K.jsxs)(`label`,{children:[l(`gitReviewSource`),` `,(0,K.jsxs)(`select`,{value:e.historical?`turn`:e.source??`unstaged`,onChange:t=>e.setSource?.(t.currentTarget.value),children:[e.historical&&(0,K.jsx)(`option`,{value:`turn`,children:l(`turnChangesReview`)}),(0,K.jsx)(`option`,{value:`unstaged`,children:l(`gitReviewUnstaged`)}),(0,K.jsx)(`option`,{value:`staged`,children:l(`gitReviewStaged`)}),(0,K.jsx)(`option`,{value:`branch`,children:l(`gitReviewBranch`)}),(0,K.jsx)(`option`,{value:`session`,children:l(`gitReviewSessionSnapshot`)})]})]}),e.source===`branch`&&e.setBaseRef&&f&&(0,K.jsx)(yz,{branches:f,value:e.baseRef??(e.result?.ok?e.result.snapshot.baseBranch??void 0:void 0),loading:e.loading,onChange:e.setBaseRef}),Ce&&(!e.setSource||e.historical||se?.comparison===`branch`)&&(0,K.jsx)(`span`,{className:`review-source-summary`,title:Ce,children:Ce}),(0,K.jsxs)(`div`,{className:`review-source-actions`,children:[o&&(0,K.jsx)(`button`,{type:`button`,onClick:o,children:l(`sessionFileRecords`)}),(0,K.jsx)(`button`,{type:`button`,className:`icon-button`,"aria-label":l(`gitReviewRefresh`),title:l(`gitReviewRefresh`),disabled:e.loading,"aria-busy":e.loading||void 0,onClick:()=>{e.loading||e.refresh()},children:(0,K.jsx)(dt,{"aria-hidden":`true`})})]})]}),ce&&(0,K.jsxs)(`div`,{className:`review-update`,role:`status`,children:[(0,K.jsx)(`span`,{children:l(`gitReviewNewVersion`)}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{w.current?.focus(),F(oe),V(null)},children:l(`gitReviewShowLatest`)})]}),(e.error||ue)&&(0,K.jsx)(lz,{status:`error`,container:`section`,title:e.error||ue,description:se?l(`gitReviewOlderResult`):void 0,className:`review-banner`,endContent:(0,K.jsx)(qc,{variant:`ghost`,size:`sm`,label:l(`gitReviewRetry`),isDisabled:e.loading,isLoading:e.loading,onClick:()=>{e.loading||e.refresh()}})}),(0,K.jsxs)(`div`,{className:`review-workspace`,children:[I&&(0,K.jsxs)(`div`,{className:`review-file-screen`,children:[(0,K.jsxs)(`header`,{className:`review-file-header`,children:[!v&&(0,K.jsx)(qc,{label:l(`gitReviewBackToFiles`),variant:`ghost`,size:`sm`,isIconOnly:!0,icon:(0,K.jsx)(T,{"aria-hidden":`true`}),onClick:Te}),(0,K.jsxs)(`div`,{className:`review-file-heading`,children:[(0,K.jsx)(`strong`,{title:I,children:Tz(I)}),(0,K.jsx)(`span`,{title:I,children:I})]}),fe&&pe&&(0,K.jsxs)(`label`,{className:`review-file-viewed`,children:[(0,K.jsx)(`input`,{type:`checkbox`,"aria-label":l(`gitReviewMarkCurrentViewed`,{path:I}),checked:me.has(I),disabled:me.size>=Cz&&!me.has(I),onChange:e=>W(I,e.currentTarget.checked)}),(0,K.jsx)(`span`,{children:l(`gitReviewViewedLabel`)})]}),!i&&(0,K.jsxs)(`div`,{className:`review-file-actions`,children:[r&&(0,K.jsx)(qc,{label:l(`openTools`),variant:`ghost`,size:`sm`,isIconOnly:!0,icon:(0,K.jsx)(lt,{"aria-hidden":`true`}),onClick:r}),(0,K.jsx)(qc,{label:l(`close`),variant:`ghost`,size:`sm`,isIconOnly:!0,icon:(0,K.jsx)(Lt,{"aria-hidden":`true`}),onClick:n})]})]}),(0,K.jsxs)(`div`,{className:`review-file-toolbar`,children:[(0,K.jsx)(`div`,{className:`review-file-context`,children:fe&&(0,K.jsx)(`span`,{children:l(`gitFileStatus_${fe.status}`)})}),(0,K.jsxs)(RP,{gap:2,align:`center`,className:`session-review-stats`,children:[fe&&!fe.binary&&!fe.statsUnavailable&&fe.additions>0&&(0,K.jsxs)(zo,{type:`supporting`,hasTabularNumbers:!0,className:`review-additions`,children:[`+`,fe.additions]}),fe&&!fe.binary&&!fe.statsUnavailable&&fe.deletions>0&&(0,K.jsxs)(zo,{type:`supporting`,hasTabularNumbers:!0,className:`review-deletions`,children:[`-`,fe.deletions]})]})]}),(0,K.jsx)(`section`,{ref:w,className:`review-file-preview`,"aria-label":l(`gitReviewFilePreview`,{file:I}),tabIndex:-1,onScroll:e=>{u?.review&&(u.review.previewScroll=e.currentTarget.scrollTop)},children:fe?he?(0,K.jsxs)(`div`,{role:`alert`,children:[(0,K.jsx)(`p`,{children:he}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>re(e=>e+1),children:l(`retryAdmissionCheck`)})]}):fe.diffLoaded===!1&&e.readFile?(0,K.jsx)(`p`,{role:`status`,children:l(`gitReviewLoading`)}):fe.binary?(0,K.jsx)(dz,{icon:(0,K.jsx)(ve,{"aria-hidden":`true`}),title:l(`gitReviewBinary`),isCompact:!0}):fe.statsUnavailable?(0,K.jsx)(dz,{icon:(0,K.jsx)(ve,{"aria-hidden":`true`}),title:l(`turnEditStatsUnknown`),description:l(`turnEditReason_${fe.statsUnavailable}`),isCompact:!0}):fe.diff?(0,K.jsxs)(K.Fragment,{children:[fe.diffTruncated&&(0,K.jsx)(`p`,{className:`review-hidden-lines`,children:l(`gitReviewDiffTruncated`)}),(0,K.jsx)(VL,{file:fe,onReferenceLine:c})]}):(0,K.jsx)(dz,{icon:(0,K.jsx)(ve,{"aria-hidden":`true`}),title:l(fe.diffTruncated?`gitReviewDiffTruncated`:`gitReviewNoDiff`),description:fe.diffTruncated?l(`gitReviewDiffTruncated`):void 0,isCompact:!0}):(0,K.jsx)(`p`,{role:`status`,children:l(e.loading?`gitReviewLoading`:`gitReviewFileMissing`)})})]}),(!I||v)&&(0,K.jsxs)(`div`,{className:`review-navigation`,children:[!i&&!v&&(0,K.jsxs)(`header`,{className:`review-heading`,children:[(0,K.jsx)(`div`,{children:(0,K.jsxs)(`h2`,{children:[(0,K.jsx)(ye,{"aria-hidden":`true`}),` `,l(`changeEvidence`)]})}),(0,K.jsxs)(`div`,{className:`review-heading-actions`,children:[r&&(0,K.jsx)(`button`,{type:`button`,className:`icon-button`,"aria-label":l(`openTools`),title:l(`openTools`),onClick:r,children:(0,K.jsx)(lt,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{ref:S,type:`button`,className:`icon-button review-close`,"aria-label":l(`close`),title:l(`close`),onClick:n,children:(0,K.jsx)(Lt,{"aria-hidden":`true`})})]})]}),(0,K.jsxs)(`div`,{ref:C,onScroll:e=>{u?.review&&(u.review.listScroll=e.currentTarget.scrollTop)},className:`review-body`,tabIndex:i?-1:void 0,children:[se&&(0,K.jsxs)(zP,{gap:1,align:`stretch`,className:`review-summary`,children:[(0,K.jsxs)(RP,{gap:3,align:`center`,justify:`between`,children:[(0,K.jsx)(zo,{type:`label`,children:l(xe?`gitReviewLoadedCount`:`filesChanged`,{count:xe?se.files.length:se.totalFiles??se.files.length})}),se.nextOffset!==void 0&&!xe&&(0,K.jsx)(zo,{type:`supporting`,color:`secondary`,children:l(`gitReviewLoadedCount`,{count:se.files.length})}),!xe&&!se.truncated&&se.nextOffset===void 0&&(se.additions>0||se.deletions>0)&&!se.files.some(e=>e.binary||e.statsUnavailable||e.status===`untracked`&&e.diffLoaded===!1)&&(0,K.jsxs)(RP,{gap:2,align:`center`,className:`review-summary-counts`,"aria-hidden":`true`,children:[se.additions>0&&(0,K.jsxs)(zo,{type:`supporting`,hasTabularNumbers:!0,className:`review-additions`,children:[`+`,se.additions]}),se.deletions>0&&(0,K.jsxs)(zo,{type:`supporting`,hasTabularNumbers:!0,className:`review-deletions`,children:[`-`,se.deletions]})]})]}),me.size>=Cz&&(0,K.jsx)(zo,{type:`supporting`,color:`secondary`,children:l(`gitReviewViewedLimit`,{count:Cz})})]}),e.loading&&!se&&(0,K.jsxs)(`div`,{className:`review-loading`,role:`status`,children:[(0,K.jsx)(`span`,{className:`sr-only`,children:l(`gitReviewLoading`)}),(0,K.jsxs)(zP,{gap:2,align:`stretch`,"aria-hidden":`true`,children:[(0,K.jsx)(vz,{width:`42%`,height:16,radius:`rounded`,index:0}),(0,K.jsx)(`div`,{className:`review-loading-list`,children:wz.map(e=>(0,K.jsx)(vz,{width:`100%`,height:36,radius:0,index:e+1},e))})]})]}),se?.truncated&&(0,K.jsx)(lz,{status:`info`,title:l(`gitReviewTruncated`),className:`review-banner`}),se&&se.files.length>0&&(0,K.jsxs)(`label`,{className:`review-search`,children:[(0,K.jsx)(ht,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`sr-only`,children:l(Se?`gitReviewSearchLoaded`:`gitReviewSearch`)}),(0,K.jsx)(`input`,{type:`search`,value:M,placeholder:l(Se?`gitReviewSearchLoaded`:`gitReviewSearch`),onChange:e=>{N(e.target.value),j(Sz)}})]}),M&&ge.length===0&&(0,K.jsx)(`p`,{className:`review-search-empty`,role:`status`,children:l(Se?`gitReviewNoLoadedMatch`:`gitReviewNoMatch`)}),se&&se.files.length===0&&(0,K.jsx)(dz,{icon:(0,K.jsx)(Ae,{"aria-hidden":`true`}),title:l(`gitReviewEmpty`),isCompact:!0,className:`review-empty`}),_e.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(xz,{files:_e,selectedPath:I,collapsed:b,searching:!!M,onToggle:e=>x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),onSelect:we,viewed:me,onViewedChange:W,viewedLimitReached:me.size>=Cz}),be>0&&(0,K.jsx)(`div`,{className:`session-review-more`,children:(0,K.jsx)(qc,{variant:`ghost`,size:`sm`,width:`100%`,label:l(`gitReviewShowMore`,{count:Math.min(Sz,be)}),onClick:()=>j(e=>Math.min(e+Sz,ge.length))})})]}),se?.nextOffset!==void 0&&e.loadMore&&(0,K.jsx)(`div`,{className:`session-review-more`,children:(0,K.jsx)(qc,{variant:`ghost`,size:`sm`,width:`100%`,label:l(`gitReviewLoadNext`),isLoading:e.loading,isDisabled:e.loading,onClick:()=>{e.loadMore?.()}})})]})]})]})]})}function Oz(e,t,n,r){let{t:i}=cr(),a=(0,_.useMemo)(()=>new rf,[]),[o,s]=(0,_.useState)(0),[c,l]=(0,_.useState)({identity:``,result:null,error:null}),u=JSON.stringify([e,t,r,o]);(0,_.useEffect)(()=>{if(!r)return;let o=new AbortController;return a.turnChanges(e,t,r,o.signal).then(t=>{if(o.signal.aborted)return;if(!t.ok||t.changes.sessionId!==e||t.changes.promptEntryId!==r||t.changes.state===`unavailable`){l({identity:u,result:null,error:i(`turnChangesUnavailable`)});return}let a=t.changes;l({identity:u,error:null,result:{ok:!0,snapshot:{...a.source?{evidenceSource:a.source}:{},...a.fileCount===null?{}:{totalFiles:a.fileCount,listComplete:!0},repositoryRoot:n,currentBranch:null,baseBranch:null,comparison:`session`,revision:u,files:a.files,additions:a.additions,deletions:a.deletions,truncated:a.state===`partial`}}})},()=>{o.signal.aborted||l({identity:u,result:null,error:i(`turnChangesUnavailable`)})}),()=>o.abort()},[a,e,t,r,u,n,i]);let d=(0,_.useCallback)(async()=>s(e=>e+1),[]);return{result:c.identity===u?c.result:null,error:c.identity===u?c.error:null,loading:!!r&&c.identity!==u,refresh:d,historical:!0}}function kz(e,t,n){let r=(0,_.useRef)({onState:t,onOpen:n});r.current={onState:t,onOpen:n};let[i,a]=(0,_.useState)(),[o,s]=(0,_.useState)(!1);return(0,_.useEffect)(()=>{let t=()=>{let e=document.documentElement.dataset.openpiBrowserExtension===`ready`;s(e),e||a(void 0)};t();let n=new MutationObserver(t);n.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-openpi-browser-extension`]});let i=t=>{if(t.source!==window||t.origin!==location.origin)return;let n=t.data;if(!n||n.source!==`openpi-browser-extension`||n.id!==e)return;if(n.type===`lost`){a(void 0);return}if(typeof n.url!=`string`)return;let i=WR(n.url,location.origin);if(i&&(n.type===`open`&&r.current.onOpen(i),n.type===`state`&&typeof n.title==`string`)){let t={id:e,document:typeof n.document==`string`?n.document:void 0,url:i,title:n.title.slice(0,256),canGoBack:n.canGoBack===!0,canGoForward:n.canGoForward===!0};a(t),r.current.onState(t)}};return window.addEventListener(`message`,i),()=>{n.disconnect(),window.removeEventListener(`message`,i)}},[e]),{ready:o,page:o&&i?.id===e?i:void 0,command:t=>window.postMessage({source:`openpi-browser-ui`,type:`command`,id:e,action:t},location.origin)}}var Az=8;function jz({onTitle:e,onOpen:t,initialUrl:n=``,readingId:r}){let{t:i}=cr(),a=(0,_.useId)(),o=(0,_.useRef)(null),s=wk(),c=s?.browser?.pages[r],[l,u]=(0,_.useState)(c?.draft??n),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)({history:c?.history??(n?[n]:[]),index:c?.index??(n?0:-1),revision:0,loaded:!1,unknown:!1}),h=p.history[p.index],g=(0,_.useRef)(h);(0,_.useLayoutEffect)(()=>{s?.browser&&(s.browser.pages[r]={draft:l,history:p.history.map((e,t)=>t===p.index?g.current??e:e),index:p.index})},[s,r,l,p]);let v=`${a}-${p.revision}`,y=kz(v,t=>{g.current=t.url;let n=s?.browser?.pages[r];n&&(n.history=n.history.map((e,r)=>r===n.index?t.url:e)),document.activeElement!==o.current&&u(t.url),e(t.title||new URL(t.url).host)},t),b=y.page?.url??h,x=(t,n)=>{let r=t[n];r&&(g.current=r,m(e=>({history:t,index:n,revision:e.revision+1,loaded:!1,unknown:!1})),u(r),f(null),e(new URL(r).host))};return(0,K.jsxs)(`div`,{className:`browser-tool browser-direct-tool`,children:[(0,K.jsxs)(`form`,{className:`browser-toolbar`,onSubmit:e=>{e.preventDefault();let t=WR(l,window.location.origin);if(!t){f(i(`browserAddressNotAllowed`));return}if(t===h)x(p.history,p.index);else{let e=[...p.history.slice(0,p.index+1),t].slice(-64);x(e,e.length-1)}},children:[(0,K.jsxs)(`div`,{className:`browser-navigation`,children:[(0,K.jsx)(`button`,{type:`button`,"aria-label":i(`browserBack`),title:i(`browserBack`),disabled:y.page?!y.page.canGoBack:p.unknown||p.index<=0,onClick:()=>y.page?y.command(`back`):x(p.history,p.index-1),children:(0,K.jsx)(T,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{type:`button`,"aria-label":i(`browserForward`),title:i(`browserForward`),disabled:y.page?!y.page.canGoForward:p.unknown||p.index>=p.history.length-1,onClick:()=>y.page?y.command(`forward`):x(p.history,p.index+1),children:(0,K.jsx)(E,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{type:`button`,"aria-label":i(`browserReload`),title:i(`browserReload`),disabled:!h,onClick:()=>y.page?y.command(`reload`):x(p.history,p.index),children:(0,K.jsx)(dt,{"aria-hidden":`true`})})]}),(0,K.jsx)(`input`,{ref:o,"aria-label":i(`browserAddress`),title:i(y.page?`browserAddress`:`browserEnteredAddress`),value:l,placeholder:`https://`,spellCheck:!1,onChange:e=>{u(e.currentTarget.value),f(null)}}),(0,K.jsx)(`button`,{type:`submit`,"aria-label":i(`browserGo`),title:i(`browserGo`),disabled:!l.trim(),children:(0,K.jsx)(E,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{type:`button`,"aria-label":i(`openExternalBrowser`),title:i(`openExternalBrowser`),disabled:!b||!y.page&&p.unknown,onClick:()=>b&&window.open(b,`_blank`,`noopener,noreferrer`),children:(0,K.jsx)(he,{"aria-hidden":`true`})})]}),(0,K.jsxs)(`div`,{className:`browser-feedback`,children:[d&&(0,K.jsx)(`p`,{className:`workbar-error`,role:`alert`,children:d}),p.unknown&&!y.page&&(0,K.jsx)(`p`,{className:`browser-notice`,role:`status`,children:i(`browserLocationUnknown`)})]}),(0,K.jsx)(`div`,{className:`browser-direct-viewport`,children:h?(0,K.jsx)(`iframe`,{"data-openpi-browser-page":v,"data-openpi-browser-document":y.page?.document,"data-openpi-browser-url":y.page?.url,"data-openpi-browser-title":y.page?.title,src:h,title:i(`browserPageTitle`,{address:new URL(h).host}),referrerPolicy:`no-referrer`,sandbox:`allow-scripts allow-forms allow-same-origin allow-popups allow-popups-to-escape-sandbox`,onLoad:()=>m(e=>e.revision===p.revision?{...e,loaded:!0,unknown:e.loaded}:e)},p.revision):(0,K.jsxs)(`div`,{className:`workbar-empty`,children:[(0,K.jsx)(me,{"aria-hidden":`true`}),(0,K.jsx)(`strong`,{children:i(`browserReady`)}),(0,K.jsx)(`p`,{children:i(`browserDirectDescription`)})]})}),(0,K.jsx)(`p`,{className:`browser-notice`,children:i(y.ready?`browserEnhancedHint`:`browserDirectHint`)})]})}function Mz({onReady:e}={}){let{t}=cr(),n=(0,_.useId)(),r=wk(),[i,a]=(0,_.useState)(r?.browser?.tabs??[{id:0,title:``}]),o=(0,_.useRef)(Math.max(...i.map(e=>e.id))+1),s=(0,_.useRef)(i);s.current=i;let[c,l]=(0,_.useState)(),[u,d]=(0,_.useState)(r?.browser?.selected??0);(0,_.useLayoutEffect)(()=>{r&&(r.browser={tabs:i,selected:u,pages:r.browser?.pages??{}})},[r,i,u]);let f=e=>{requestAnimationFrame(()=>document.getElementById(`${n}-tab-${e}`)?.focus())},p=(e=``)=>{if(s.current.length>=Az){e&&l(e);return}let t={id:o.current++,title:e?new URL(e).host:``,initialUrl:e},r=[...s.current,t];return s.current=r,a(r),d(t.id),l(void 0),f(t.id),`${n}-page-${t.id}`},m=(0,_.useRef)(p);m.current=p,(0,_.useEffect)(()=>(e?.(e=>m.current(e)),()=>e?.(void 0)),[e]);let h=e=>{r?.browser&&delete r.browser.pages[e],l(void 0);let t=i.filter(t=>t.id!==e);if(!t.length){let e={id:o.current++,title:``};a([e]),d(e.id),f(e.id)}else if(a(t),u===e){let n=i.findIndex(t=>t.id===e),r=t[Math.min(n,t.length-1)];d(r.id),f(r.id)}};return(0,K.jsxs)(`div`,{className:`browser-workspace`,children:[(0,K.jsxs)(`div`,{className:`browser-tabs-header`,children:[(0,K.jsx)(`div`,{role:`tablist`,"aria-label":t(`browserTabs`),className:`browser-tabs`,onKeyDown:e=>{if(!(e.target instanceof HTMLElement)||e.target.getAttribute(`role`)!==`tab`)return;let t=e.target.id,r=i.findIndex(e=>`${n}-tab-${e.id}`===t),a=r;if(e.key===`ArrowRight`)a=(r+1)%i.length;else if(e.key===`ArrowLeft`)a=(r+i.length-1)%i.length;else if(e.key===`Home`)a=0;else if(e.key===`End`)a=i.length-1;else if(e.key===`Delete`){e.preventDefault(),e.stopPropagation(),h(i[r].id);return}else return;e.preventDefault(),e.stopPropagation(),d(i[a].id),f(i[a].id)},children:i.map(e=>(0,K.jsxs)(`div`,{className:`browser-tab`,"data-active":e.id===u,children:[(0,K.jsxs)(`button`,{type:`button`,role:`tab`,id:`${n}-tab-${e.id}`,"aria-selected":e.id===u,"aria-controls":`${n}-page-${e.id}`,tabIndex:e.id===u?0:-1,onClick:()=>d(e.id),children:[(0,K.jsx)(me,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:e.title||t(`browserNewTab`)})]}),(0,K.jsx)(`button`,{type:`button`,"aria-label":t(`browserCloseTab`,{title:e.title||t(`browserNewTab`)}),title:t(`close`),onClick:()=>h(e.id),children:(0,K.jsx)(Lt,{"aria-hidden":`true`})})]},e.id))}),(0,K.jsx)(`button`,{type:`button`,className:`browser-add-tab`,"aria-label":t(`browserAddTab`),title:i.length>=Az?t(`browserTabLimit`,{count:Az}):t(`browserAddTab`),disabled:i.length>=Az,onClick:()=>p(),children:(0,K.jsx)(lt,{"aria-hidden":`true`})})]}),c&&(0,K.jsxs)(`p`,{className:`browser-notice`,role:`status`,children:[t(`browserTabLimit`,{count:Az}),` ·`,` `,(0,K.jsx)(`a`,{href:c,target:`_blank`,rel:`noopener noreferrer`,children:t(`openExternalBrowser`)})]}),(0,K.jsx)(`div`,{className:`browser-pages`,children:i.map(e=>(0,K.jsx)(`div`,{role:`tabpanel`,id:`${n}-page-${e.id}`,"aria-labelledby":`${n}-tab-${e.id}`,className:`browser-page`,hidden:u!==e.id,children:(0,K.jsx)(jz,{readingId:e.id,initialUrl:e.initialUrl,onOpen:p,onTitle:t=>a(n=>n.map(n=>n.id===e.id?{...n,title:t}:n))})},e.id))})]})}var Nz=2,Pz=1,Fz=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(Nz,Math.floor(u/e.css.cell.width)),rows:Math.max(Pz,Math.floor(l/e.css.cell.height))}}},Iz=Object.defineProperty,Lz=Object.getOwnPropertyDescriptor,Rz=(e,t)=>{for(var n in t)Iz(e,n,{get:t[n],enumerable:!0})},zz=(e,t,n,r)=>{for(var i=r>1?void 0:r?Lz(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&Iz(t,n,i),i},Bz=(e,t)=>(n,r)=>t(n,r,e),Vz=`Terminal input`,Hz={get:()=>Vz,set:e=>Vz=e},Uz=`Too much output to announce, navigate to rows manually to read`,Wz={get:()=>Uz,set:e=>Uz=e};function Gz(e){return e.replace(/\r?\n/g,`\r`)}function Kz(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function qz(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function Jz(e,t,n,r){e.stopPropagation(),e.clipboardData&&Yz(e.clipboardData.getData(`text/plain`),t,n,r)}function Yz(e,t,n,r){e=Gz(e),e=Kz(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function Xz(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function Zz(e,t,n,r,i){Xz(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Qz(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function $z(e,t=0,n=e.length){let r=``;for(let i=t;i65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var eB=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o);continue}i!==65279&&(t[r++]=i)}return r}},tB=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(c=(i&31)<<6|a&63,c<128){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},nB=``,rB=` `,iB=class e{constructor(){this.fg=0,this.bg=0,this.extended=new aB}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},aB=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},oB=class e extends iB{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new aB,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Qz(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},sB=`di$target`,cB=`di$dependencies`,lB=new Map;function uB(e){return e[cB]||[]}function dB(e){if(lB.has(e))return lB.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);fB(t,e,r)};return t._id=e,lB.set(e,t),t}function fB(e,t,n){t[sB]===t?t[cB].push({id:e,index:n}):(t[cB]=[{id:e,index:n}],t[sB]=t)}var pB=dB(`BufferService`),mB=dB(`CoreMouseService`),hB=dB(`CoreService`),gB=dB(`CharsetService`),_B=dB(`InstantiationService`),vB=dB(`LogService`),yB=dB(`OptionsService`),bB=dB(`OscLinkService`),xB=dB(`UnicodeService`),SB=dB(`DecorationService`),CB=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new oB,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;ti?i.activate(e,t,a):wB(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};CB=zz([Bz(0,pB),Bz(1,yB),Bz(2,bB)],CB);function wB(e,t){if(confirm(`Do you want to navigate to ${t}? +`]},e.number))}):(0,K.jsx)(UL,{className:`evidence-log`,"aria-label":`Tool output`,children:u.output||o(`noOutput`)}),u.kind===`file`&&u.truncated&&(0,K.jsx)(`p`,{children:o(`toolReadMore`)}),u.recovery&&(0,K.jsxs)(`p`,{children:[o(`toolFullOutputReference`),` `,(0,K.jsx)(`code`,{children:u.recovery})]}),u.readRecovery&&(0,K.jsx)(`p`,{className:`evidence-warning`,children:u.readRecovery}),(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{children:o(`toolRawEvidence`)}),(0,K.jsx)(`p`,{children:(0,K.jsx)(`code`,{children:e.name})}),(0,K.jsx)(`p`,{children:(0,K.jsx)(`strong`,{children:o(`toolCallArguments`)})}),(0,K.jsx)(`pre`,{children:u.rawArguments}),(0,K.jsx)(`p`,{children:(0,K.jsx)(`strong`,{children:o(`toolCallOutput`)})}),(0,K.jsx)(`pre`,{children:u.rawResult})]})]})]})}function GL({changes:e,onReview:t}){let{t:n}=cr(),[r,i]=(0,_.useState)(!1),a=(0,_.useId)();if(e.state===`unavailable`||e.files.length===0)return null;let o=e.state===`partial`,s=e.source===`file-tools`,c=e.fileCount===null,l=r?e.files:e.files.slice(0,3);return(0,K.jsxs)(`section`,{className:`turn-changes`,"aria-label":n(`turnChangesReview`),children:[(0,K.jsxs)(`header`,{className:`turn-changes-header`,children:[(0,K.jsx)(`span`,{className:`turn-changes-icon`,"aria-hidden":`true`,children:(0,K.jsx)(ye,{})}),(0,K.jsxs)(`div`,{className:`turn-changes-summary`,children:[(0,K.jsx)(`strong`,{title:n(s?`turnEditsScope`:`turnChangesScope`),children:n(s?c?`turnEditsPartial`:`turnEdits`:o?`turnChangesPartial`:`turnChanges`,{count:e.fileCount??e.files.length})}),!c&&!e.files.some(e=>e.binary||e.statsUnavailable)&&(0,K.jsxs)(`span`,{className:`turn-changes-totals`,children:[(0,K.jsxs)(`span`,{className:`review-additions`,children:[`+`,e.additions]}),(0,K.jsxs)(`span`,{className:`review-deletions`,children:[`−`,e.deletions]})]}),o&&!s&&(0,K.jsx)(`span`,{className:`turn-changes-warning`,children:n(`turnChangesIncomplete`)})]}),(0,K.jsx)(`button`,{type:`button`,className:`turn-changes-review-button`,"aria-label":n(`turnChangesReview`),disabled:!t,onClick:()=>t?.(e.promptEntryId,e.files[0]?.path),children:n(`reviewChanges`)})]}),(0,K.jsx)(`div`,{className:`turn-changes-list`,id:a,children:l.map(r=>{let i=Math.max(r.path.lastIndexOf(`/`),r.path.lastIndexOf(`\\`));return(0,K.jsxs)(`button`,{type:`button`,className:`turn-changes-file`,title:r.path,disabled:!t,onClick:()=>t?.(e.promptEntryId,r.path),children:[(0,K.jsxs)(`span`,{className:`turn-changes-path`,children:[(0,K.jsx)(`span`,{children:r.path.slice(0,i+1)}),(0,K.jsx)(`strong`,{children:r.path.slice(i+1)})]}),(0,K.jsx)(`span`,{className:`turn-changes-file-stats`,children:r.binary?(0,K.jsx)(`span`,{children:n(`gitReviewBinaryShort`)}):r.statsUnavailable?(0,K.jsx)(`span`,{title:n(`turnEditReason_${r.statsUnavailable}`),children:n(`turnEditStatsUnknown`)}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`span`,{className:`review-additions`,children:[`+`,r.additions]}),(0,K.jsxs)(`span`,{className:`review-deletions`,children:[`−`,r.deletions]})]})})]},r.path)})}),e.files.length>3&&(0,K.jsxs)(`button`,{type:`button`,className:`turn-changes-more`,"aria-expanded":r,"aria-controls":a,onClick:()=>i(e=>!e),children:[n(r?`turnChangesLess`:`turnChangesMore`,{count:e.files.length-3}),(0,K.jsx)(L,{className:r?`up`:``,"aria-hidden":`true`})]})]})}function KL({item:e,position:t,current:n,onNavigate:r,onPreview:i}){let{t:a}=cr(),o=(0,_.useRef)(()=>{}),s=yd({placement:`start`,delay:150,hideDelay:100,touchTrigger:`none`,onShow:(0,_.useCallback)(()=>i(e.entryId,()=>o.current()),[e.entryId,i])});return o.current=s.hide,(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{ref:s.ref,className:`turn-tick`,type:`button`,"data-turn-entry":e.entryId,"aria-label":a(`conversationTurnPosition`,{position:t}),"aria-describedby":s.describedBy,"aria-current":n?`location`:void 0,onClick:()=>{s.hide(),r(e.entryId)},children:(0,K.jsx)(`span`,{className:`turn-tick-mark`,"aria-hidden":`true`})}),s.renderHoverCard((0,K.jsx)(`span`,{className:`turn-preview`,children:e.previewState===`idle`||e.previewState===`loading`?(0,K.jsx)(`span`,{role:`status`,children:a(`turnPreviewLoading`)}):e.previewState===`unavailable`?(0,K.jsx)(`span`,{role:`status`,children:a(`turnPreviewUnavailable`)}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{className:`turn-preview-prompt`,children:e.title}),e.reply&&(0,K.jsx)(`span`,{className:`turn-preview-reply`,children:e.reply})]})}),{className:`turn-preview-layer`})]})}function qL({items:e,viewport:t,onNavigate:n,readingHistory:r,onRequestPreview:i,enabled:a=!0,onHidden:o}){let{t:s}=cr(),c=(0,_.useRef)(null),l=JSON.stringify(e.map(e=>e.entryId)),u=(0,_.useRef)(null),d=(0,_.useRef)(null),f=(0,_.useRef)(!1),p=(0,_.useRef)(0),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)({top:0,height:0,visible:!1,current:[]}),y=(0,_.useCallback)(()=>{u.current?.hide(),u.current=null,d.current&&d.current.captureTarget.hasPointerCapture?.(d.current.pointerId)&&d.current.captureTarget.releasePointerCapture(d.current.pointerId),d.current=null,p.current++,o?.()},[o]),b=(0,_.useCallback)((e,n)=>{if(!a||!t.current||!c.current||c.current.style.visibility===`hidden`||t.current.checkVisibility?.()===!1||c.current.checkVisibility?.()===!1||getComputedStyle(t.current).display===`none`||getComputedStyle(c.current).display===`none`){n();return}u.current?.entryId!==e&&u.current?.hide(),u.current={entryId:e,hide:n},i?.(e)},[a,t,i]),x=(0,_.useCallback)((e,t=!1)=>{u.current?.hide();let r=++p.current;h(!1),Promise.resolve(n(e,t)).then(e=>{p.current===r&&e===!1&&h(!0)})},[n]);return(0,_.useLayoutEffect)(()=>{let e=t.current,n=e?.parentElement,i=JSON.parse(l);if(!e||!n){y();return}let o,s=r?n.querySelector(`.jump-to-latest`):null,u=()=>{o=void 0;let t=e.getBoundingClientRect(),r=n.getBoundingClientRect(),l=new Map;for(let t of e.querySelectorAll(`[data-history-entry]`)){let e=t.dataset.historyEntry;e&&!l.has(e)&&l.set(e,t)}let u=e.querySelector(`.conversation-turn`)??l.values().next().value,d=e.offsetWidth>0?t.width/e.offsetWidth:1,f=a&&t.height>0&&d>0&&!!u&&(t.right-u.getBoundingClientRect().right)/d>=48&&e.checkVisibility?.()!==!1&&getComputedStyle(e).display!==`none`&&(!c.current||getComputedStyle(c.current).display!==`none`);f||y();let p=s?.getBoundingClientRect(),m=Math.min(t.bottom-8,p&&p.height>0?p.top-12:1/0),h=Math.max(0,m-t.top-8),g=i.flatMap(e=>{let n=l.get(e);if(!n)return[];let r=(n.closest(`.conversation-turn`)??n).getBoundingClientRect();return r.bottom>t.top+16&&r.tope.top===_.top&&e.height===_.height&&e.visible===f&&e.current.join(`\0`)===g.join(`\0`)?e:_)},d=()=>{o===void 0&&(o=requestAnimationFrame(u))};u(),e.addEventListener(`scroll`,d),window.addEventListener(`resize`,d);let f=typeof ResizeObserver>`u`?void 0:new ResizeObserver(d);f?.observe(e),f?.observe(n),s&&f?.observe(s);for(let t of e.children)f?.observe(t);let p=new MutationObserver(d);return p.observe(e,{childList:!0,subtree:!0}),()=>{o!==void 0&&cancelAnimationFrame(o),e.removeEventListener(`scroll`,d),window.removeEventListener(`resize`,d),f?.disconnect(),p.disconnect()}},[l,t,r,a,y]),(0,_.useLayoutEffect)(()=>{if(g.height,!g.visible||d.current)return;let e=c.current,t=Array.from(e?.querySelectorAll(`[data-turn-entry]`)??[]),n=t.find(e=>e===document.activeElement)??t.find(e=>e.matches(`:hover`))??t.find(e=>g.current.includes(e.dataset.turnEntry??``));if(!e||!n)return;let r=e.getBoundingClientRect(),i=n.getBoundingClientRect();i.topr.bottom&&(e.scrollTop+=i.bottom-r.bottom)},[g.current,g.height,g.visible,l]),(0,_.useLayoutEffect)(()=>{let n=t.current;if(!n)return;let r=t=>{if(!a||t.defaultPrevented||t.isComposing||!t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||![`ArrowUp`,`ArrowDown`].includes(t.key)||!n.parentElement?.contains(document.activeElement)||n.checkVisibility?.()===!1||getComputedStyle(n).display===`none`||getComputedStyle(n).visibility===`hidden`||n.getBoundingClientRect().height<=0)return;let r=new Map;for(let e of n.querySelectorAll(`[data-history-entry]`)){let t=e.dataset.historyEntry;t&&!r.has(t)&&r.set(t,e)}let i=e.flatMap((e,t)=>{let n=r.get(e.entryId);return n?[{item:e,index:t,top:n.getBoundingClientRect().top}]:[]}),o=n.getBoundingClientRect().top,s;if(t.key===`ArrowDown`){let t=i.findIndex(e=>e.top>o+24);s=i.length===0?e[0]:t<0?e[i.at(-1).index+1]:e[(i[t-1]?.index??-1)+1]}else{for(let t=i.length-1;t>=0;t--){let n=i[t];if(Math.abs(n.top-o)<=24){s=e[n.index-1];break}if(n.tope.top>o+24)&&(s=i[0]?.item),i.length===0&&(s=e.at(-1))}s&&(t.preventDefault(),x(s.entryId))};return document.addEventListener(`keydown`,r),()=>document.removeEventListener(`keydown`,r)},[t,a,e,x]),(0,_.useLayoutEffect)(()=>()=>y(),[y]),e.length<4?null:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`nav`,{ref:c,className:`turn-rail`,"aria-label":s(`conversationTurns`),style:{top:g.top,maxHeight:g.height,visibility:g.visible?`visible`:`hidden`},onClickCapture:e=>{f.current&&=(e.preventDefault(),e.stopPropagation(),!1)},onPointerDown:e=>{if(!e.isPrimary||e.button!==0)return;let t=e.target instanceof Element?e.target.closest(`.turn-tick`):null;!t||!e.currentTarget.contains(t)||(f.current=!1,d.current={pointerId:e.pointerId,captureTarget:t,y:e.clientY,moved:!1},t.setPointerCapture?.(e.pointerId))},onPointerMove:e=>{let t=d.current;if(!t||t.pointerId!==e.pointerId||Math.abs(e.clientY-t.y)<3&&!t.moved)return;t.moved=!0,f.current=!0;let n=Array.from(e.currentTarget.querySelectorAll(`[data-turn-entry]`)).find(t=>{let n=t.getBoundingClientRect();return e.clientY>=n.top&&e.clientY{let t=d.current;d.current=null,t?.captureTarget.hasPointerCapture?.(e.pointerId)&&t.captureTarget.releasePointerCapture(e.pointerId)},onPointerCancel:e=>{let t=d.current;d.current=null,t?.captureTarget.hasPointerCapture?.(e.pointerId)&&t.captureTarget.releasePointerCapture(e.pointerId),f.current=!1},children:e.map((e,t)=>(0,K.jsx)(KL,{item:e,position:t+1,current:g.current.includes(e.entryId),onNavigate:x,onPreview:b},e.entryId))}),m&&(0,K.jsx)(`span`,{className:`turn-navigation-error`,role:`status`,children:s(`turnPreviewUnavailable`)})]})}function JL({message:e,sessionId:t,path:n,entryId:r}){let{t:i}=cr(),[a,o]=(0,_.useState)(null),s=JSON.stringify([t,n,r]),c=e.parts?.filter(e=>e.type===`image`)??[];if(c.length===0)return null;let l=new Map,u=a?.scope===s?a:null,d=()=>o(e=>e?{...e,open:!1}:null);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`section`,{className:`message-attachments`,"aria-label":i(`imageAttachments`),children:c.map(e=>{let a=`${e.mimeType}:${e.name??``}:${e.previewUrl??``}`,c=l.get(a)??0;l.set(a,c+1);let u=`${a}:${c}`,d=t&&n&&r&&typeof e.sourcePartIndex==`number`&&Number.isSafeInteger(e.sourcePartIndex)&&e.sourcePartIndex>=0?{id:`${r}:${e.sourcePartIndex}`,entryId:r,partIndex:e.sourcePartIndex,kind:`image`,name:e.name??i(`attachedImage`)}:null,f=e.previewUrl?(0,K.jsx)(`img`,{src:e.previewUrl,alt:e.name??i(`attachedImage`)},`preview`):d&&t&&n?(0,K.jsx)(`span`,{className:`message-attachment-preview`,children:(0,K.jsx)(PI,{sessionId:t,path:n,source:d,thumbnail:!0})},`preview`):(0,K.jsx)(Ne,{"aria-hidden":`true`},`preview`),p=(0,K.jsx)(`span`,{children:e.name??i(`attachedImage`)},`name`);return d?(0,K.jsxs)(`button`,{className:`message-attachment`,type:`button`,title:d.name,"aria-label":d.name,onClick:()=>o({scope:s,source:d,open:!0}),children:[f,p]},u):(0,K.jsxs)(`div`,{className:`message-attachment`,children:[f,p]},u)})}),t&&n&&u&&(0,K.jsx)(II,{sessionId:t,path:n,source:u.source,open:u.open,onSelect:d,onClose:d})]})}function YL(e,t,n){let r=(0,_.useMemo)(()=>new rf,[]),i=e?.history?.leafEntryId??e?.entries.at(-1)?.id,a=e?.id,o=e?.path,s=JSON.stringify([e?.id,e?.path,i]),c=(0,_.useRef)(s);c.current=s;let[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)({}),p=(0,_.useRef)(new Map),m=(0,_.useMemo)(()=>a&&o&&i?{sessionId:a,sessionPath:o,entryId:i}:null,[a,o,i]);(0,_.useEffect)(()=>{if(u(null),f({}),!n||!m)return;let e=new AbortController,t=async()=>{try{let t=null,n=[],i=new Set;for(let a=0;a<10;a++){let a=await r.sessionPromptHistory(m,t,e.signal);if(e.signal.aborted||c.current!==s||a.sessionId!==m.sessionId||a.sessionPath!==m.sessionPath||a.anchorEntryId!==m.entryId||a.requestedBeforeEntryId!==t||a.entryIds.length>100||a.entryIds.some(e=>!e||i.has(e))||new Set(a.entryIds).size!==a.entryIds.length||a.nextBeforeEntryId!==null&&(a.entryIds.length===0||a.nextBeforeEntryId!==a.entryIds[0]))return;for(let e of a.entryIds)i.add(e);if(n=[...a.entryIds,...n],a.nextBeforeEntryId===null){u({scope:s,ids:n});return}t=a.nextBeforeEntryId}}catch{}},i=typeof window.requestIdleCallback==`function`?window.requestIdleCallback(()=>void t(),{timeout:2e3}):void 0,a=i===void 0?window.setTimeout(()=>void t(),0):void 0;return()=>{e.abort(),i!==void 0&&window.cancelIdleCallback(i),a!==void 0&&window.clearTimeout(a);for(let e of p.current.values())e.abort();p.current.clear()}},[s,n,m,r]);let h=(0,_.useMemo)(()=>{let e=new Map(t.map(e=>[e.entryId,e]));if(l?.scope!==s)return t;let n=new Set(l.ids);return[...l.ids.map(t=>e.get(t)??d[t]??{entryId:t,title:``,previewState:`idle`}),...t.filter(e=>!n.has(e.entryId))]},[l,s,t,d]),g=(0,_.useRef)(h);return g.current=h,{items:h,requestPreview:(0,_.useCallback)(e=>{if(!n||!m||c.current!==s||p.current.has(e))return;let t=g.current.find(t=>t.entryId===e);if(!t||t.previewState===void 0||t.previewState===`ready`)return;let i=new AbortController;p.current.set(e,i),f(t=>({...t,[e]:{entryId:e,title:``,previewState:`loading`}})),r.sessionPromptPreview(m,e,i.signal).then(t=>{if(!(i.signal.aborted||c.current!==s)){if(t.sessionId!==m.sessionId||t.sessionPath!==m.sessionPath||t.anchorEntryId!==m.entryId||t.entryId!==e||typeof t.prompt!=`string`||typeof t.response!=`string`||Array.from(t.prompt).length>240||Array.from(t.response).length>240)throw Error(`Unverified preview`);f(n=>({...n,[e]:{entryId:e,title:t.prompt,reply:t.response,previewState:`ready`}}))}}).catch(()=>{!i.signal.aborted&&c.current===s&&f(t=>({...t,[e]:{entryId:e,title:``,previewState:`unavailable`}}))}).finally(()=>{p.current.get(e)===i&&p.current.delete(e)})},[n,m,s,r])}}var XL=1e3,ZL=Wd*4;function QL(e,t){return t.history?.leafEntryId===e.validatedLeaf||t.history?.anchorEntryId===e.anchor&&t.history.anchorOnBranch===!0}function $L(e,t,n=t.entriesOmitted){let r=e.filter(e=>e.message?.truncation).length,i=e.reduce((e,t)=>e+(t.message?.truncation?.partsOmitted??0),0);return{...t,entriesOmitted:n,messagesTruncated:r,messagePartsOmitted:i,truncated:n>0||r>0||i>0}}function eR(e,t){let n=t.history?.leafEntryId??null;if(n===e.validatedLeaf)return e;let r=t.entries.findIndex(t=>t.id===e.anchor),i=r>=0?t.entries.slice(r+1):t.entries[0]?.parentId===e.anchor?t.entries:null,a=i?.reduce((e,t)=>e+Kd(t)+1,0)??0;return i&&e.session.entries.length+i.length<=XL&&e.session.bytes+a<=ZL?{...e,anchor:n??e.anchor,validatedLeaf:n,session:{...e.session,entries:[...e.session.entries,...i],bytes:e.session.bytes+a,truncation:$L([...e.session.entries,...i],e.session.truncation)}}:{...e,validatedLeaf:n}}function tR(e,t,n,r){let i=(0,_.useMemo)(()=>new rf,[]),a=(0,_.useMemo)(()=>n??new Map,[n]),o=_L(e),s=(0,_.useRef)({scope:o,state:a.get(o)});s.current.scope!==o&&(s.current={scope:o,state:a.get(o)});let c=(0,_.useRef)({selected:e,callbacks:t});c.current={selected:e,callbacks:t};let l=(0,_.useRef)(s.current.state?.window??null),u=(0,_.useRef)(null),d=(0,_.useRef)(null),f=(0,_.useRef)(null),[p,m]=(0,_.useState)(l.current),[h,g]=(0,_.useState)(!1),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(0),S=(0,_.useRef)(o),C=(0,_.useRef)(null),w=r?JSON.stringify([r.sessionId,r.sessionPath,r.entryId,r.revision]):null,T=r&&e&&w!==C.current&&r.sessionId===e.id&&r.sessionPath===e.path&&r.session.id===e.id&&r.session.path===e.path&&r.session.history?.anchorEntryId===r.entryId&&r.session.history.anchorOnBranch===!0&&r.session.entries.some(e=>e.id===r.entryId)?{session:r.session,anchor:r.session.entries.at(-1).id,validatedLeaf:r.session.history?.leafEntryId??null}:null,E=(0,_.useCallback)(e=>{l.current=e,vL(a,_L(e.session),{window:e}),m(e),c.current.callbacks.onAnchorChange?.({sessionId:e.session.id,sessionPath:e.session.path,entryId:e.anchor})},[a]),D=(0,_.useCallback)((e=!1)=>{u.current?.controller.abort(),u.current=null,d.current=null,a.delete(_L(l.current?.session??c.current.selected)),l.current=null,a.persist?.(),m(null),g(!1),y(e?`historyChanged`:null),f.current=null,c.current.callbacks.onAnchorChange?.(null),x(e=>e+1)},[a]),O=(0,_.useCallback)((e=!1)=>{let t=l.current,n=c.current.selected;if(!t||!n)return;let r=JSON.stringify([_L(n),t.anchor,n.history?.leafEntryId]);if(!e&&f.current===r)return;f.current=r,y(null);let i=()=>{f.current===r&&l.current===t&&(u.current?.controller.abort(),u.current=null,g(!1),y(`historyValidationUnavailable`))};c.current.callbacks.onAnchorChange?.({sessionId:t.session.id,sessionPath:t.session.path,entryId:t.anchor});let a=c.current.callbacks.onRefresh?.();if(!a){i();return}a.then(e=>{e||i()}).catch(i)},[]),k=(0,_.useCallback)(e=>{let t=l.current,n=c.current.selected;if(!e.page||!e.consuming||u.current!==e||e.controller.signal.aborted||!t||!n||e.scope!==_L(n)||t.session.history?.beforeEntryId!==e.before||!QL(t,n))return;let r=e.page,i=new Set(t.session.entries.map(e=>e.id)),a=[...r.entries.filter(e=>!i.has(e.id)),...t.session.entries],o=Kd(a);for(;a.length>XL||o>ZL;){let e=a.pop();if(!e)break;o-=Kd(e)+ +!!a.length}c.current.callbacks.beforePrepend(),E({...t,anchor:a.at(-1)?.id??t.anchor,session:{...t.session,entries:a,bytes:o,truncation:$L(a,t.session.truncation,r.truncation.entriesOmitted),history:{...t.session.history,beforeEntryId:r.history?.beforeEntryId??null}}}),u.current=null,g(!1),y(null)},[E]);(0,_.useLayoutEffect)(()=>{if(T&&w!==C.current){S.current=o,u.current?.controller.abort(),u.current=null,d.current=null,f.current=null,g(!1),y(null),C.current=w,E(T);return}S.current!==o&&(S.current=o,u.current?.controller.abort(),u.current=null,d.current=null,l.current=s.current.state?.window??null,m(l.current),g(!1),y(null),f.current=null,x(e=>e+1),l.current||c.current.callbacks.onAnchorChange?.(null));let t=u.current;t&&!t.consuming&&e&&!QL(t.source,e)&&(t.controller.abort(),u.current=null);let n=l.current;if(!(!n||!e)){if(e.history?.anchorEntryId===n.anchor&&e.history.anchorOnBranch===!1){D(!0),c.current.callbacks.onRefresh?.();return}if(!QL(n,e)){O();return}y(e=>e===`historyValidationUnavailable`?null:e),(e.history?.leafEntryId??null)!==n.validatedLeaf&&(n=eR(n,e),E(n)),u.current?.page&&k(u.current)}},[o,e,D,O,E,k,T,w]),(0,_.useLayoutEffect)(()=>{let e=l.current;return e&&(vL(a,o,{...s.current.state,window:e}),c.current.callbacks.onAnchorChange?.({sessionId:e.session.id,sessionPath:e.session.path,entryId:e.anchor})),()=>{u.current?.controller.abort(),u.current=null,d.current=null,c.current.callbacks.onAnchorChange?.(null)}},[o,a]);let A=(0,_.useCallback)(()=>{let e=c.current.selected;return!l.current&&e?.history?.leafEntryId&&E({session:e,anchor:e.history.leafEntryId,validatedLeaf:e.history.leafEntryId}),l.current},[E]),j=(0,_.useCallback)((e,t)=>{let n=c.current.selected;if(!n||u.current)return;let r=e.session.history?.beforeEntryId;if(!r)return;let a={controller:new AbortController,scope:_L(n),before:r,source:e,consuming:t,anchor:{sessionId:n.id,sessionPath:n.path,entryId:e.anchor}};return u.current=a,t&&(g(!0),y(null)),a.done=(async()=>{try{let e=await i.sessionHistory(a.anchor,r,a.controller.signal);if(u.current!==a||a.controller.signal.aborted||a.scope!==_L(c.current.selected))return;if(e.id!==n.id||e.path!==n.path||e.anchorEntryId!==a.anchor.entryId||e.requestedBeforeEntryId!==r||e.history?.anchorEntryId!==a.anchor.entryId||e.history.anchorOnBranch!==!0)throw new tf(`Session history identity changed`,409,`SESSION_HISTORY_CHANGED`);a.page=e,a.consuming&&(k(a),u.current===a&&O())}catch(e){if(u.current!==a||a.controller.signal.aborted||(u.current=null,!a.consuming))return;g(!1),e instanceof tf&&e.code===`SESSION_HISTORY_CHANGED`?(D(!0),c.current.callbacks.onRefresh?.()):y(`historyUnavailable`)}})(),a.done},[k,D,i,O]),M=(0,_.useCallback)(async()=>{let e=c.current.selected;if(!e?.history?.leafEntryId)return;let t=l.current;if(t&&!QL(t,e)){O(!0);return}if(t||=A(),!t)return;let n=u.current;if(n){if(n.scope===_L(e)&&n.before===t.session.history?.beforeEntryId&&QL(n.source,e))return n.consuming=!0,g(!0),y(null),n.page&&k(n),n.done;n.controller.abort(),u.current=null}return j(t,!0)},[k,j,O,A]);(0,_.useEffect)(()=>{if(!t.preload){let e=u.current;e&&!e.consuming&&(e.controller.abort(),u.current=null,d.current=null);return}if(v||u.current||!e||p!==l.current)return;let n=p;if(n&&!QL(n,e))return;let r=n??(e.history?.leafEntryId?{session:e,anchor:e.history.leafEntryId,validatedLeaf:e.history.leafEntryId}:null);if(!r?.session.history?.beforeEntryId)return;let i=JSON.stringify([o,n?r.anchor:`initial`,n?r.session.history.beforeEntryId:null]);d.current!==i&&(d.current=i,j(r,!1))},[t.preload,v,o,e,p,j]);let N=p&&_L(p.session)===o?p:null,P=T??(N&&e&&QL(N,e)?eR(N,e):N),F=(0,_.useCallback)(()=>D(),[D]),I=!!(P&&e&&!QL(P,e));return{session:P?.session??e,engaged:!!P,hasMore:!!(P?.session??e)?.history?.beforeEntryId,hasNewer:!!(P&&P.anchor!==e?.history?.leafEntryId),verifying:I,loading:h,error:v,reset:b,retainReading:A,loadOlder:M,resetToLatest:F}}var nR;function rR(e,t){if(Object.is(e,t))return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n{c(!0),a(n,r).finally(()=>c(!1))},children:[(0,K.jsx)(ft,{"aria-hidden":`true`}),o(s?`retryingPrompt`:`retryPrompt`)]})})}):(0,K.jsx)(`div`,{className:`provider-outcome aborted`,role:`status`,children:o(`modelRequestStopped`)})}function fR({attempts:e,state:t,retry:n,observed:r=!0}){let{t:i}=cr(),a=t===`retrying`&&!r,o=n?.attempt,s=n?.maxAttempts,c=typeof o==`number`&&Number.isSafeInteger(o)&&o>0&&typeof s==`number`&&Number.isSafeInteger(s)&&s>=o,l=e.length>0||!!n?.errorMessage,u=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Pt,{"aria-hidden":`true`}),(0,K.jsxs)(`span`,{role:t===`retrying`?`status`:void 0,children:[i(a?`modelReconnectUnknown`:t===`recovered`?`modelRequestRecovered`:t===`retrying`?n?`modelReconnecting`:`modelEarlierAttempts`:t===`interrupted`?`modelRequestStopped`:`modelEarlierAttempts`),t===`retrying`&&c&&` ${o}/${s}`]}),t!==`retrying`&&(0,K.jsx)(`span`,{children:i(`modelFailedAttempts`,{count:e.length})}),l&&(0,K.jsx)(ee,{className:`reconnect-chevron`,"aria-hidden":`true`})]}),d=`provider-attempts ${t}${a?` unavailable`:``}`;return l?(0,K.jsxs)(`details`,{className:d,children:[(0,K.jsx)(`summary`,{children:u}),(0,K.jsxs)(`ol`,{children:[e.length===0&&(0,K.jsx)(`li`,{children:(0,K.jsx)(`p`,{children:n?.errorMessage})}),e.map(({entry:e,content:t})=>(0,K.jsxs)(`li`,{"data-history-entry":e.entryId??e.key,children:[(0,K.jsx)(`p`,{children:e.message.errorMessage||i(`modelFailureUnknown`)}),t?.map(e=>(0,K.jsx)(_.Fragment,{children:e.content},e.key))]},e.key))]})]}):(0,K.jsx)(`div`,{className:d,children:u})}function pR(e,t){let n=new Set,r=new Map,i=[],a=-1,o=(o,s=!1,c=!1)=>{if(i.length>0){let l=e[a]?.message.stopReason,u=o?.outcome===`cancelled`||l===`aborted`,d=l===`error`&&!u&&!(s&&t)&&!c;d&&n.add(a);let f=d?i.slice(0,-1):i,p=f.at(-1);p!==void 0&&r.set(p,{attempts:f.map(t=>e[t]),state:u?`interrupted`:l===`stop`||l===`length`||l===`toolUse`?`recovered`:s&&t?`retrying`:`earlier`})}i=[],a=-1};return e.forEach((e,t)=>{e.optimistic||(e.timing?o(e.timing):e.forkSnapshotBoundary?o(void 0,!1,!0):e.message.role===`user`||e.message.role===`custom`&&e.message.customType===`openpi-setup-request`?o():e.message.role===`assistant`&&(a=t,e.message.stopReason===`error`&&i.push(t)))}),o(void 0,!0),{finalErrors:n,groups:r}}function mR(e,t){return ej(nL(e,t).split(` +`).find(Boolean),120)}function hR(e){let t=e.split(` +`).map(e=>e.trim()).find(Boolean);return t?ej(t.replace(/^#{1,6}\s+/u,``).replace(/^>\s*/u,``).replace(/[*_~`]+/gu,``).replace(/\[([^\]]+)\]\([^)]*\)/gu,`$1`).trim(),600):``}function gR({body:e,icon:t,name:n,status:r,summary:i,output:a,evidenceState:o,note:s,rawDetails:c,snapshotMissingResult:l=!1,defaultOpen:u=!1}){let{t:d}=cr(),[f,p]=(0,_.useState)(u);(0,_.useEffect)(()=>p(u),[u]);let m=o??(r===`done`?`returned`:r===`error`?`failed`:r===`running`?`running`:`unknown`);return(0,K.jsxs)(`details`,{className:`message-details tool-line ${r}`,"data-tool":n,open:f,onToggle:e=>p(e.currentTarget.open),children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(`span`,{className:`tool-icon`,"aria-hidden":`true`,children:t}),(0,K.jsx)(`span`,{className:`tool-kind`,"aria-hidden":$I(n).action!==`call`,title:n,children:tL(n)}),(0,K.jsxs)(`span`,{className:`details-title`,children:[(0,K.jsx)(`span`,{className:`tool-action`,children:eL(d,n,m)}),i&&(0,K.jsx)(`span`,{className:`tool-summary`,children:i})]}),l&&(0,K.jsx)(`span`,{className:`evidence-status`,children:d(`toolSnapshotMissingResult`)}),(0,K.jsx)(ee,{className:`tool-disclosure`,"aria-hidden":`true`}),(0,K.jsx)(lR,{status:r})]}),s&&(0,K.jsx)(`p`,{className:`evidence-note`,children:s}),a===void 0?(0,K.jsx)(`pre`,{className:`details-body tool-evidence`,children:Fd(e).text}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`figure`,{"aria-label":d(`toolCallArguments`),style:{margin:0},children:(0,K.jsx)(`pre`,{className:`details-body tool-evidence`,children:Fd(e).text})}),(0,K.jsx)(`figure`,{"aria-label":d(`toolCallOutput`),style:{margin:0},children:(0,K.jsx)(`pre`,{className:`details-body tool-evidence`,children:Fd(a).text||d(`noOutput`)})})]}),c!==void 0&&(0,K.jsxs)(`details`,{className:`evidence-raw`,children:[(0,K.jsx)(`summary`,{children:d(`toolRawEvidence`)}),(0,K.jsx)(`pre`,{children:Fd(JSON.stringify(c,null,2)).text})]})]})}function _R({body:e,family:t,meta:n,status:r,title:i,defaultOpen:a=!1}){return(0,K.jsxs)(`details`,{className:`message-details activity-card ${t}`,open:a||void 0,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(`span`,{className:`activity-icon`,"aria-hidden":`true`,children:t===`subagent`?(0,K.jsx)(M,{}):(0,K.jsx)(Ft,{})}),(0,K.jsxs)(`span`,{className:`activity-main`,children:[(0,K.jsx)(`span`,{className:`activity-title`,children:i}),n&&(0,K.jsx)(`span`,{className:`activity-meta`,children:n})]}),(0,K.jsx)(lR,{status:r}),(0,K.jsx)(ee,{className:`tool-disclosure`,"aria-hidden":`true`})]}),(0,K.jsx)(`pre`,{className:`details-body tool-evidence`,children:e})]})}function vR(e,t,n={sessionId:``}){if(t?.forkSnapshotToolResult)return null;let{sessionId:r,subagents:i=[],records:a=[],workflows:o=[],onInspectSubagent:s,liveState:c,defaultOpen:l=!1,observed:u=!0}=n,d=e.name||``,f=oR(e.arguments),p=aR(t?.details),m=cR(t,c),h=!u&&m===`running`?`unknown`:m;if(d===`subagent_spawn`)return(0,K.jsx)(yR,{sessionId:r,id:typeof p.id==`string`?p.id:void 0,title:String(p.title||f.name||`subagent`),body:t?.content||String(f.prompt||e.arguments),activity:i.find(e=>e.id===p.id),saved:a.find(e=>e.id===p.id),spawnFailed:t?.isError===!0,observed:u,defaultOpen:l,onInspect:s});if(d.startsWith(`subagent`)){let n=d.replaceAll(`_`,` `).replace(/^subagent /u,``),r=i.find(e=>e.id===f.id)??a.find(e=>e.id===f.id);return(0,K.jsx)(_R,{family:`subagent`,defaultOpen:l,title:`${n[0]?.toUpperCase()||``}${n.slice(1)} · ${r?.title||f.id||`Subagent`}`,body:t?.content||e.arguments,status:h})}if(d===`workflow`){let n=typeof f.script==`string`?f.script:e.arguments,i=String(p.name||n.match(/\bname:\s*["'`]([^"'`]+)["'`]/u)?.[1]||`unnamed`),a=aR(p.agents),c=o.find(e=>e.runId===p.runId)?.children,l=[p.runId,p.status,a.total?`${Number(a.total)-Number(a.running||0)}/${a.total} agents`:``].filter(Boolean).join(` · `);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(_R,{family:`workflow`,title:`Workflow · ${i}`,meta:l,body:t?.content||n,status:h}),(0,K.jsx)(bR,{sessionId:r,tasks:c,observed:u,onInspect:s})]})}return d.startsWith(`workflow`)?(0,K.jsx)(_R,{family:`workflow`,title:d.replaceAll(`_`,` `),meta:String(f.runId||``),body:t?.content||e.arguments,status:h}):null}function yR({sessionId:e,id:t,title:n,body:r,activity:i,saved:a,spawnFailed:o,onInspect:s,defaultOpen:c=!1,observed:l=!0}){let{t:u}=cr(),d=i?.outcome===`interrupted`?`interrupted`:i?.status??(a?.state===`running`?void 0:a?.state),f=!l&&(d===`running`||!d&&!o)?`unknown`:d,p=u(f===`unknown`?`toolState_unknown`:f?`subagentState_${f}`:o?`subagentSpawnFailed`:t?`subagentStateUnavailable`:`subagentStarting`);return(0,K.jsxs)(`section`,{className:`activity-card subagent subagent-activity`,children:[(0,K.jsx)(TL,{identity:`${e}:${t??n}`,title:n,state:f,label:p,onInspect:t&&s?()=>s(t):void 0}),(c||o)&&(0,K.jsxs)(`details`,{className:`subagent-receipt`,open:c||void 0,children:[(0,K.jsx)(`summary`,{children:u(`subagentSpawnReceipt`)}),(0,K.jsx)(`p`,{children:u(`subagentSpawnReceiptHint`)}),(0,K.jsx)(`pre`,{className:`details-body tool-evidence`,children:r})]})]})}function bR({sessionId:e,tasks:t,observed:n,onInspect:r}){let{t:i}=cr();return(0,K.jsxs)(K.Fragment,{children:[t?.items.map(t=>{let a=t.outcome===`interrupted`?`interrupted`:!n&&t.status===`running`?`unknown`:t.status;return(0,K.jsx)(TL,{identity:`${e}:${t.id}`,title:t.title,state:a,label:i(a===`unknown`?`toolState_unknown`:`subagentState_${a}`),onInspect:r?()=>r(t.id,`workflows`):void 0},t.id)}),!!t?.omitted&&(0,K.jsx)(`p`,{className:`inspection-note`,children:i(`subagentListTruncated`,{count:t?.omitted})})]})}function xR({body:e,duration:t,status:n,level:r,defaultOpen:i,truncated:a,source:o}){let{t:s}=cr(),c=n===`running`,[l,u]=(0,_.useState)(i),[d,f]=(0,_.useState)();(0,_.useEffect)(()=>u(i),[i]);let p=t===void 0?``:nj(0,t),m=hR(e),h=[n===`unknown`?s(`toolState_unknown`):c?r?s(`thinkingActiveLevel`,{level:r}):s(`thinkingActive`):s(`thinkingDone`),p].filter(Boolean).join(` · `);return(0,K.jsxs)(`details`,{className:`message-details tool-line thinking-line ${n}`,open:l,onToggle:e=>u(e.currentTarget.open),children:[(0,K.jsxs)(`summary`,{"aria-label":[h,m].filter(Boolean).join(` · `),title:m,children:[(0,K.jsx)(`span`,{className:`tool-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Le,{})}),(0,K.jsx)(`span`,{className:`details-title`,children:(0,K.jsx)(`span`,{className:`tool-summary`,children:m||h})}),(0,K.jsx)(ee,{className:`tool-disclosure`,"aria-hidden":`true`})]}),l&&(0,K.jsx)(`div`,{className:`details-body thinking-evidence`,children:a&&o&&!c?(0,K.jsx)(FL,{...o,preview:e,markdown:!0,purpose:`thinking`,fullText:d,onComplete:f}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Sk,{children:e}),a&&(0,K.jsx)(`p`,{className:`evidence-warning`,children:s(`thinkingPreviewOnly`)})]})})]})}function SR({content:e,editable:t,copyRequiresFull:n=!1,timestamp:r,onResend:i,onRegenerate:a,onFork:o,canFork:s=!1,forkPending:c=!1}){let{t:l}=cr(),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(!1),g=(0,_.useRef)(0),v=(0,_.useRef)(void 0);(0,_.useEffect)(()=>()=>{g.current+=1,window.clearTimeout(v.current)},[]);let[y,b]=(0,_.useState)(!1),[x,S]=(0,_.useState)(e),[C,w]=(0,_.useState)(!1),T=(0,_.useRef)(null),E=(0,_.useId)();(0,_.useEffect)(()=>{y&&T.current?.focus()},[y]);let D=async()=>{if(!(C||!x.trim()||!t)){w(!0);try{await i(x.trim())&&b(!1)}finally{w(!1)}}};if(y)return(0,K.jsxs)(`div`,{className:`message-editor`,children:[(0,K.jsx)(`textarea`,{ref:T,value:x,"aria-label":l(`editMessage`),"aria-describedby":E,readOnly:C,onChange:e=>S(e.target.value),onKeyDown:e=>{e.nativeEvent.isComposing||C||(e.key===`Escape`&&b(!1),e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),D()))}}),(0,K.jsx)(`p`,{className:`message-edit-hint`,id:E,children:l(`editMessageHint`)}),(0,K.jsxs)(`div`,{className:`message-edit-actions`,children:[(0,K.jsx)(`button`,{type:`button`,disabled:C,onClick:()=>b(!1),children:l(`cancel`)}),(0,K.jsx)(`button`,{type:`button`,className:`confirm`,disabled:C||!x.trim()||!t,onClick:()=>void D(),children:l(`confirmEdit`)})]})]});let O=tj(r);return(0,K.jsxs)(`div`,{className:`message-actions${f?` copy-failed`:``}`,children:[O&&(0,K.jsx)(`time`,{dateTime:r,children:O}),o&&(0,K.jsx)(`button`,{type:`button`,"aria-label":l(`forkMessage`),title:l(c?`forkSessionPending`:s?`forkMessageHint`:`forkSessionUnavailable`),disabled:!s||c,onClick:()=>void o(),children:(0,K.jsx)(Ae,{"aria-hidden":`true`})}),t&&(0,K.jsx)(`button`,{type:`button`,"aria-label":l(`editMessage`),title:l(`editMessage`),onClick:()=>{S(e),b(!0)},children:(0,K.jsx)(at,{})}),a&&(0,K.jsx)(`button`,{type:`button`,"aria-label":l(`regenerateMessage`),title:l(`regenerateMessageHint`),disabled:!s||c,onClick:()=>void a(),children:(0,K.jsx)(ft,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{type:`button`,"aria-label":l(u?`copiedMessage`:`copyMessage`),title:l(n?`messageCopyRequiresFull`:u?`copiedMessage`:`copyMessage`),disabled:m||n,onClick:()=>{let t=++g.current;window.clearTimeout(v.current),h(!0),d(!1),p(!1),wd(e).then(e=>{t===g.current&&(h(!1),d(e),p(!e),e&&(v.current=window.setTimeout(()=>d(!1),1200)))})},children:u?(0,K.jsx)(I,{}):(0,K.jsx)(oe,{})}),f&&(0,K.jsx)(`span`,{className:`copy-error`,role:`status`,children:l(`copyFailed`)})]})}function CR({message:e,fullSubagent:t=!1,sessionId:n,onInspectSubagent:r}){let{t:i}=cr();if(e.customType===`openpi-web-command-feedback`)return(0,K.jsxs)(`div`,{className:`command-feedback`,role:`status`,children:[e.content,e.truncation?.truncated&&(0,K.jsx)(`p`,{children:i(`commandFeedbackTruncated`)})]});let a=aR(e.details);if(e.customType===`openpi-setup-request`||e.customType===`openpi-setup-closed`)return(0,K.jsx)(gR,{body:e.content,icon:(0,K.jsx)(It,{}),name:i(`configureOpenPi`),summary:e.customType===`openpi-setup-closed`?ej(e.content):void 0,status:`unknown`});if(e.customType===`subagent-result`){let o=Array.isArray(a.results)?a.results.map(aR):[a],s=new Set(aj([e]).map(e=>e.id));return(0,K.jsxs)(`section`,{className:`activity-card subagent subagent-activity`,children:[o.map(e=>{let t=typeof e.id==`string`?e.id:``,a=e.outcome===`interrupted`?`interrupted`:e.status===`done`||e.status===`error`||e.status===`running`?e.status:`unknown`;return(0,K.jsx)(TL,{identity:`${n}:${t}`,title:String(e.title||t||i(`subagentDetails`)),state:a,label:i(a===`unknown`?`unknownState`:`subagentState_${a}`),onInspect:r&&s.has(t)?()=>r(t):void 0},t||JSON.stringify(e))}),(0,K.jsxs)(`details`,{className:`subagent-result-evidence`,open:t||void 0,children:[(0,K.jsx)(`summary`,{children:i(`subagentBackgroundResult`,{count:o.length})}),(0,K.jsx)(`pre`,{className:`details-body tool-evidence`,children:!t&&typeof a.displayContent==`string`?a.displayContent:e.content})]})]})}if(e.customType===`workflow-result`){let t=Array.isArray(a.entries)?a.entries.map(aR):[],n=t.map(e=>sR(e.status)),r=n.includes(`error`)?`error`:n.includes(`warn`)?`warn`:n.length>0&&n.every(e=>e===`done`)?`done`:n.includes(`running`)?`running`:`unknown`,i=t.length?t.map(e=>`${e.status===`completed`?`✓`:`✗`} ${String(e.summary||e.runId||`run`)}${e.resultPreview?`\nResult: ${e.resultPreview}`:``}`).join(` +`):e.content;return(0,K.jsx)(_R,{family:`workflow`,title:t.length>1?`Workflow results · ${t.length} runs`:`Workflow ${String(t[0]?.runId||`result`)}`,body:i,status:r})}return null}function wR(e){return[``,`[]`,`{}`,`null`].includes(e.trim())}function TR(e){if(e.role===`toolResult`&&e.toolCallId)return`tool-result-${e.toolCallId}`;if(e.timestamp!==void 0)return`message-${e.role}-${e.timestamp}`}function ER(e){return[`assistant`,`toolResult`].includes(e.role??``)&&!e.truncation?.truncated?JSON.stringify(e):null}function DR(e){return JSON.stringify([e.role,e.content,(e.parts??[]).filter(t=>e.role!==`user`||t.type!==`text`).map(t=>t.type===`image`?[t.type,t.mimeType,e.role===`user`?void 0:t.name]:t.type),e.stopReason,e.errorMessage,e.toolCallId])}function OR(e){return e.role===`user`?DR(e):JSON.stringify({...e,timestamp:void 0})}var kR=new WeakMap;function AR(e,t){let n=kR.get(e),r=n?.get(t);if(r&&r.length===e.length&&r.head===e[0]&&r.tail===e[e.length-1])return r.projection;let i=new Map(e.map(e=>[e.id,e])),a=new Map;for(let t of e){let e=t.message&&ER(t.message);if(!e)continue;let n=a.get(e)??[];n.push(t),a.set(e,n)}let o=e.flatMap(e=>{if(e.forkSnapshotBoundary)return[{key:e.id,entryId:e.id,timestamp:e.timestamp,forkSnapshotBoundary:!0,message:{role:`custom`,content:``}}];if(e.type===`compaction`)return[{key:e.id,entryId:e.id,timestamp:e.timestamp,compaction:!0,message:{role:`custom`,content:``}}];if(`turnTiming`in e&&e.turnTiming&&e.turnTiming.sessionId===t)return[{key:e.id,timestamp:e.timestamp,timing:e.turnTiming,message:{role:`custom`,content:``}}];if(e.type!==`message`||!e.message)return[];let n=SL(e.message),r=CL(e,e=>i.get(e));return wL(e.message,r)?[]:[{key:e.id,entryId:e.id,timestamp:e.timestamp,message:n}]}).map(e=>({...e,persisted:!0})),s=new Map,c=new Map;o.forEach((e,t)=>{if(e.entryId&&s.set(e.entryId,t),e.timing||e.compaction||e.forkSnapshotBoundary)return;let n=TR(e.message)??e.entryId??e.key,r=c.get(n)??[];r.push(t),c.set(n,r)});let l=new Map,u=0;for(let t of e){if(t.message?.role!==`custom`||t.message.truncation?.truncated)continue;let e=OR(t.message),n=l.get(e)??[];n.push(u),l.set(e,n),u++}let d=o.map(e=>({identity:TR(e.message),signature:OR(e.message)})),f=new Map,p=new Map;d.forEach((e,t)=>{let n=p.get(e.signature)??[];if(n.push(t),p.set(e.signature,n),e.identity===void 0)return;let r=f.get(e.identity)??[];r.push(t),f.set(e.identity,r)});let m=new Map(e.map((e,t)=>[e.id,t])),h=o.filter(e=>e.message.role===`user`).map(e=>({key:e.entryId??e.key,position:m.get(e.entryId??e.key),parentId:i.get(e.entryId??e.key)?.parentId,signature:DR(e.message)})),g=new Map;for(let e of h){let t=g.get(e.signature)??[];t.push(e),g.set(e.signature,t)}let _={nativeById:i,exactNative:a,baseEntries:o,indexById:s,lookupIndexes:c,customIndexes:l,nativeByIdentity:f,nativeByLegacySignature:p,nativeMessages:d,promptCandidates:h,promptsBySignature:g,commandInputs:new Map(o.flatMap(e=>e.message.role===`user`&&e.message.customType===`openpi-web-command-input`&&e.message.commandId?[[e.message.commandId,e.entryId??e.key]]:[])),persistedPositions:m};return n||(n=new Map,kR.set(e,n)),n.set(t,{projection:_,length:e.length,head:e[0],tail:e[e.length-1]}),_}function jR(e,t){if(!e)return-1;for(let n of e)if(!t.has(n))return n;return-1}function MR(e,t){let n=[e.timingKey,e.key,e.entryId,TR(e.message)];for(let e of n){if(!e)continue;let n=t[e];if(n!==void 0)return n}}function NR(e,t,n){let r=e.selectedSession,i=AR(r?.entries??[],r?.id);for(let e of n.keys())i.nativeById.has(e)||n.delete(e);let a=new Map;for(let e of t){if(e.optimistic)continue;let t=ER(e.message);if(!t)continue;let n=a.get(t)??[];n.push(e),a.set(t,n)}let o=new Set(n.values());for(let[e,t]of i.exactNative){let r=a.get(e);if(t.length!==1||r?.length!==1)continue;let s=t[0].id,c=r[0].key;n.has(s)||o.has(c)||i.nativeById.has(c)||(n.set(s,c),o.add(c))}let s=new Map;for(let e of t){let t=TR(e.message)??e.key,n=i.lookupIndexes.get(t);if(n)for(let t of n)s.set(t,e.key)}let c=new Set(t.flatMap(e=>e.optimistic?.projectedEntryId?[e.optimistic.projectedEntryId]:[])),l=[],u=[],d=e.selectedExecution?.sessionId===r?.id&&e.selectedExecution?.sessionPath===r?.path?e.selectedExecution:void 0,f=d?.pendingFollowUps??0,p=Math.max(0,t.filter(e=>e.optimistic?.admitted&&!e.optimistic.projectedEntryId&&!i.commandInputs.has(e.optimistic.commandId)).length-f),m=0,h=new Set,g=new Set,_=new Set,v=[];for(let e of t){if(e.optimistic?.projectedEntryId)continue;if(e.message.role===`custom`&&!e.message.truncation?.truncated){let t=OR(e.message),n=jR(i.customIndexes.get(t),g);if(n>=0){g.add(n);continue}}let n=e.optimistic?.commandId??(e.key.startsWith(`optimistic-`)?e.key.slice(11):void 0),a=n?i.commandInputs.get(n):void 0;if(a){e.optimistic&&l.push({key:e.key,entryId:a});continue}let o=SL(e.message);if(o.role===`user`&&e.optimistic){let t=e.optimistic.afterEntryId===null?-1:i.persistedPositions.get(e.optimistic.afterEntryId),n=!e.optimistic.admitted||m>=p?void 0:i.promptsBySignature.get(DR(o))?.find(n=>n.position!==void 0&&(t===void 0?n.parentId===e.optimistic?.afterEntryId:n.position>t)&&!c.has(n.key));if(n){c.add(n.key),l.push({key:e.key,entryId:n.key}),m++;continue}}else{let e=o.role===`user`?t.find(e=>e.optimistic?.admitted&&!e.optimistic.projectedEntryId&&!h.has(e.key)&&!l.some(t=>t.key===e.key)&&e.optimistic.sessionId===r?.id&&e.optimistic.sessionPath===r?.path&&DR(SL(e.message))===DR(o)):void 0;if(e){h.add(e.key);continue}let n=TR(o),a=OR(o),s=n===void 0?jR(i.nativeByLegacySignature.get(a),_):(i.nativeByIdentity.get(n)??[]).find(e=>!_.has(e)&&i.nativeMessages[e]?.signature===a)??-1;if(s>=0){_.add(s);continue}}let s={key:e.key,timingKey:e.key,timestamp:e.timestamp??new Date().toISOString(),message:o,optimistic:e.optimistic};o.role===`user`&&e.optimistic?u.push(s):v.push(s)}let y=new Map;for(let e of d?.queuedMessages??[])y.set(e,(y.get(e)??0)+1);let b=u.filter(e=>{if(!e.optimistic?.admitted||e.optimistic.commandId===d?.activeTurn?.commandId)return!0;let t=y.get(e.message.content)??0;return!t||(y.set(e.message.content,t-1),!1)}),x=new Map(t.flatMap(e=>e.optimistic?.projectedEntryId?[[e.optimistic.projectedEntryId,e.key]]:[]));for(let e of l)x.set(e.entryId,e.key);let S=i.baseEntries,C=(e,t)=>{S===i.baseEntries&&(S=i.baseEntries.slice()),S[e]=t};for(let[e,t]of s){let n=S[e];!n||n.timingKey===t||C(e,{...n,timingKey:t})}for(let[e,t]of n){let n=i.indexById.get(e);if(n===void 0)continue;let r=S[n];!r||r.key===t||C(n,{...r,key:t})}for(let[e,t]of x){let n=i.indexById.get(e);if(n===void 0)continue;let r=S[n];!r||r.key===t||C(n,{...r,key:t})}return{entries:S.concat(v,b),projectedPrompts:l}}function PR(e){let[t,n]=(0,_.useState)(()=>({row:e,since:Date.now()}));return(0,_.useEffect)(()=>{if(e?.key===t.row?.key)return;if(!e||!t.row){n({row:e,since:Date.now()});return}let r=window.setTimeout(()=>n({row:e,since:Date.now()}),Math.max(0,1e3-(Date.now()-t.since)));return()=>window.clearTimeout(r)},[e,t]),!e||e.key===t.row?.key?e:t.row??e}function FR({rows:e,active:t}){let{t:n}=cr(),r,[i,a]=(0,_.useState)(t),o=e.length===1,s=(0,_.useRef)(o),c=(0,_.useRef)(null),l=(0,_.useRef)(!0),u=(0,_.useRef)(0),d=(0,_.useRef)(void 0),[f,p]=(0,_.useState)({above:!1,below:!1}),m=(0,_.useCallback)(()=>{let e=c.current;if(!e)return;let t=e.scrollTop>1,n=e.scrollHeight-e.clientHeight-e.scrollTop>1;p(e=>e.above===t&&e.below===n?e:{above:t,below:n})},[]);(0,_.useEffect)(()=>a(t),[t]),(0,_.useLayoutEffect)(()=>{let n=c.current,r=s.current&&!o;s.current=o,!(!n||o||!i||e.length===0)&&(!r&&n.scrollTop!==u.current&&n.scrollHeight-n.clientHeight-n.scrollTop>24&&(l.current=!1),r&&!l.current&&(n.scrollTop=u.current),t&&l.current&&(n.scrollTop=n.scrollHeight,u.current=n.scrollTop),m())},[e,t,i,o,m]),(0,_.useEffect)(()=>{let e=c.current,n=e?.firstElementChild;if(!e||!n||o||typeof ResizeObserver>`u`)return;let r=new ResizeObserver(()=>{i&&t&&l.current&&(e.scrollTop=e.scrollHeight,u.current=e.scrollTop),m()});return r.observe(e),r.observe(n),()=>r.disconnect()},[t,i,o,m]);let h=e.filter(e=>e.processType===`thinking`).length,g=e.filter(e=>e.processType===`tool`).length,v=e.filter(e=>e.processType===`activity`).length,y=[h?n(`processThinkingCount`,{count:h}):``,g?n(`processToolCount`,{count:g}):``,v?n(`processActivityCount`,{count:v}):``].filter(Boolean),b=[...e].reverse().find(e=>e.processStatus===`running`),x=PR(b),S=x?.processPreview??(t?[...e].reverse():e).find(e=>e.processPreview)?.processPreview,C=x?.processToolName&&[`read`,`write`,`edit`].includes(x.processToolName)?S?.slice(Math.max(S.lastIndexOf(`/`),S.lastIndexOf(`\\`))+1):S,w=e.some(e=>e.error||e.processStatus===`error`),T=b?`running`:w?`error`:e.some(e=>e.processStatus===`warn`)?`warn`:e.every(e=>e.processStatus===`done`)?`done`:`unknown`,E=e.flatMap(e=>e.processToolName?[e.processToolName]:[]),D=[...new Set(E.map(e=>$I(e).action))],O=D.map(e=>n(`toolActionGroup_${e}`)),k=D.length?n(`toolGroup_${T===`done`?`done`:T===`running`?`running`:`unknown`}`,{actions:O.join(n(`toolGroupSeparator`))}):n(T===`running`?`processRunning`:`processDetails`),A=x?.processToolName?eL(n,x.processToolName,`running`):x?.processType===`thinking`?n(`thinkingActive`):k,j=x?.processToolName??E[0],M=x?.processType===`thinking`?Le:j?$I(j).Icon:It;return(0,K.jsxs)(`details`,{className:`process-sequence ${o?`single-process `:``}${T}`,open:o||i,"data-status":T,"data-running":T===`running`?`true`:void 0,"data-history-entry":e[0]?.key,onToggle:e=>{o||a(e.currentTarget.open)},children:[(0,K.jsxs)(`summary`,{hidden:o,"aria-label":[A,b?S:``,...y].filter(Boolean).join(` · `),children:[(0,K.jsx)(`span`,{className:`tool-icon`,"aria-hidden":`true`,children:(0,K.jsx)(M,{})}),(0,K.jsx)(`span`,{className:`process-sequence-title`,title:[O.join(n(`toolGroupSeparator`)),...y].filter(Boolean).join(` · `),children:(0,K.jsx)(`strong`,{children:A})}),S&&(b||!D.length)&&(0,K.jsx)(`span`,{className:`process-sequence-preview`,title:S,children:C}),(0,K.jsx)(`span`,{className:`process-sequence-counts`,children:y.join(` · `)}),(0,K.jsx)(ee,{className:`tool-disclosure`,"aria-hidden":`true`}),(0,K.jsx)(lR,{status:T})]}),(0,K.jsx)(`section`,{ref:c,className:`process-sequence-scroll`,"aria-label":o?void 0:[n(`processDetails`),...y].join(` · `),tabIndex:o?void 0:0,"data-scroll-above":f.above||void 0,"data-scroll-below":f.below||void 0,onScrollCapture:e=>{let t=e.target;if(o&&t instanceof HTMLElement&&t.classList.contains(`thinking-evidence`)){let n=t.getBoundingClientRect().top-e.currentTarget.getBoundingClientRect().top+t.scrollTop,r=n>u.current;u.current=n,l.current=(l.current||r)&&t.scrollHeight-t.clientHeight-t.scrollTop<=24}},onScroll:e=>{if(o)return;let t=e.currentTarget,n=t.scrollTop>u.current;u.current=t.scrollTop,l.current=(l.current||n)&&t.scrollHeight-t.clientHeight-t.scrollTop<=24,m()},onWheel:e=>{!e.defaultPrevented&&!e.ctrlKey&&!e.metaKey&&e.deltaY<0&&(o||KR(e.nativeEvent,e.currentTarget))&&(l.current=!1)},onKeyDown:e=>{let t=e.target;!e.defaultPrevented&&!e.altKey&&!e.metaKey&&(!e.ctrlKey||e.key===`Home`)&&([`ArrowUp`,`PageUp`,`Home`].includes(e.key)||e.key===` `&&e.shiftKey)&&t instanceof HTMLElement&&!t.isContentEditable&&!t.closest(`input, textarea, select`)&&!(e.key===` `&&t.closest(`button, summary`))&&(o||KR(e.nativeEvent,e.currentTarget))&&(l.current=!1)},onTouchStart:e=>{d.current=e.touches[0]?.clientY},onTouchMove:e=>{let t=e.touches[0]?.clientY;t!==void 0&&d.current!==void 0&&t>d.current&&(o||KR(e.nativeEvent,e.currentTarget))&&(l.current=!1),d.current=t},children:(0,K.jsx)(`div`,{className:`process-sequence-body`,children:e.map(e=>{e.processType===`thinking`?r=e.processMessageKey:e.processMessageKey!==r&&(r=void 0);let t=r!==void 0&&e.processType!==`thinking`;return(0,K.jsx)(`div`,{className:`process-step ${o?`single-tool-step `:``}${t?`thought-tool-step `:``}${e.processStatus??`unknown`}`,"data-status":e.processStatus??`unknown`,children:e.content},e.key)})})})]})}var IR=(0,_.memo)(function({rowKey:e,token:t,children:n}){return nR?.(e),n});function LR(e,t){return e.content==null?e:{...e,content:(0,K.jsx)(IR,{rowKey:e.key,token:t,children:e.content})}}function RR(e,t){let n=[];for(let t of e){let e=n.at(-1),r=t.kind===`process`;r&&e?.process?e.rows.push(t):n.push({process:r,rows:[t]})}return n.flatMap((e,r)=>{let i=`${e.process?`process`:`rows`}-${e.rows[0]?.key}`;return e.process?(0,K.jsx)(FR,{rows:e.rows,active:t&&r===n.length-1},i):e.rows.map(e=>(0,K.jsx)(_.Fragment,{children:e.content},e.key))})}function zR({rows:e,timing:t,active:n,timedTurn:r}){let{t:i}=cr(),a=(0,_.useId)(),[o,s]=(0,_.useState)(t?.outcome!==`completed`),c=(0,_.useRef)(t?.outcome);(0,_.useEffect)(()=>{c.current!==t?.outcome&&t?.outcome===`completed`&&s(!1),c.current=t?.outcome},[t?.outcome]);let l=!!(t||r),u=[];for(let r of e){if(r.content===null)continue;let e=t?.resultEntryId?r.responseEntryId===t.resultEntryId&&r.final!==!1:!n&&r.final,i=r.kind!==`prompt`&&!e,a=u.at(-1);i&&a?.foldable?a.rows.push(r):u.push({foldable:i,rows:[r]})}let d=u.filter(e=>e.foldable),f=e=>e===0?a:`${a}-${e}`,p=d.length>0,m=t?(0,K.jsx)(OL,{timing:t}):r?(0,K.jsx)(DL,{elapsedMs:r.elapsedMs},JSON.stringify([r.sessionId,r.sessionPath,r.commandId,r.epoch,r.startedAt])):null;return(0,K.jsxs)(K.Fragment,{children:[l&&(0,K.jsxs)(`header`,{className:`turn-duration`,"data-outcome":t?.outcome,children:[p?(0,K.jsxs)(`button`,{type:`button`,className:`turn-duration-toggle`,"aria-expanded":o,"aria-controls":d.map((e,t)=>f(t)).join(` `),onClick:()=>s(e=>!e),children:[m,(0,K.jsx)(ee,{"aria-hidden":`true`})]}):m,t&&t.outcome!==`completed`&&(0,K.jsx)(`span`,{className:`turn-duration-outcome`,children:i(`turnElapsedOutcome_${t.outcome}`)})]}),l?u.map(e=>e.foldable?(0,K.jsx)(`div`,{className:`turn-response-body`,id:f(d.indexOf(e)),hidden:!o,children:RR(e.rows,n&&e===d.at(-1))},e.rows[0].key):(0,K.jsx)(_.Fragment,{children:RR(e.rows,!1)},e.rows[0].key)):RR(e,n)]})}function BR({id:e,rows:t,active:n,observed:r=!0,changes:i,session:a,timedTurn:o,onReviewTurn:s}){let{t:c}=cr(),l=[...t].reverse().find(e=>e.outcome||e.timing),u=l?.timing?.outcome??l?.outcome,d=t.some(e=>e.kind===`response`),f=t.find(e=>e.kind===`prompt`),p=!!(f?.promptEntryId&&t.some(e=>e.commandHandledInputId===f.promptEntryId&&e.commandHandledCommandId===f.promptCommandId)),m=t.some(e=>e.forkSnapshotBoundary),h=m?`forked`:n?r?`running`:`unknown`:u===`failed`?`failed`:u===`interrupted`||u===`cancelled`?`interrupted`:u===`completed`||d||p?`complete`:`waiting`,g=h===`failed`?`error`:h===`interrupted`?`warning`:h===`running`?`accent`:h===`complete`?`success`:`neutral`,v=c(h===`unknown`?`toolState_unknown`:`turnState_${h}`),y=t.some(e=>e.timing&&e.timing.commandId===o?.commandId&&e.timing.epoch===o?.epoch)?void 0:o,b=[],x=[],S=0,C=(e,t=!1)=>{b.push((0,K.jsx)(zR,{rows:x,timing:e,active:n&&t,timedTurn:t?y:void 0},`run-${S++}`)),x=[]};for(let e of t)e.kind===`prompt`?x.length?x.push(e):b.push((0,K.jsx)(_.Fragment,{children:e.content},e.key)):e.timing?C(e.timing):x.push(e);(x.length||y)&&C(void 0,!0);let w=!!(o||t.some(e=>e.timing));return(0,K.jsxs)(`section`,{className:`conversation-turn${e===0?` prelude`:``}`,"data-turn":e,children:[e>0&&h!==`complete`&&(!w||m)&&(0,K.jsxs)(`header`,{className:`turn-heading`,children:[(0,K.jsx)(`span`,{className:`sr-only`,children:c(`turnLabel`,{number:e})}),(0,K.jsxs)(`span`,{className:`turn-state ${h}`,children:[(0,K.jsx)(xL,{variant:g,label:v,isPulsing:h===`running`,icon:h===`failed`||h===`interrupted`?(0,K.jsx)(Lt,{"aria-hidden":`true`}):h===`forked`?(0,K.jsx)(Ae,{"aria-hidden":`true`}):void 0}),v]})]}),b,i&&a&&(0,K.jsx)(GL,{changes:i,onReview:s},`${a.id}:${a.path}:${i.promptEntryId}`)]})}function VR(e,t,n,r){let i=new Map;for(let t=0;t{if(!t)return;let r=i.get(t);if(!(r===void 0||r>=n)){for(let t=r+1;te.rows.some(e=>e.promptCommandId===n||r?.promptEntryId&&e.promptEntryId===r.promptEntryId)):void 0,l=s.length-1;for(;l>=0&&s[l].id!==0&&!s[l].rows.some(e=>e.kind===`prompt`&&!e.pendingPrompt);)l--;return{turns:s,activeTurn:c?.id??s[l]?.id}}function HR(e,t,n,r,i,a,o,s=!0){let{turns:c,activeTurn:l}=VR(e,t,n,a);return c.map(e=>(0,K.jsx)(BR,{id:e.id,rows:e.rows,active:t&&e.id===l&&!e.rows.some(e=>e.forkSnapshotBoundary),observed:s,changes:r?.get(e.rows.find(e=>e.kind===`prompt`&&!e.pendingPrompt)?.promptEntryId??``),session:i,timedTurn:t&&e.id===l&&!e.rows.some(e=>e.forkSnapshotBoundary)?a:void 0,onReviewTurn:o},`turn-group-${e.rows[0]?.key}`))}function UR(e,t,n){let r=e.getBoundingClientRect(),i=r.top,a=Array.from(e.querySelectorAll(`[data-history-entry], [data-history-message], [data-history-result]`)).filter(t=>{let n=t.getBoundingClientRect(),i=Math.max(n.top,r.top),a=Math.min(n.bottom,r.bottom);for(let n=t;n&&n!==e;n=n.parentElement){if(n.hidden||n instanceof HTMLDetailsElement&&!n.open&&n!==t&&!n.querySelector(`:scope > summary`)?.contains(t))return!1;if(n===t)continue;let e=getComputedStyle(n);if(!/^(auto|scroll|overlay|hidden|clip)$/.test(e.overflowY))continue;let r=n.getBoundingClientRect();i=Math.max(i,r.top),a=Math.min(a,r.bottom)}return a>i}),o=a.find(e=>!a.some(t=>t!==e&&e.contains(t))),s=o?.dataset.historyResult??o?.dataset.historyEntry??o?.dataset.historyMessage,c=o?.dataset.historyResult??o?.dataset.historyMessage,l=n?.entries.find(e=>e.id===c||e.id===s)?.id;if(!l&&s)for(let e of n?.entries??[])s.startsWith(`${e.id}-`)&&(!l||e.id.length>l.length)&&(l=e.id);return{key:l?s:void 0,entryId:l,offset:(o?.getBoundingClientRect().top??i)-i,scrollTop:e.scrollTop,pinned:t}}function WR(e,t){let n=!1;for(let r=e.parentElement;r&&r!==t;r=r.parentElement)if(r instanceof HTMLDetailsElement&&(r.open=!0),r.classList.contains(`turn-response-body`)&&r.hidden){let e=Array.from(t.querySelectorAll(`button[aria-controls]`)).find(e=>e.getAttribute(`aria-controls`)?.split(` `).includes(r.id));e&&(e.click(),n=!0)}return n}function GR(e,t,n){if(e.scrollIntoView?.({block:`nearest`,inline:`nearest`,behavior:`instant`}),n){t.scrollTop=n.scrollTop;for(let r=e.parentElement;r&&r!==t;r=r.parentElement)!/^(auto|scroll|overlay)$/.test(getComputedStyle(r).overflowY)||r.scrollHeight<=r.clientHeight||(r.scrollTop+=e.getBoundingClientRect().top-t.getBoundingClientRect().top-n.offset)}return Math.max(0,t.scrollTop+e.getBoundingClientRect().top-t.getBoundingClientRect().top-(n?.offset??24))}function KR(e,t){for(let n of e.composedPath()){if(n===t)return!0;if(!(n instanceof HTMLElement))continue;let e=getComputedStyle(n);if(/^(auto|scroll|overlay)$/.test(e.overflowY)&&(n.scrollTop>0||/^(contain|none)$/.test(e.overscrollBehaviorY)))return!1}return!1}function qR(e){let{t}=cr(),n=(0,_.useRef)(null),r=(0,_.useRef)(null),i=(0,_.useRef)(!0),a=(0,_.useRef)(0),o=(0,_.useRef)(void 0),s=(0,_.useRef)(0),c=(0,_.useRef)(e.readingRestorePending);c.current=e.readingRestorePending;let[l,u]=(0,_.useState)(!1),d=(0,_.useRef)(null),f=e.activityObserved!==!1&&e.resultExposureEnabled!==!1,p=(0,_.useCallback)(()=>{d.current?.abort(),d.current=null},[]),m=(0,_.useRef)(void 0),h=(0,_.useRef)(e.scrollToBottom),g=(0,_.useRef)(null),v=(0,_.useMemo)(()=>e.readingCache??new Map,[e.readingCache]),y=e.historyNavigation,b=y?JSON.stringify([y.sessionId,y.sessionPath,y.entryId,y.revision]):null,x=(0,_.useRef)(null),[S,C]=(0,_.useState)(null),T=tR(e.snapshot.selectedSession,{onAnchorChange:e.onHistoryAnchorChange,onRefresh:e.onRefreshHistory,preload:e.activityObserved!==!1&&e.resultExposureEnabled!==!1,beforePrepend:()=>{let e=n.current;e&&(g.current={...UR(e,!1,D.current),scrollHeight:e.scrollHeight},i.current=!1)}},v,y),E=T.session,D=(0,_.useRef)(E);D.current=E;let O=E?.id,k=E?.path,A=E?.cwd,j=S&&S.sessionId===O&&S.sessionPath===k?S.entryId:void 0,M=JSON.stringify([O,k]),N=JSON.stringify([e.snapshot.selectedSession?.id,e.snapshot.selectedSession?.path,e.snapshot.selectedSession?.history?.leafEntryId??e.snapshot.selectedSession?.entries.at(-1)?.id]);(0,_.useLayoutEffect)(()=>(f||p(),p),[N,b,f,p]),(0,_.useLayoutEffect)(()=>{let e=n.current;if(!e||!O||!k)return;let t=()=>{c.current||vL(v,M,{position:UR(e,i.current,D.current)})};window.addEventListener(`pagehide`,t);let r=()=>{document.visibilityState===`hidden`&&t()};return document.addEventListener(`visibilitychange`,r),()=>{window.clearTimeout(s.current),window.removeEventListener(`pagehide`,t),document.removeEventListener(`visibilitychange`,r),t()}},[M,v,O,k]);let P=(0,_.useRef)(M),[F,I]=(0,_.useState)({});(0,_.useLayoutEffect)(()=>{P.current!==M&&(P.current=M,I({}))},[M]);let L=(0,_.useMemo)(()=>new Map((E?.entries??[]).flatMap(e=>e.turnChanges&&e.turnChanges.sessionId===E?.id?[[e.turnChanges.promptEntryId,e.turnChanges]]:[])),[E?.entries,E?.id]),R=(0,_.useRef)(T.reset),ee=T.hasNewer||T.verifying,z=rj(e.snapshot,E),B=e.snapshot.selectedExecution?.sessionId===E?.id&&e.snapshot.selectedExecution?.sessionPath===E?.path?e.snapshot.selectedExecution:void 0,V=z&&e.liveActiveTurn!==void 0?e.liveRunning:z&&e.liveRunning||(B?B.status===`running`:z&&e.snapshot.runtime.status===`running`),H=!ee&&V?B?B.retry:z?e.liveRetry??void 0:void 0:void 0,te=(0,_.useRef)({scope:M,keys:new Map}),ne=(0,_.useRef)({scope:M,rows:new Map}),re=(0,_.useRef)(e.onReviewTurn);re.current=e.onReviewTurn;let ie=(0,_.useCallback)((e,t)=>{re.current?.(e,t)},[]);te.current.scope!==M&&(te.current={scope:M,keys:new Map});let{entries:ae,projectedPrompts:U}=(0,_.useMemo)(()=>NR({...e.snapshot,selectedSession:E},ee?[]:e.liveMessages.filter(e=>e.optimistic?e.optimistic.sessionId===E?.id&&e.optimistic.sessionPath===E?.path:z),te.current.keys),[e.snapshot,E,z,ee,e.liveMessages]);(0,_.useEffect)(()=>{E&&U.length>0&&e.onPromptProjection?.(E.id,E.path,U)},[E,U,e.onPromptProjection]),(0,_.useEffect)(()=>{let e=n.current;if(!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(()=>{i.current&&(typeof e.scrollTo==`function`?e.scrollTo({top:e.scrollHeight,behavior:`instant`}):e.scrollTop=e.scrollHeight,a.current=e.scrollTop)});return t.observe(e),r.current&&t.observe(r.current),()=>t.disconnect()},[]);let oe=(0,_.useMemo)(()=>({active:z,running:V,selectedExecution:B,retry:H,activityObserved:e.activityObserved,historyPaused:ee,onResend:e.onResend,onEdit:e.onEdit,onRegenerate:e.onRegenerate,onFork:e.onFork,forkAvailable:e.forkAvailable,forkPending:e.forkPending,onInspectSubagent:e.onInspectSubagent,subagents:e.snapshot.runtime.capabilities.subagents,workflows:e.snapshot.runtime.capabilities.workflows?.items,expandThinking:e.snapshot.preferences.expandThinking,subagentResultDisplay:e.snapshot.preferences.subagentResultDisplay,bashToolDisplay:e.snapshot.preferences.bashToolDisplay,fileMutationDisplay:e.snapshot.preferences.fileMutationDisplay,thinkingLevel:e.snapshot.thinking?.level,selectedId:O,selectedPath:k,selectedCwd:A,t}),[z,V,B,H,e.activityObserved,ee,e.onResend,e.onEdit,e.onRegenerate,e.onFork,e.forkAvailable,e.forkPending,e.onInspectSubagent,e.snapshot.runtime.capabilities.subagents,e.snapshot.runtime.capabilities.workflows?.items,e.snapshot.preferences.expandThinking,e.snapshot.preferences.subagentResultDisplay,e.snapshot.preferences.bashToolDisplay,e.snapshot.preferences.fileMutationDisplay,e.snapshot.thinking?.level,O,k,A,t]),{rows:se,turns:ce}=(0,_.useMemo)(()=>{let n=aj(ae.map(e=>e.message)),r=pR(ae,V&&!ee),i=[...r.finalErrors].at(-1),a=-1;for(let e=ae.length-1;e>=0;e--)if(ae[e].message.role===`assistant`){a=e;break}let o=new Map,s,c=new Map,l=new Set,u=z?e.snapshot.runtime.liveTools??[]:[],d=B?.liveTools??[],f=ee?[]:[...u,...d.filter(e=>!u.some(t=>t.call.id===e.call.id))];ae.forEach(e=>{let{message:t}=e;t.role===`toolResult`&&t.toolCallId&&c.set(t.toolCallId,e),t.parts?.forEach(e=>{e.type===`toolCall`&&e.id&&![`ask_user`,`human_handoff`].includes(e.name)&&l.add(e.id)})});let p=[],m=0,h,g=-1,_=-1;for(let e=ae.length-1;e>=0;e--){if(ae[e]?.message.role===`user`){_=e;break}if(ae[e]?.message.role===`custom`&&ae[e]?.message.customType===`openpi-setup-request`)break}let v=new Set,y=-1;ae.forEach(({message:e},t)=>{e.role===`user`||e.role===`custom`&&e.customType===`openpi-setup-request`?(y>=0&&v.add(y),y=-1):e.role===`assistant`&&e.content.trim()&&(y=t)}),y>=0&&v.add(y);let b=[...n.values()].map(e=>`${e.id}\0${e.title}\0${e.state??``}\0${e.result??``}\0${e.receipt??``}`).join(` +`),x=(u,d)=>{let y=u.message;if(u.forkSnapshotBoundary)return[{key:u.key,turn:m,kind:`custom`,forkSnapshotBoundary:!0,content:null}];if(u.timing)return[{key:u.key,turn:m,kind:`custom`,timing:u.timing,content:null}];if(u.compaction)return[{key:u.key,turn:m,kind:`custom`,content:(0,K.jsx)(kL,{compaction:{state:`completed`}})}];if(y.role===`custom`){if(y.customType===`openpi-web-command-handled`){let e=y.details;return e&&typeof e==`object`&&`inputEntryId`in e&&typeof e.inputEntryId==`string`?[{key:u.key,turn:m,kind:`custom`,commandHandledInputId:e.inputEntryId,commandHandledCommandId:`commandId`in e&&typeof e.commandId==`string`?e.commandId:void 0,content:null}]:[]}return y.display===!1||![`openpi-web-command-feedback`,`openpi-setup-request`,`openpi-setup-closed`,`subagent-result`,`workflow-result`].includes(y.customType??``)?[]:(y.customType===`openpi-setup-request`&&(h=void 0,g=-1,m++),[{key:u.key,turn:m,kind:`custom`,content:(0,K.jsx)(`article`,{className:`message-row assistant detail-only`,"data-history-entry":u.entryId??u.key,tabIndex:-1,children:(0,K.jsx)(`div`,{className:`message-content`,children:(0,K.jsx)(CR,{message:y,sessionId:O??``,onInspectSubagent:e.onInspectSubagent,fullSubagent:e.snapshot.preferences.subagentResultDisplay===`full`})})})}])}if(y.role===`user`){h=y.content,g=d,m++,p.push({entryId:u.entryId??u.key,title:Array.from((y.content||t(`attachedImage`)).replace(/\s+/g,` `).trim()).slice(0,240).join(``)});let n=u.entryId?JSON.stringify([O,k,u.entryId]):``,r=F[n],i=!!(y.truncation?.visibleText&&r===void 0);return[{key:u.key,turn:m,kind:`prompt`,pendingPrompt:!!u.optimistic,promptCommandId:u.optimistic?.commandId??y.commandId,promptEntryId:u.entryId,content:(0,K.jsxs)(`article`,{className:`message-row user`,id:`turn-${m}`,"data-history-entry":u.entryId??u.key,"data-history-highlighted":j&&u.entryId===j||void 0,tabIndex:-1,children:[(0,K.jsxs)(`div`,{className:`message-content`,children:[(0,K.jsx)(JL,{message:y,sessionId:O,path:k,entryId:u.entryId}),(y.content||y.truncation?.visibleText)&&(u.entryId&&O&&k&&y.truncation?.visibleText?(0,K.jsx)(FL,{preview:y.content,sessionId:O,sessionPath:k,entryId:u.entryId,markdown:!1,fullText:r,onComplete:e=>I(t=>({...t,[n]:e}))},`${O}:${k}:${u.entryId}`):(0,K.jsx)(PL,{content:y.content}))]}),(0,K.jsx)(SR,{content:r??y.content,editable:z&&!V&&!!(e.forkAvailable&&e.onEdit&&u.entryId&&O&&k&&!u.optimistic)&&!i,copyRequiresFull:i,timestamp:u.timestamp,onResend:t=>e.onEdit&&u.entryId&&O&&k?e.onEdit({sessionId:O,sessionPath:k,entryId:u.entryId},t):Promise.resolve(!1),onFork:u.entryId&&O&&k&&e.onFork&&!u.optimistic?()=>e.onFork({sessionId:O,sessionPath:k,entryId:u.entryId}):void 0,canFork:z&&!V&&e.forkAvailable,forkPending:e.forkPending})]})}]}if(y.role===`assistant`){let b=p.at(-1);b&&y.content.trim()&&(b.reply=Array.from(y.content.replace(/\s+/g,` `).trim()).slice(0,240).join(``));let x=[],S=y.parts??[],C=y.webSearch??[],w=e=>Math.min(S.length,e.beforePartIndex??0),T=e=>{for(let[t,n]of C.entries()){if(w(n)!==e)continue;let r=n.status===`completed`?`done`:n.status===`failed`?`error`:`warn`;x.push({key:`${u.key}-native-search-${t}`,turn:m,kind:`process`,processType:`tool`,processMessageKey:u.key,processToolName:`web_search`,processPreview:n.query,processStatus:r,error:n.status===`failed`,content:(0,K.jsx)(`article`,{className:`message-row assistant detail-only`,"data-history-entry":`${u.entryId??u.key}-native-search-${t}-body`,"data-history-message":u.entryId??u.key,tabIndex:-1,children:(0,K.jsx)(`div`,{className:`message-content`,children:(0,K.jsx)(gR,{body:n.query,icon:(0,K.jsx)(je,{}),name:`web_search`,summary:n.query,status:r})})})})}},E=S.reduce((e,t,n)=>(t.type===`thinking`||t.type===`text`)&&!t.text.trim()?e:n,-1),D=S.reduce((e,t,n)=>t.type===`text`?n:e,-1),M=!!(u.entryId&&O&&k&&y.truncation?.visibleText),N=y.content,P=u.entryId?JSON.stringify([O,k,u.entryId]):``,L=F[P],R=!!(y.truncation?.visibleText&&L===void 0),te=(t,n,r)=>{M&&!r||!M&&!t.trim()||x.push({key:n,turn:m,kind:`response`,responseEntryId:u.entryId,final:r&&(y.stopReason===`stop`||y.stopReason===`length`),content:(0,K.jsxs)(`article`,{className:`message-row assistant response${r&&v.has(d)?` final-response`:``}`,"data-history-message":u.entryId??u.key,"data-history-highlighted":j&&u.entryId===j||void 0,tabIndex:-1,"data-history-entry":u.entryId?`${u.entryId}-${n.slice(u.key.length+1)}`:n,children:[(0,K.jsx)(`div`,{className:`message-content`,children:M&&O&&k&&u.entryId?(0,K.jsx)(FL,{preview:N,sessionId:O,sessionPath:k,entryId:u.entryId,markdown:!0,fullText:L,onComplete:e=>I(t=>({...t,[P]:e}))},`${O}:${k}:${u.entryId}`):(0,K.jsx)(Sk,{children:t})}),r&&v.has(d)&&(0,K.jsx)(SR,{content:L??y.content,editable:!1,copyRequiresFull:R,timestamp:u.timestamp,onResend:e.onResend,onRegenerate:b?.entryId&&O&&k&&e.onRegenerate&&!u.optimistic&&!y.isError&&(y.stopReason===`stop`||y.stopReason===`length`)?()=>e.onRegenerate({sessionId:O,sessionPath:k,entryId:b.entryId}):void 0,onFork:u.entryId&&O&&k&&e.onFork?()=>e.onFork({sessionId:O,sessionPath:k,entryId:u.entryId}):void 0,canFork:z&&!V&&e.forkAvailable,forkPending:e.forkPending})]})})};y.parts?.forEach((r,i)=>{if(T(i),r.type===`text`&&(S[i-1]?.type!==`text`||C.some(e=>w(e)===i))){let e=r.text,t=i+1;for(;S[t]?.type===`text`&&!C.some(e=>w(e)===t);){let n=S[t];n?.type===`text`&&(e+=n.text),t++}te(e,`${u.key}-text-${i}`,t>D)}if(r.type===`thinking`&&r.text.trim()){let t=!ee&&!H&&!y.stopReason&&B?.compaction?.state!==`running`&&V&&d===ae.length-1&&i===E?e.activityObserved===!1?`unknown`:`running`:`done`;x.push({key:`${u.key}-thinking-${i}`,turn:m,kind:`process`,processType:`thinking`,processMessageKey:u.key,processPreview:hR(r.text),processStatus:t,content:(0,K.jsx)(`article`,{className:`message-row assistant detail-only`,"data-history-entry":`${u.entryId??u.key}-thinking-${i}-body`,"data-history-message":u.entryId??u.key,"data-history-highlighted":j&&u.entryId===j||void 0,tabIndex:-1,children:(0,K.jsx)(`div`,{className:`message-content`,children:(0,K.jsx)(xR,{body:r.text,truncated:r.textTruncated,source:u.entryId&&O&&k&&r.sourcePartIndex!==void 0?{sessionId:O,sessionPath:k,entryId:u.entryId,partIndex:r.sourcePartIndex}:void 0,status:t,level:t===`running`?e.snapshot.thinking?.level:void 0,duration:MR(u,e.thinkingDurations),defaultOpen:e.snapshot.preferences.expandThinking===!0},JSON.stringify([O,k,u.key,i]))})})})}if(r.type===`toolCall`){let a=r,o=f.find(e=>e.call.id===a.id),s=a.id?c.get(a.id):void 0,d=s?.message??o?.result,p=AL(a,d,f,s?void 0:o?.state),h=p?[...p.children.map(e=>({call:e.call,child:e})),...p.showWrapper?[{call:a}]:[]]:[{call:a}];for(let[r,{call:o,child:g}]of h.entries()){let _=o.name.startsWith(`subagent`)?e.snapshot.preferences.subagentResultDisplay===`full`:o.name===`bash`?e.snapshot.preferences.bashToolDisplay===`full`:o.name===`write`||o.name===`edit`?e.snapshot.preferences.fileMutationDisplay===`full`:!1,v=o.id?f.find(e=>e.call.id===o.id):void 0,y=g?s:o.id?c.get(o.id):void 0,b=g?void 0:y?.message,S=g?g.result:b??v?.result,C=g?g.state:b?void 0:v?.state,w=g?g.state===`returned`?`done`:g.state===`failed`?`error`:g.state===`cancelled`||g.state===`timed_out`?`warn`:g.state:cR(S,C),T=e.activityObserved===!1&&w===`running`?`unknown`:w,E=o.name===`plan_ready`&&S&&IL(S)?(0,K.jsx)(LL,{result:S,sessionId:O,sessionPath:k,entryId:y?.entryId},`${u.key}-${o.id||i}-plan`):Ld(o.name)&&!g?.outputMissing?(0,K.jsx)(WL,{call:o,result:S,liveState:C,observed:e.activityObserved,cwd:A,defaultOpen:_},`${u.key}-${o.id||i}-evidence`):g?.outputMissing?null:vR(o,S,{sessionId:O??``,subagents:z?e.snapshot.runtime.capabilities.subagents?.items:void 0,workflows:z?e.snapshot.runtime.capabilities.workflows?.items:void 0,records:n,onInspectSubagent:e.onInspectSubagent,liveState:C,defaultOpen:_,observed:e.activityObserved!==!1}),D=oR(o.arguments),{Icon:M,action:N}=$I(o.name),P=(0,K.jsx)(M,{},`${u.key}-${o.id||i}-icon`);x.push({key:`${u.key}-tool-${o.id||i}`,turn:m,kind:o.name===`plan_ready`&&S&&IL(S)?`response`:E&&(o.name===`subagent_spawn`||o.name===`workflow`)?`custom`:`process`,processType:/^(subagent|workflow)/u.test(o.name)?`activity`:`tool`,processMessageKey:u.key,processToolName:o.name,processPreview:nL(o.name,D).split(` +`).find(Boolean),processStatus:T,error:T===`error`,content:(0,K.jsx)(`article`,{className:`message-row assistant detail-only`,"data-history-message":u.entryId??u.key,"data-history-result":y?.entryId,"data-history-highlighted":j&&(u.entryId===j||y?.entryId===j)||void 0,tabIndex:-1,children:(0,K.jsxs)(`div`,{className:`message-content`,children:[E||(0,K.jsx)(gR,{body:o.name===`bash`&&typeof D.command==`string`?D.command:o.arguments,icon:P,name:o.name||`tool`,summary:N===`search`&&typeof D.path==`string`?t(`toolSearchTarget`,{path:D.path,pattern:mR(o.name,D)}):mR(o.name,D),output:g?g.error??S?.content:o.id&&l.has(o.id)?S?.content:void 0,status:T,evidenceState:e.activityObserved===!1&&g?.state===`running`?`unknown`:g?.state,rawDetails:p?.showWrapper&&o.id===a.id?d?.details:void 0,note:g?.outputMissing?t(g.argumentsOmitted?`toolNestedArgumentsMissing`:`toolNestedOutputMissing`):void 0,snapshotMissingResult:S?.forkSnapshotToolResult,defaultOpen:_}),p?.incomplete&&r===h.length-1&&(0,K.jsx)(`p`,{className:`evidence-note`,role:`status`,children:t(`toolNestedIncomplete`)}),p&&r===h.length-1&&!p.showWrapper&&(0,K.jsxs)(`details`,{className:`evidence-raw`,children:[(0,K.jsx)(`summary`,{children:t(`toolCodemodeDetails`)}),(0,K.jsx)(`pre`,{children:Fd(a.arguments).text}),(0,K.jsx)(`pre`,{children:Fd(d?.content??``).text})]})]})})})}}}),T(S.length),D<0&&te(y.content,`${u.key}-answer`,!0),y.stopReason===`error`&&!r.finalErrors.has(d)&&(o.set(u.key,[...x]),x.length=0);let ne=r.groups.get(d);if(ne&&(ne.state===`retrying`&&H&&(s=`${ne.attempts[0].key}-attempts`),x.push({key:`${ne.attempts[0].key}-attempts`,turn:m,kind:`outcome`,outcome:ne.state===`interrupted`?`interrupted`:void 0,content:(0,K.jsx)(`article`,{className:`message-row assistant outcome-row`,children:(0,K.jsx)(fR,{state:ne.state,retry:ne.state===`retrying`?H:void 0,observed:e.activityObserved!==!1&&B?.status!==`unknown`,attempts:ne.attempts.map(e=>({entry:e,content:o.get(e.key)}))})})})),r.finalErrors.has(d)||y.stopReason===`aborted`){let t=y.stopReason===`error`,n=g===_&&d===i&&d===a?h:void 0;x.push({key:`${u.key}-outcome`,turn:m,kind:`outcome`,error:t,outcome:t?`failed`:`interrupted`,content:(0,K.jsx)(`article`,{className:`message-row assistant outcome-row`,children:(0,K.jsx)(dR,{failed:t,error:y.errorMessage,retryPrompt:n,retryEntryId:u.entryId,canRetry:z&&!ee&&!V,onRetry:e.onResend})})})}else(y.stopReason===`stop`||y.stopReason===`length`)&&x.push({key:`${u.key}-completed`,turn:m,kind:`outcome`,outcome:`completed`,content:null});return x}if(y.role===`toolResult`){if(y.toolCallId&&l.has(y.toolCallId))return[];if(IL(y))return[{key:u.key,turn:m,kind:`response`,content:(0,K.jsx)(`article`,{className:`message-row assistant detail-only`,"data-history-message":u.entryId??u.key,"data-history-highlighted":j&&u.entryId===j||void 0,tabIndex:-1,children:(0,K.jsx)(`div`,{className:`message-content`,children:(0,K.jsx)(LL,{result:y,sessionId:O,sessionPath:k,entryId:u.entryId})})})}];let n=y.toolName?.startsWith(`subagent`)?`subagent`:y.toolName?.startsWith(`workflow`)?`workflow`:null,r=cR(y),i=e.activityObserved===!1&&r===`running`?`unknown`:r,a=y.toolName||`tool`,o=n===`subagent`?e.snapshot.preferences.subagentResultDisplay===`full`:a===`bash`?e.snapshot.preferences.bashToolDisplay===`full`:a===`write`||a===`edit`?e.snapshot.preferences.fileMutationDisplay===`full`:!1,{Icon:s}=$I(a),c=(0,K.jsx)(s,{},`${u.key}-icon`),d=n&&!y.forkSnapshotToolResult?(0,K.jsx)(_R,{family:n,title:`${a.replaceAll(`_`,` `)} · ${ej(y.content)}`,body:y.content,status:i,defaultOpen:o},`${u.key}-card`):wR(y.content)&&!y.forkSnapshotToolResult?(0,K.jsxs)(`div`,{className:`tool-line-empty`,children:[(0,K.jsx)(`span`,{className:`tool-icon`,children:c}),(0,K.jsx)(`span`,{className:`tool-name`,children:a}),(0,K.jsx)(`span`,{className:`tool-summary`,children:t(`noOutput`)}),(0,K.jsx)(lR,{status:i})]},`${u.key}-empty`):(0,K.jsx)(gR,{body:y.content,icon:c,name:a,summary:ej(y.content),status:i,snapshotMissingResult:y.forkSnapshotToolResult,defaultOpen:o},`${u.key}-evidence`);return[{key:u.key,turn:m,kind:a===`ask_user`||a===`human_handoff`?`response`:`process`,processType:n?`activity`:`tool`,processToolName:a,processStatus:i,error:i===`error`,content:(0,K.jsx)(`article`,{className:`message-row assistant detail-only`,"data-history-entry":`${u.entryId??u.key}-body`,"data-history-message":u.entryId??u.key,"data-history-highlighted":j&&u.entryId===j||void 0,tabIndex:-1,children:(0,K.jsx)(`div`,{className:`message-content`,children:d})})}]}return[]};ne.current.scope!==M&&(ne.current={scope:M,rows:new Map});let S=ne.current.rows,C=new Set,w=ae.flatMap((t,n)=>{let i=t.entryId?JSON.stringify([O,k,t.entryId]):``,a=r.groups.get(n),u=[],d=!!(j&&t.entryId===j);if(t.message.role===`assistant`)for(let e of t.message.parts??[]){if(e.type!==`toolCall`||!e.id)continue;let t=c.get(e.id);j&&t?.entryId===j&&(d=!0);let n=new Set([e.id]),r=[];for(let t of f)t.call.id!==e.id&&!(t.parentToolCallId&&n.has(t.parentToolCallId))||(t.call.id&&n.add(t.call.id),r.push(t.call.id,t.state,t.result,t.parentToolCallId));u.push(e.id,t?.message,e.name.startsWith(`subagent`)||e.name.startsWith(`workflow`)?b:void 0,r)}else t.message.role===`toolResult`&&t.message.toolCallId&&u.push(l.has(t.message.toolCallId));let _=[oe,t.message,t.key,t.entryId,t.timestamp,t.timing,t.compaction,t.forkSnapshotBoundary,t.optimistic,t.persisted,n,d,i?F[i]:void 0,MR(t,e.thinkingDurations),v.has(n),r.finalErrors.has(n),a?.state,a?a.attempts.map(e=>e.key).join(`\0`):void 0,m,h,g,u],y=S.get(t.key);if(y&&iR(y.slots,_)){m=y.turn,h=y.latestUserPrompt,g=y.latestUserIndex,y.retryRowKey&&(s=y.retryRowKey);for(let e of y.turnItems)p.push(e);for(let[e,t]of y.attemptContents)o.set(e,t);return C.add(t.key),y.rows}let w=p.length,T=new Set(o.keys()),E=x(t,n).map(e=>t.persisted?{...e,persisted:!0}:e),D={},A=E.map(e=>LR(e,D)),M=[];for(let[e,t]of o)T.has(e)||M.push([e,t]);return S.set(t.key,{slots:_,rows:A,token:D,turn:m,latestUserPrompt:h,latestUserIndex:g,retryRowKey:s,turnItems:p.slice(w),attemptContents:M}),C.add(t.key),A});for(let e of S.keys())C.has(e)||S.delete(e);let T=w.length;for(;T>0&&w[T-1].pendingPrompt;)T--;let E=w.length-T,D=w[T-1]?.turn??0;H&&!s&&(s=`native-retry`,w.splice(T,0,{key:`native-retry`,turn:D,kind:`outcome`,content:(0,K.jsx)(`article`,{className:`message-row assistant outcome-row`,children:(0,K.jsx)(fR,{attempts:[],state:`retrying`,retry:H,observed:e.activityObserved!==!1&&B?.status!==`unknown`})})}));let N=!ee&&B?.compaction;if(N&&N.state!==`completed`){let n=w.findIndex(e=>e.key===s),r={key:`native-compaction-${N.startedAt??N.state}`,turn:w[n]?.turn??D,kind:`custom`,content:(0,K.jsx)(kL,{compaction:N,observed:e.activityObserved!==!1&&B?.status!==`unknown`})};w.splice(n<0?T:n,0,r),N.state===`failed`&&N.errorMessage&&w.splice(w.length-E,0,{key:`native-compaction-error`,turn:r.turn,kind:`custom`,content:(0,K.jsx)(`article`,{className:`message-row assistant outcome-row`,children:(0,K.jsx)(uR,{label:t(`compactionFailed`),message:N.errorMessage})})})}return{rows:w,turns:p}},[z,V,B,H,e.activityObserved,ee,ae,e.onResend,e.onEdit,e.onRegenerate,e.onFork,e.forkAvailable,e.forkPending,e.onInspectSubagent,e.snapshot.runtime.capabilities.subagents,e.snapshot.runtime.capabilities.workflows?.items,e.snapshot.preferences.expandThinking,e.snapshot.preferences.subagentResultDisplay,e.snapshot.preferences.bashToolDisplay,e.snapshot.preferences.fileMutationDisplay,e.snapshot.thinking?.level,e.thinkingDurations,e.snapshot.runtime.liveTools,O,k,A,F,j,M,oe,t]),le=YL(e.snapshot.selectedSession,ce,f),ue=(0,_.useCallback)(async(t,r=!1)=>{if(p(),!f||!O||!k)return!1;let o=n.current,s=Array.from(o?.querySelectorAll(`[data-history-entry]`)??[]).find(e=>e.dataset.historyEntry===t);if(o&&s){i.current=!1,u(!0),C({sessionId:O,sessionPath:k,entryId:t});let e=Math.max(0,o.scrollTop+s.getBoundingClientRect().top-o.getBoundingClientRect().top-16),n=window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches;return o.scrollTo?.({top:e,behavior:r||n?`instant`:`smooth`}),typeof o.scrollTo!=`function`&&(o.scrollTop=e),a.current=o.scrollTop,s.focus({preventScroll:!0}),!0}if(r)return;if(!e.onNavigateToMessage)return!1;let c=new AbortController;d.current=c;let l=await e.onNavigateToMessage({sessionId:O,sessionPath:k,entryId:t},c.signal);if(!(c.signal.aborted||d.current!==c))return d.current=null,l},[p,f,O,k,e.onNavigateToMessage]);(0,_.useLayoutEffect)(()=>{let t=n.current;if(!t||!E)return;let r=_L(E),o=m.current!==r,s=R.current!==T.reset,l=o||s;R.current=T.reset;let d=h.current!==e.scrollToBottom;if(h.current=e.scrollToBottom,y&&b!==x.current&&y.sessionId===E.id&&y.sessionPath===E.path){i.current=!1,g.current=null,m.current=r;return}if(d&&T.engaged){g.current=null,T.resetToLatest();return}let f=o&&!s&&!d?v.get(r)?.position:void 0,p=f?.key&&Array.from(t.querySelectorAll(`[data-history-entry], [data-history-message], [data-history-result]`)).some(e=>e.dataset.historyEntry===f.key||e.dataset.historyMessage===f.key||e.dataset.historyResult===f.key),_=g.current??(f&&!f.pinned&&(!c.current||p)?{...f,scrollHeight:t.scrollHeight}:null);if(g.current=null,_&&(!l||f)&&!d){let e=Array.from(t.querySelectorAll(`[data-history-entry], [data-history-message], [data-history-result]`)),n=_.key===void 0?void 0:e.find(e=>e.dataset.historyEntry===_.key)??e.reverse().find(e=>e.dataset.historyMessage===_.key||e.dataset.historyResult===_.key);i.current=!1,u(!0),m.current=r;let o=()=>{if(n&&!t.contains(n))return;g.current===_&&(g.current=null);let e=n?GR(n,t,_):_.scrollTop+t.scrollHeight-_.scrollHeight;typeof t.scrollTo==`function`?t.scrollTo({top:e,behavior:`instant`}):t.scrollTop=e,a.current=t.scrollTop};if(n&&WR(n,t)){g.current=_;let e=requestAnimationFrame(o);return()=>cancelAnimationFrame(e)}o();return}(l||d||i.current)&&(i.current=!0,u(!1),typeof t.scrollTo==`function`?t.scrollTo({top:t.scrollHeight,behavior:`instant`}):t.scrollTop=t.scrollHeight,a.current=t.scrollTop),m.current=r},[E,ae,T.reset,T.engaged,T.resetToLatest,e.scrollToBottom,v,y,b]),(0,_.useLayoutEffect)(()=>{let e=n.current;if(!e||!E||!y||b===x.current||y.sessionId!==E.id||y.sessionPath!==E.path)return;let t=Array.from(e.querySelectorAll(`[data-history-entry], [data-history-message], [data-history-result]`)),r=t.filter(e=>e.dataset.historyEntry===y.entryId||e.dataset.historyMessage===y.entryId||e.dataset.historyResult===y.entryId),o=y.restorePosition?.key?t.find(e=>e.dataset.historyEntry===y.restorePosition.key)??[...t].reverse().find(e=>e.dataset.historyMessage===y.restorePosition.key||e.dataset.historyResult===y.restorePosition.key):void 0,s=o??r.find(e=>e.classList.contains(`response`))??r.find(e=>e.dataset.historyMessage===y.entryId||e.dataset.historyResult===y.entryId)??r[0];if(!s)return;WR(s,e);let c=()=>{if(!e.contains(s)||y.restorePosition&&x.current===b)return;let t=GR(s,e,o?y.restorePosition:void 0);e.scrollTo?.({top:t,behavior:`instant`}),typeof e.scrollTo!=`function`&&(e.scrollTop=t),a.current=e.scrollTop,y.restorePosition||s.focus({preventScroll:!0}),i.current=!1,u(!0),y.restorePosition||C(y),x.current=b,vL(v,_L(E),{position:UR(e,!1,E)})},l=document.querySelector(`dialog[open]`),d,f=()=>{d=requestAnimationFrame(c)};return l?l.addEventListener(`close`,f,{once:!0}):f(),()=>{l?.removeEventListener(`close`,f),d!==void 0&&cancelAnimationFrame(d)}},[E,y,b,v]);let de=z?e.liveRetry?`${t(`modelRetrying`)} (${e.liveRetry.attempt}/${e.liveRetry.maxAttempts})`:e.livePhase===`preparing`?t(`modelPreparing`):t(`modelRunning`):t(`backgroundSessionRunning`),fe=z?0:B?.liveTools.filter(e=>e.state===`running`).length??0,pe=z&&e.liveActiveTurn!==void 0?e.liveActiveTurn:B?B.activeTurn:z?e.snapshot.runtime.activeTurn:void 0,me=V&&pe&&E&&pe.sessionId===E.id&&pe.sessionPath===E?.path&&typeof pe.startedAt==`number`&&Number.isFinite(pe.startedAt)&&typeof pe.elapsedMs==`number`&&Number.isFinite(pe.elapsedMs)&&pe.elapsedMs>=0?pe:void 0,W=!T.verifying&&me&&(!ee||me.promptEntryId&&se.some(e=>e.promptEntryId===me.promptEntryId))?me:void 0,he=t=>{T.hasMore&&!T.error&&!T.verifying&&e.activityObserved!==!1&&e.resultExposureEnabled!==!1&&t.scrollTop<=Math.max(t.clientHeight,160)&&T.loadOlder()},ge=()=>{i.current=!1,u(!0),T.retainReading()};return(0,K.jsxs)(`div`,{className:`transcript-surface`,children:[(0,K.jsx)(`div`,{ref:n,className:`conversation`,role:`log`,"aria-label":`Conversation`,tabIndex:0,onPointerDownCapture:()=>{y?.restorePosition&&(x.current=b)},onTouchStartCapture:e=>{o.current=e.touches[0]?.clientY,y?.restorePosition&&(x.current=b)},onTouchMove:e=>{let t=e.touches[0]?.clientY;t!==void 0&&o.current!==void 0&&t>o.current&&KR(e.nativeEvent,e.currentTarget)&&ge(),o.current=t},onScroll:e=>{let t=e.currentTarget,n=t.scrollTopa.current;a.current=t.scrollTop;let o=t.scrollTop+t.clientHeight>=t.scrollHeight-48;i.current=i.current?!n||o:r&&o,i.current||T.retainReading(),u(!i.current),window.clearTimeout(s.current),s.current=window.setTimeout(()=>{!c.current&&O&&k&&t.isConnected&&vL(v,M,{position:UR(t,i.current,D.current)})},200),n&&he(t)},onWheel:e=>{y?.restorePosition&&(x.current=b),!e.defaultPrevented&&!e.ctrlKey&&!e.metaKey&&e.deltaY<0&&KR(e.nativeEvent,e.currentTarget)&&(ge(),he(e.currentTarget))},onKeyDown:e=>{y?.restorePosition&&[`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `].includes(e.key)&&(x.current=b);let t=e.target;!e.defaultPrevented&&!e.altKey&&!e.metaKey&&(!e.ctrlKey||e.key===`Home`)&&([`ArrowUp`,`PageUp`,`Home`].includes(e.key)||e.key===` `&&e.shiftKey)&&t instanceof HTMLElement&&!t.isContentEditable&&!t.closest(`input, textarea, select`)&&!(e.key===` `&&t.closest(`button, summary`))&&KR(e.nativeEvent,e.currentTarget)&&(ge(),he(e.currentTarget))},children:(0,K.jsxs)(`div`,{ref:r,className:`conversation-content`,children:[E?.rerun&&e.onOpenOriginal&&(0,K.jsxs)(`div`,{className:`message-branch-origin`,children:[(0,K.jsxs)(`button`,{type:`button`,onClick:()=>void e.onOpenOriginal(E.rerun.source),children:[(0,K.jsx)(Ae,{"aria-hidden":`true`}),` `,t(`openOriginalConversation`)]}),(0,K.jsx)(`span`,{children:t(`messageRerunWorkspaceHint`)})]}),(T.hasMore||T.error||T.verifying)&&(0,K.jsxs)(`div`,{className:`conversation-history`,children:[T.error&&(0,K.jsx)(`p`,{role:`alert`,children:t(T.error)}),T.error&&T.error!==`historyChanged`&&(0,K.jsx)(`button`,{type:`button`,className:`secondary`,disabled:T.loading,onClick:()=>void T.loadOlder(),children:t(`retryAdmissionCheck`)}),T.loading&&(0,K.jsx)(`p`,{role:`status`,children:t(`historyLoading`)}),T.verifying&&!T.error&&!T.loading&&(0,K.jsx)(`p`,{role:`status`,children:t(`historyVerifying`)}),T.hasMore&&(0,K.jsx)(`span`,{children:t(`historyOmitted`,{count:E?.truncation.entriesOmitted??0})})]}),HR(se,V&&(!ee||!!W)&&B?.compaction?.state!==`running`,pe?.commandId,L,E,e.activityObserved===!1?void 0:W,ie,e.activityObserved!==!1),V&&e.activityObserved!==!1&&B?.compaction?.state!==`running`&&(0,K.jsxs)(`div`,{className:`conversation-execution-status sr-only`,role:`status`,"aria-live":`polite`,children:[(0,K.jsx)(`span`,{children:de}),fe>0&&(0,K.jsx)(`span`,{children:t(`observedSessionTools`,{count:fe})}),(B?.pendingFollowUps??0)>0&&(0,K.jsx)(`span`,{children:t(`pendingFollowUpsHint`,{count:B.pendingFollowUps})})]})]})}),(l||T.hasNewer)&&se.length>0&&(0,K.jsx)(`button`,{className:`jump-to-latest`,type:`button`,"aria-label":t(`jumpToLatest`),title:t(`jumpToLatest`),onClick:()=>{let e=n.current;e&&(i.current=!0,u(!1),C(null),T.resetToLatest(),e.scrollTo({top:e.scrollHeight,behavior:`smooth`}),queueMicrotask(()=>{n.current===e&&(Array.from(e.querySelectorAll(`.message-row[tabindex="-1"]`)).reverse().find(e=>!e.closest(`[hidden], details:not([open])`))??e).focus({preventScroll:!0})}))},children:V&&e.activityObserved!==!1?(0,K.jsxs)(`span`,{className:`latest-activity-dots`,"aria-hidden":`true`,children:[(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{})]}):(0,K.jsx)(w,{"aria-hidden":`true`})}),(0,K.jsx)(qL,{items:le.items,viewport:n,enabled:f,onHidden:p,onRequestPreview:le.requestPreview,readingHistory:l||T.hasNewer,onNavigate:ue},N)]})}function JR(){(0,_.useEffect)(()=>{let e=new rf,t=new AbortController,n,r=async r=>{let i=r.data;if(!(r.source!==window||r.origin!==location.origin||i?.source!==`openpi-browser-extension`||i.type!==`connector-hello`||typeof i.bridgeId!=`string`||!/^[\da-f-]{36}$/.test(i.bridgeId)||!tF(i.browser)||n===i.bridgeId)){n=i.bridgeId;try{let r=await e.request(`/api/browser/connections`,{method:`POST`,signal:t.signal,body:JSON.stringify({browser:i.browser,profileId:i.profileId,extensionId:i.extensionId,extensionOrigin:i.extensionOrigin,version:i.version})});!t.signal.aborted&&n===i.bridgeId&&window.postMessage({source:`openpi-browser-ui`,type:`connector-authorize`,...r},location.origin)}catch{n===i.bridgeId&&(n=void 0)}}},i=()=>window.postMessage({source:`openpi-browser-ui`,type:`connector-probe`},location.origin);window.addEventListener(`message`,r),i();let a=setInterval(i,5e3);return()=>{t.abort(),clearInterval(a),window.removeEventListener(`message`,r)}},[])}function YR(e,t){let n=e.trim();if(!n||n.length>16384)return null;let r=/^[a-z][a-z\d+.-]*:\/\//iu.test(n);try{let e=new URL(r?n:`https://${n}`);return!r&&(e.hostname===`localhost`||e.hostname.endsWith(`.localhost`)||e.hostname===`[::1]`||/^127(?:\.\d{1,3}){3}$/u.test(e.hostname))&&(e=new URL(`http://${n}`)),![`http:`,`https:`].includes(e.protocol)||e.username||e.password||e.origin===t?null:e.href}catch{return null}}function XR(){return document.documentElement.dataset.openpiBrowserExtension===`ready`?[...document.querySelectorAll(`iframe[data-openpi-browser-document]`)].map(e=>({id:e.dataset.openpiBrowserPage,document:e.dataset.openpiBrowserDocument,url:e.dataset.openpiBrowserUrl,title:e.dataset.openpiBrowserTitle||``})):[]}function ZR(e,t,n){let r=(0,_.useRef)(n),i=(0,_.useRef)(0);r.current=n,(0,_.useEffect)(()=>{if(!e||!t)return;let n=new rf,a=new AbortController,o,s,c,l=e=>window.postMessage({source:`openpi-browser-ui`,...e},location.origin),u=()=>{c?.(),c=void 0,s&&l({type:`control-cancel`,requestId:s}),s=void 0},d=(r,i,o)=>{r===s&&(c?.(),c=void 0,s=void 0,n.request(`/api/browser/control`,{method:`POST`,signal:a.signal,body:JSON.stringify({sessionId:e,sessionPath:t,requestId:r,result:i,error:o,pages:XR()})}).catch(()=>{}))},f=e=>{let t=e.data;e.source===window&&e.origin===location.origin&&t?.source===`openpi-browser-extension`&&(t.type===`connector-hello`?i.current=Date.now():t.type===`control-result`&&d(t.requestId,t.result,t.error))},p=async(e,t)=>{let n=YR(t||``,location.origin);if(!n){d(e,void 0,`Invalid internal browser URL.`);return}let i=new AbortController;c=()=>i.abort();let o=await r.current(n,AbortSignal.any([a.signal,i.signal]));if(a.signal.aborted||s!==e)return;if(!o){d(e,void 0,`The internal browser has reached its page limit.`);return}let l=()=>{let t=document.getElementById(o)?.querySelector(`iframe[data-openpi-browser-document]`),n=t&&XR().find(e=>e.id===t.dataset.openpiBrowserPage);n&&d(e,{root:n.id})},u=new MutationObserver(l);u.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`data-openpi-browser-document`]});let f=setTimeout(()=>d(e,void 0,`The internal page did not bind. Inspect the browser's loading or embedding error.`),1e4);c=()=>{i.abort(),u.disconnect(),clearTimeout(f)},l()},m=async()=>{if(Date.now()-i.current>15e3&&document.documentElement.dataset.openpiBrowserExtension!==`ready`){u(),a.signal.aborted||(o=setTimeout(()=>void m(),1e3));return}try{let{pending:r}=await n.request(`/api/browser/control`,{method:`POST`,signal:a.signal,body:JSON.stringify({sessionId:e,sessionPath:t,pages:XR()})});s&&s!==r?.requestId&&u(),r&&!r.running&&r.request&&!s&&(s=r.requestId,r.request.operation===`open`?p(r.requestId,r.request.url).catch(()=>d(r.requestId,void 0,`The embedded browser could not open.`)):r.page?l({type:`control`,id:r.page.id,document:r.page.document,requestId:r.requestId,request:r.request}):d(r.requestId,void 0,`The embedded page is unavailable.`))}catch{u()}a.signal.aborted||(o=setTimeout(()=>void m(),250))};return window.addEventListener(`message`,f),m(),()=>{clearTimeout(o),a.abort(),u(),window.removeEventListener(`message`,f)}},[e,t])}function QR({usage:e,workspace:t,sessionId:n}){let{t:r,i18n:i}=cr(),[a,o]=(0,_.useState)(!1);if(!e)return null;let s=e.context,c=e=>new Intl.NumberFormat(i.resolvedLanguage).format(e),l=e=>new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:0}).format(e).toLowerCase(),u=s?.percent==null?r(`usageUnknown`):`${Math.round(s.percent)}%`,d=s?.percent==null?r(`usageUnknown`):`${new Intl.NumberFormat(i.resolvedLanguage,{maximumFractionDigits:1}).format(s.percent)}%`,f=s?l(s.contextWindow):r(`usageUnknown`);return(0,K.jsx)(`div`,{className:`session-usage`,children:(0,K.jsx)(gd,{isOpen:a,onOpenChange:o,placement:`below`,alignment:`end`,width:`min(360px, calc(100vw - 24px))`,label:r(`sessionUsage`),isModal:!1,hasCloseButton:!1,content:(0,K.jsxs)(`div`,{className:`session-usage-details`,children:[(0,K.jsxs)(`div`,{className:`usage-details-heading`,children:[(0,K.jsx)(`h2`,{children:r(`sessionOverview`)}),(0,K.jsx)(`button`,{className:`icon-button`,type:`button`,"aria-label":r(`close`),onClick:()=>o(!1),children:(0,K.jsx)(Lt,{"aria-hidden":`true`})})]}),(0,K.jsxs)(`section`,{className:`usage-section`,children:[(0,K.jsxs)(`div`,{className:`usage-context-heading`,children:[(0,K.jsx)(`h3`,{children:r(`usageContextLabel`)}),(0,K.jsx)(`span`,{children:d})]}),(0,K.jsxs)(`p`,{className:`usage-context-value`,children:[(0,K.jsx)(`strong`,{children:s?.tokens==null?r(`usageUnknown`):c(s.tokens)}),s&&(0,K.jsxs)(`span`,{children:[` / `,c(s.contextWindow),` tokens`]})]}),s?.percent!=null&&(0,K.jsx)(`progress`,{value:Math.max(0,Math.min(100,s.percent)),max:100,"aria-label":r(`sessionContextUsage`)}),(0,K.jsx)(`p`,{className:`usage-help`,children:r(`usageContextHelp`)})]}),(0,K.jsxs)(`section`,{className:`usage-section`,children:[(0,K.jsx)(`h3`,{children:r(`usageSessionTotals`)}),(0,K.jsxs)(`dl`,{className:`usage-metrics`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:r(`usageInputLabel`)}),(0,K.jsx)(`dd`,{children:c(e.input)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:r(`usageOutputLabel`)}),(0,K.jsx)(`dd`,{children:c(e.output)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:r(`usageTotalLabel`)}),(0,K.jsx)(`dd`,{children:c(e.total)})]})]}),(0,K.jsx)(`p`,{className:`usage-help`,children:r(`usageTotalsHelp`)})]}),t&&(0,K.jsxs)(`dl`,{className:`usage-workspace`,children:[(0,K.jsx)(`dt`,{children:r(`usageWorkspaceLabel`)}),(0,K.jsx)(`dd`,{children:t})]}),n&&(0,K.jsxs)(`details`,{className:`usage-identity`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(`span`,{children:r(`usageSessionId`)}),(0,K.jsx)(L,{"aria-hidden":`true`})]}),(0,K.jsx)(`code`,{children:n})]})]}),children:t=>(0,K.jsxs)(`button`,{...t,className:`session-usage-trigger`,type:`button`,"aria-label":r(`usageOpenDetails`,{input:l(e.input),output:l(e.output),percent:u,capacity:f}),children:[(0,K.jsxs)(`span`,{className:`usage-stat`,title:`${r(`sessionInputTokens`)}: ${c(e.input)}`,children:[(0,K.jsx)(k,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:l(e.input)})]}),(0,K.jsxs)(`span`,{className:`usage-stat`,title:`${r(`sessionOutputTokens`)}: ${c(e.output)}`,children:[(0,K.jsx)(w,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:l(e.output)})]}),(0,K.jsxs)(`span`,{className:`usage-stat`,title:`${r(`sessionContextUsage`)}: ${d}`,children:[(0,K.jsx)(ke,{"aria-hidden":`true`}),(0,K.jsxs)(`span`,{children:[u,s&&(0,K.jsxs)(`span`,{className:`usage-capacity`,children:[` / `,f]})]})]})]})})})}function $R(e,t){return new Promise((n,r)=>{let i=new FileReader,a=e=>{t.removeEventListener(`abort`,o),e?r(e):typeof i.result==`string`?n(i.result.slice(i.result.indexOf(`,`)+1)):r(Error(`File read failed`))},o=()=>{i.abort(),a(new DOMException(`File read cancelled`,`AbortError`))};i.onload=()=>a(),i.onerror=()=>a(Error(`File read failed`)),t.addEventListener(`abort`,o,{once:!0}),t.aborted?o():i.readAsDataURL(e)})}function ez({name:e,kind:t=`file`,expanded:n=!1}){let r=t===`directory`?`folder`:t===`symlink`?`link`:/\.(?:md|markdown)$/iu.test(e)?`markdown`:/\.(?:csv|tsv|xlsx?)$/iu.test(e)?`sheet`:/\.(?:png|jpe?g|gif|webp|svg|bmp|ico)$/iu.test(e)?`image`:/\.(?:pdf|docx?|pptx?)$/iu.test(e)?`document`:/\.(?:[cm]?[jt]sx?|json|html?|css|py|rs|go|sh|ya?ml|toml|xml)$/iu.test(e)?`code`:`file`;return(0,K.jsx)(r===`folder`?n?G:De:r===`link`?Re:r===`sheet`?yt:r===`image`?be:r===`markdown`||r===`document`?Se:r===`code`?ve:Ce,{className:`file-icon file-icon-${r}`,"aria-hidden":`true`})}function tz({sessionId:e,sessionPath:t,cwd:n,canWrite:r,active:i,selected:a,onSelect:o,dropTarget:s,onShowTree:c,onRemoved:l}){let{t:u}=cr(),d=(0,_.useContext)(fk),f=wk(),p=(0,_.useMemo)(()=>new rf,[]),[m,h]=(0,_.useState)(f?.files?.query??``),[g,v]=(0,_.useState)(f?.files?.expanded??[`.`]),[y,b]=(0,_.useState)({}),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(null),[T,E]=(0,_.useState)(!1),[D,O]=(0,_.useState)(0),[k,A]=(0,_.useState)(a.includes(`/`)?a.slice(0,a.lastIndexOf(`/`)):`.`),[j,M]=(0,_.useState)(null),[N,P]=(0,_.useState)(``),[F,I]=(0,_.useState)(null),[R,z]=(0,_.useState)(!1),[B,V]=(0,_.useState)(!1),[H,te]=(0,_.useState)([]),[ne,re]=(0,_.useState)(!1),[ie,ae]=(0,_.useState)([]),[U,oe]=(0,_.useState)(null),[se,ce]=(0,_.useState)(`.`),[le,ue]=(0,_.useState)(``),[de,fe]=(0,_.useState)([]),[pe,me]=(0,_.useState)(!1),[he,ge]=(0,_.useState)([]),[_e,ve]=(0,_.useState)(0),[ye,be]=(0,_.useState)(!1),[Se,Ce]=(0,_.useState)(),we=(0,_.useRef)(0),[G,De]=(0,_.useState)([]),[Oe,ke]=(0,_.useState)(!1),[Ae,je]=(0,_.useState)(``),Me=(0,_.useRef)(null),Ne=(0,_.useRef)(null),Pe=(0,_.useRef)(null),Fe=(0,_.useRef)(null),Ie=(0,_.useRef)(null),Le=(0,_.useRef)(!1),Re=(0,_.useRef)(0),Be=(0,_.useRef)(null),Ve=(0,_.useRef)(void 0),He=JSON.stringify([e,t,n]),Ue=(0,_.useRef)(He);Ue.current=He;let We=(0,_.useRef)(r);We.current=r;let Ge=(0,_.useRef)(null);(0,_.useEffect)(()=>(Ue.current=He,()=>{Ue.current=``,Ge.current?.abort(),clearTimeout(Ve.current)}),[He]),(0,_.useEffect)(()=>{Ne.current?.setAttribute(`webkitdirectory`,``)},[]),(0,_.useEffect)(()=>{if(!pe||!i)return;we.current++;let n=new AbortController;return be(!0),p.workspaceTrash(e,t,n.signal).then(r=>{!n.signal.aborted&&r.sessionId===e&&r.sessionPath===t&&(ge(r.entries),ve(r.unavailable??0),Ce(r.nextCursor))}).catch(e=>{n.signal.aborted||(z(!0),I(e instanceof Error?e.message:u(`filesReadFailed`)))}).finally(()=>{n.signal.aborted||be(!1)}),()=>n.abort()},[p,e,t,i,pe,D,u]),(0,_.useEffect)(()=>{U&&(Fe.current?.focus(),Fe.current?.select())},[U]),(0,_.useEffect)(()=>{j&&Pe.current?.focus()},[j]);let Ke=(0,_.useRef)(null),qe=(0,_.useRef)(f?.files?.treeScroll??0);(0,_.useLayoutEffect)(()=>{f?.files&&Object.assign(f.files,{query:m,expanded:g})},[f,m,g]),(0,_.useLayoutEffect)(()=>{!i||!(x||y[`.`])||qe.current!==null&&Ke.current&&(Ke.current.scrollTop=qe.current,qe.current=null)},[i,x,y]);let Je=(0,_.useRef)(y);Je.current=y;let Ye=(0,_.useRef)(x);Ye.current=x;let Xe=(0,_.useRef)(``),Ze=(0,_.useRef)(null),Qe=(0,_.useRef)(new Set),$e=(0,_.useRef)(!1),[et,tt]=(0,_.useState)(!1),nt=!!m.trim();(0,_.useLayoutEffect)(()=>{let e=Be.current;if(!e||!i)return;let t=[...Ke.current?.querySelectorAll(`[data-file-row]`)??[]].find(t=>t.dataset.fileRow===e);t&&(t.focus({preventScroll:!0}),Be.current=null)});let rt=e=>e instanceof tf&&e.code===`ARTIFACT_EXISTS`?u(`filesNameExists`):e instanceof Error?e.message:u(`filesMutationFailed`),it=e=>{h(``);let t=e.path.split(`/`),n=e.kind===`directory`?t.length:t.length-1;v(e=>[...new Set([...e,`.`,...t.slice(0,n).map((e,n)=>t.slice(0,n+1).join(`/`))])]),Be.current=e.path,O(e=>e+1),e.kind===`file`&&(e.bytes??0)<=20971520&&(o(e.path),d?.open(encodeURI(e.path)))},at=()=>{Le.current||(M(null),I(null),Ie.current?.focus({preventScroll:!0}))},ot=async n=>{if(n.preventDefault(),!j||!We.current||Le.current)return;if(!N||N===`.`||N===`..`||/[\\/\u0000-\u001f\u007f]/u.test(N)){z(!0),I(u(`filesNameInvalid`)),Pe.current?.focus();return}Le.current=!0,V(!0),I(null);let r=He;try{let n=await p.mutateWorkspaceFile(e,t,{kind:j,directory:k,name:N});if(Ue.current!==r||n.sessionId!==e||n.sessionPath!==t)return;M(null),P(``),z(!1),I(u(`filesCreated`,{path:n.path})),it(n)}catch(e){Ue.current===r&&(z(!0),I(rt(e)),Pe.current?.focus())}finally{Ue.current===r&&(Le.current=!1,V(!1))}},st=async n=>{if(!We.current||Le.current)return;let r=He;Le.current=!0,V(!0);let i=new AbortController;Ge.current=i;let a=(e,t)=>te(n=>n.map(n=>n.id===e.id?{...n,...t}:n));try{for(let o of n){if(Ue.current!==r)return;if(!We.current){a(o,{state:`error`,message:u(`filesWriteUnavailable`)});continue}if(!(!o.file&&o.kind!==`directory`)){a(o,{state:`running`,message:void 0});try{if(o.kind===`directory`){try{await p.mutateWorkspaceFile(e,t,{kind:`create-directory`,directory:o.directory,name:o.name})}catch(n){if(!(n instanceof tf)||n.code!==`ARTIFACT_EXISTS`)throw n;await p.workspaceFiles(e,t,[o.directory===`.`?``:o.directory,o.name].filter(Boolean).join(`/`),``,i.signal)}if(Ue.current!==r)return;a(o,{state:`done`,message:u(`filesImported`)}),O(e=>e+1);continue}if(!o.file)continue;if(o.file.size>52428800)throw Error(u(`filesImportTooLarge`));let n=await $R(o.file,i.signal);if(Ue.current!==r)return;if(!We.current){a(o,{state:`error`,message:u(`filesWriteUnavailable`)});continue}let s=await p.mutateWorkspaceFile(e,t,{kind:`import-file`,directory:o.directory,name:o.name,data:n,...o.createParents?{createParents:!0}:{}});if(Ue.current!==r||s.sessionId!==e||s.sessionPath!==t)return;a(o,{state:`done`,file:void 0,message:(s.bytes??0)>20971520?u(`filesImportedNoPreview`):u(`filesImported`)}),it(s)}catch(e){if(Ue.current!==r)return;a(o,{state:`error`,message:rt(e)})}}}}finally{Ge.current===i&&(Ge.current=null),Ue.current===r&&(Le.current=!1,V(!1))}},ct=(e,t=[],n=new Map,r=[])=>{if(!We.current||Le.current)return;if(e.length+r.length>2e3){z(!0),I(u(`filesImportFolderLimit`));return}c(!0);let i=[...[...new Set(r)].sort((e,t)=>e.split(`/`).length-t.split(`/`).length).map(e=>({id:++Re.current,name:e.split(`/`).at(-1),directory:[k===`.`?``:k,...e.split(`/`).slice(0,-1)].filter(Boolean).join(`/`)||`.`,kind:`directory`,state:`pending`})),...e.map(e=>{let t=n.get(e)??e.webkitRelativePath;return{id:++Re.current,name:e.name,directory:t?[k===`.`?``:k,...t.split(`/`).slice(0,-1)].filter(Boolean).join(`/`)||`.`:k,createParents:!!t,file:e,state:`pending`}})];te(e=>[...e,...t.map(e=>({id:++Re.current,name:e,directory:k,state:`error`,message:u(`filesImportDirectoryUnsupported`)})),...i]),st(i)},lt=async(n,r)=>{if(!We.current||Le.current)return;let i=He,s=r.filter(e=>!r.some(t=>t.kind===`directory`&&e.path.startsWith(`${t.path}/`)));Le.current=!0,V(!0),fe([]);let c=[],f=new Set;try{for(let r of s){if(Ue.current!==i||!We.current)return;try{if(!r.identity)throw Error(u(`filesRefreshBeforeOrganizing`));let s=await p.mutateWorkspaceFile(e,t,n===`trash`?{kind:n,path:r.path,identity:r.identity}:{kind:n,path:r.path,identity:r.identity,directory:se,name:U?.rename?le:r.name});if(Ue.current!==i||s.sessionId!==e||s.sessionPath!==t)return;if(f.add(r.path),s.trashed&&c.push(s.trashed),s.moved&&Lk(e,t,s.moved.from,s.moved.to),r.kind===`directory`){let e=e=>e===r.path||e.startsWith(`${r.path}/`);if(v(t=>n===`trash`?t.filter(t=>!e(t)):t.map(t=>e(t)?`${s.path}${t.slice(r.path.length)}`:t)),A(t=>e(t)?n===`move`?`${s.path}${t.slice(r.path.length)}`:r.path.split(`/`).slice(0,-1).join(`/`)||`.`:t),n===`move`&&e(a)){let e=`${s.path}${a.slice(r.path.length)}`;o(e),d?.open(encodeURI(e))}}n===`move`&&it(s),fe(e=>[...e,{path:r.path}])}catch(e){if(Ue.current!==i)return;fe(t=>[...t,{path:r.path,error:rt(e)}])}}De(c),n===`trash`&&l([...f]),ae(e=>e.filter(e=>![...f].some(t=>t===e.path||e.path.startsWith(`${t}/`)))),oe(null),O(e=>e+1)}finally{Ue.current===i&&(Le.current=!1,V(!1))}},ut=async n=>{if(!We.current||Le.current)return;let r=He;Le.current=!0,V(!0),fe([]);try{for(let i of n){if(Ue.current!==r||!We.current)return;try{let n=await p.mutateWorkspaceFile(e,t,{kind:`restore`,id:i.id,identity:i.identity});if(Ue.current!==r||n.sessionId!==e||n.sessionPath!==t)return;De(e=>e.filter(e=>e.id!==i.id)),ge(e=>e.filter(e=>e.id!==i.id)),fe(e=>[...e,{path:i.path}]),it(n)}catch(e){if(Ue.current!==r)return;fe(t=>[...t,{path:i.path,error:rt(e)}])}}O(e=>e+1)}finally{Ue.current===r&&(Le.current=!1,V(!1))}},ft=async()=>{if(!Se||ye)return;let n=we.current,r=He;be(!0);try{let i=await p.workspaceTrash(e,t,void 0,Se);if(n!==we.current||Ue.current!==r||i.sessionId!==e||i.sessionPath!==t)return;ge(e=>[...new Map([...e,...i.entries].map(e=>[e.id,e])).values()]),ve(e=>e+(i.unavailable??0)),Ce(i.nextCursor)}catch(e){n===we.current&&Ue.current===r&&(z(!0),I(rt(e)))}finally{n===we.current&&Ue.current===r&&be(!1)}},pt=e=>ae(t=>t.some(t=>t.path===e.path)?t.filter(t=>t.path!==e.path):[...t,e]),mt=(e,t=!1)=>{oe({entries:e,rename:t});let n=e[0]?.path??``;ce(t?n.split(`/`).slice(0,-1).join(`/`)||`.`:k),ue(e[0]?.name??``),I(null)},gt=(0,_.useRef)(ct);gt.current=ct,(0,_.useEffect)(()=>{let e=s.current;if(!e)return;let t=e=>{if(!e.dataTransfer?.types.includes(`Files`))return;e.preventDefault();let t=We.current&&!Le.current;e.dataTransfer.dropEffect=t?`copy`:`none`,ke(t)},n=t=>{(!(t.relatedTarget instanceof Node)||!e.contains(t.relatedTarget))&&ke(!1)},r=e=>{let t=e.dataTransfer;if(!t?.types.includes(`Files`)||(e.preventDefault(),ke(!1),!We.current||Le.current))return;let n=[],r=[],i=[];for(let e of t.items){if(e.kind!==`file`)continue;let t=e.webkitGetAsEntry?.();if(t?.isDirectory&&`createReader`in t)i.push(t);else if(t?.isDirectory)r.push(t.name);else{let t=e.getAsFile();t&&n.push(t)}}if(i.length){let e=Ue.current,t=new Map,a=[],o=0,s=async(r,i)=>{if(Ue.current!==e||!We.current)throw new DOMException(`Import cancelled`,`AbortError`);if(++o>2e3||i.split(`/`).length>64)throw Error(u(`filesImportFolderLimit`));let c=i?`${i}/${r.name}`:r.name;if(r.isDirectory){a.push(c);let e=r.createReader();for(;;){let t=await new Promise((t,n)=>e.readEntries(t,n));if(!t.length)break;for(let e of t)await s(e,c)}}else if(r.isFile){let e=await new Promise((e,t)=>r.file(e,t));t.set(e,c),n.push(e)}};Le.current=!0,V(!0),(async()=>{try{for(let e of i)await s(e,``);if(Ue.current!==e||!We.current)return;Le.current=!1,V(!1),gt.current(n,r,t,a)}catch(t){Ue.current===e&&(z(!0),I(t instanceof Error?t.message:u(`filesMutationFailed`)))}finally{Ue.current===e&&!Ge.current&&(Le.current=!1,V(!1))}})();return}gt.current(t.items.length?n:[...t.files],r)};return e.addEventListener(`dragover`,t),e.addEventListener(`dragleave`,n),e.addEventListener(`drop`,r),()=>{e.removeEventListener(`dragover`,t),e.removeEventListener(`dragleave`,n),e.removeEventListener(`drop`,r)}},[s,u]);let _t=async(e,t)=>{let r=He,i=n.includes(`\\`)?`\\`:`/`,a=await wd(t?`${n.replace(/[\\/]$/u,``)}${i}${e.split(`/`).join(i)}`:e);Ue.current===r&&(clearTimeout(Ve.current),je(u(a?`filesPathCopied`:`copyFailed`,{path:e})),Ve.current=setTimeout(()=>je(``),3e3))};(0,_.useEffect)(()=>{if(!i)return;let n=new AbortController;Ze.current=n;let r;Xe.current!==m.trim()&&(Xe.current=m.trim(),Ye.current=null,S(null)),r=setTimeout(async()=>{if(document.visibilityState!==`hidden`){E(!0);try{let r=async(r,i,a)=>{let o=await p.workspaceFiles(e,t,r,i,n.signal);for(o.nextCursor&&Qe.current.add(o.nextCursor);o.nextCursor&&o.entries.length{document.visibilityState!==`hidden`&&O(e=>e+1)};return window.addEventListener(`focus`,a),document.addEventListener(`visibilitychange`,a),()=>{n.abort(),clearTimeout(r),window.removeEventListener(`focus`,a),document.removeEventListener(`visibilitychange`,a);for(let e of Qe.current)p.releaseFileListing(e).catch(()=>void 0);Qe.current.clear(),$e.current=!1,tt(!1)}},[i,p,g,m,nt,e,t,D,u]);let vt=e=>v(t=>t.includes(e)?t.filter(t=>t!==e&&!t.startsWith(`${e}/`)):[...t,e]),yt=async n=>{let r=nt?Ye.current:Je.current[n],i=Ze.current;if(!(!r?.nextCursor||!i||i.signal.aborted||$e.current||T)){$e.current=!0,tt(!0),w(null);try{let a=await p.workspaceFiles(e,t,n,nt?m.trim():``,i.signal,r.nextCursor);if(Qe.current.delete(r.nextCursor),a.nextCursor&&Qe.current.add(a.nextCursor),i.signal.aborted)return;let o=[...new Map([...r.entries,...a.entries].map(e=>[e.path,e])).values()],s={...a,entries:o};nt?S(s):b(e=>({...e,[n]:s}))}catch(e){i.signal.aborted||w(e instanceof Error?e.message:u(`filesReadFailed`))}finally{i.signal.aborted||($e.current=!1,tt(!1))}}},bt=(e,t)=>t?.nextCursor?(0,K.jsxs)(`li`,{className:`file-tree-more`,children:[(0,K.jsx)(`button`,{type:`button`,disabled:T||et,onClick:()=>void yt(e),children:u(et?`loading`:`filesLoadMore`)}),(0,K.jsx)(`small`,{children:u(`filesLoaded`,{count:t.entries.length})})]}):null,xt=e=>{let t=[...Ke.current?.querySelectorAll(`button[data-file-row]:not(:disabled)`)??[]],n=t.indexOf(document.activeElement),r=t[n];if(!r)return;let i;if(e.key===`ArrowDown`)i=t[Math.min(n+1,t.length-1)];else if(e.key===`ArrowUp`)i=t[Math.max(n-1,0)];else if(e.key===`Home`)i=t[0];else if(e.key===`End`)i=t.at(-1);else if(e.key===`ArrowRight`&&r.getAttribute(`aria-expanded`)===`false`)r.click();else if(e.key===`ArrowLeft`)r.getAttribute(`aria-expanded`)===`true`?r.click():i=t.find(e=>e.dataset.fileRow===r.dataset.fileRow?.split(`/`).slice(0,-1).join(`/`));else return;e.preventDefault(),i?.focus()},St=(e,t=0)=>e.map(e=>{let n=e.kind===`directory`,i=g.includes(e.path),s=r&&!!e.identity&&!e.path.split(`/`).some(e=>[`.git`,`.pi`,`.openpi-trash`].includes(e.toLowerCase()))&&(n||e.kind===`file`);return(0,K.jsxs)(`li`,{children:[(0,K.jsxs)(`div`,{className:`file-tree-item`,children:[ne&&(0,K.jsx)(`input`,{type:`checkbox`,className:`file-tree-check`,"aria-label":u(`filesSelectItem`,{name:e.name}),checked:ie.some(t=>t.path===e.path),disabled:!s||B,onChange:()=>pt(e)}),(0,K.jsxs)(`button`,{type:`button`,"data-file-row":e.path,className:`file-tree-row`,style:{paddingInlineStart:10+t*16},"aria-expanded":n?i:void 0,"aria-current":!n&&a===e.path?`true`:void 0,disabled:e.kind===`symlink`||e.kind===`other`,title:e.kind===`symlink`?u(`filesSymlink`):e.path,onClick:t=>{if(s&&(t.metaKey||t.ctrlKey)){re(!0),pt(e);return}n?(A(e.path),nt?(h(``),v([`.`,...e.path.split(`/`).map((e,t,n)=>n.slice(0,t+1).join(`/`))])):vt(e.path)):(A(e.path.includes(`/`)?e.path.slice(0,e.path.lastIndexOf(`/`)):`.`),o(e.path),d?.open(encodeURI(e.path),void 0,t.currentTarget))},children:[n?i?(0,K.jsx)(L,{className:`file-chevron`,"aria-hidden":`true`}):(0,K.jsx)(ee,{className:`file-chevron`,"aria-hidden":`true`}):(0,K.jsx)(`span`,{className:`file-chevron`}),(0,K.jsx)(ez,{name:e.name,kind:e.kind,expanded:i}),(0,K.jsxs)(`span`,{className:`file-tree-name`,children:[e.name,nt&&(0,K.jsx)(`small`,{children:e.path})]})]}),(0,K.jsx)(jA,{button:{label:u(`filesPathActions`,{name:e.name}),icon:(0,K.jsx)(W,{"aria-hidden":`true`}),isIconOnly:!0,size:`sm`,variant:`ghost`,className:`file-path-actions`},items:[{label:u(`filesCopyRelativePath`),onClick:()=>void _t(e.path,!1)},{label:u(`filesCopyAbsolutePath`),onClick:()=>void _t(e.path,!0)},{label:u(`filesRename`),isDisabled:!s||B,onClick:()=>mt([e],!0)},{label:u(`filesMove`),isDisabled:!s||B,onClick:()=>mt([e])},{label:u(`filesTrashAction`),isDisabled:!s||B,onClick:()=>void lt(`trash`,[e])}],menuWidth:200,alignment:`end`,hasChevron:!1})]}),!nt&&n&&i&&(0,K.jsxs)(`ul`,{children:[y[e.path]?St(y[e.path].entries,t+1):(0,K.jsx)(`li`,{className:`file-tree-note`,children:u(`loading`)}),bt(e.path,y[e.path])]})]},e.path)});return(0,K.jsxs)(`aside`,{className:`file-explorer`,"aria-label":u(`filesExplorer`),"data-drag-over":Oe||void 0,children:[(0,K.jsxs)(`div`,{className:`file-search`,children:[(0,K.jsx)(ht,{"aria-hidden":`true`}),(0,K.jsx)(`input`,{value:m,onChange:e=>h(e.currentTarget.value.slice(0,200)),placeholder:u(`filesSearch`),"aria-label":u(`filesSearch`)}),(0,K.jsx)(`span`,{className:`file-search-progress`,"aria-hidden":`true`,"data-loading":T||void 0}),(0,K.jsx)(`button`,{type:`button`,className:`icon-button`,"aria-label":u(`refreshFiles`),title:u(`refreshFiles`),onClick:()=>O(e=>e+1),disabled:T,children:(0,K.jsx)(dt,{"aria-hidden":`true`})})]}),(0,K.jsxs)(`div`,{className:`file-create-toolbar`,children:[(0,K.jsxs)(`fieldset`,{className:`file-write-actions`,"aria-label":u(`filesWorkspaceActions`),children:[(0,K.jsx)(jA,{button:{ref:Ie,label:u(`filesCreateMenu`),variant:`ghost`,className:`file-toolbar-button`,tooltip:r&&!B?u(`filesCreateMenu`):void 0,isDisabled:!r||B},items:[`create-file`,`create-directory`].map(e=>({label:u(e===`create-file`?`filesNewFile`:`filesNewDirectory`),icon:e===`create-file`?(0,K.jsx)(xe,{"aria-hidden":`true`}):(0,K.jsx)(Ee,{"aria-hidden":`true`}),isDisabled:!r||B,onClick:()=>{M(e),P(``),I(null)}})),menuWidth:190}),(0,K.jsx)(jA,{button:{label:u(`filesImportMenu`),variant:`ghost`,className:`file-toolbar-button`,tooltip:r&&!B?u(`filesImportMenu`):void 0,isDisabled:!r||B},items:[{label:u(`filesImport`),icon:(0,K.jsx)(Mt,{"aria-hidden":`true`}),isDisabled:!r||B,onClick:()=>Me.current?.click()},{label:u(`filesImportFolder`),icon:(0,K.jsx)(Te,{"aria-hidden":`true`}),isDisabled:!r||B,onClick:()=>Ne.current?.click()}],menuWidth:190}),(0,K.jsx)(`input`,{ref:Me,type:`file`,multiple:!0,hidden:!0,"aria-label":u(`filesImportChoose`),onChange:e=>{ct([...e.currentTarget.files??[]]),e.currentTarget.value=``}}),(0,K.jsx)(`input`,{ref:Ne,type:`file`,multiple:!0,hidden:!0,"aria-label":u(`filesImportFolderChoose`),onChange:e=>{ct([...e.currentTarget.files??[]]),e.currentTarget.value=``}}),(0,K.jsxs)(jA,{button:{label:u(`filesMoreMenu`),variant:`ghost`,className:`file-toolbar-button`,tooltip:u(`filesMoreMenu`)},menuWidth:210,children:[(0,K.jsx)(XA,{label:u(`filesSelectMultiple`),icon:(0,K.jsx)(ze,{"aria-hidden":`true`}),value:ne,isDisabled:!r||B,hasCloseOnSelect:!0,onChange:e=>{re(e),ae([])}}),(0,K.jsx)(XA,{label:u(`filesTrash`),icon:(0,K.jsx)(kt,{"aria-hidden":`true`}),value:pe,hasCloseOnSelect:!0,onChange:me})]})]}),(0,K.jsxs)(`p`,{className:`file-write-directory`,title:k,children:[(0,K.jsxs)(`span`,{children:[u(`filesTargetDirectory`),`:`,` `,k===`.`?u(`filesWorkspaceRoot`):k]}),k!==`.`&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>A(`.`),children:u(`filesWorkspaceRoot`)})]})]}),ne&&(0,K.jsxs)(`div`,{className:`file-organization-bar`,children:[(0,K.jsx)(`span`,{children:u(`filesSelectedCount`,{count:ie.length})}),(0,K.jsx)(`button`,{type:`button`,disabled:!ie.length||B||!r,onClick:()=>mt(ie),children:u(`filesMove`)}),(0,K.jsx)(`button`,{type:`button`,disabled:!ie.length||B||!r,onClick:()=>void lt(`trash`,ie),children:u(`filesTrashAction`)})]}),U&&(0,K.jsxs)(`form`,{className:`file-create-form`,onSubmit:e=>{e.preventDefault(),(!U.rename||le.trim())&<(`move`,U.entries)},children:[(0,K.jsxs)(`label`,{children:[u(U.rename?`filesRename`:`filesMoveDestination`),(0,K.jsx)(`input`,{ref:Fe,value:U.rename?le:se,"aria-label":u(U.rename?`filesNewName`:`filesMoveDestination`),disabled:B,onChange:e=>U.rename?ue(e.currentTarget.value):ce(e.currentTarget.value)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`button`,{type:`submit`,disabled:B||!r,children:u(U.rename?`filesRename`:`filesMove`)}),(0,K.jsx)(`button`,{type:`button`,disabled:B,onClick:()=>oe(null),children:u(`cancel`)})]})]}),de.length>0&&(0,K.jsxs)(`div`,{className:`file-import-results`,children:[(0,K.jsx)(`ol`,{"aria-label":u(`filesOrganizationResults`),"aria-live":`polite`,children:de.map(e=>(0,K.jsxs)(`li`,{children:[(0,K.jsx)(`span`,{children:e.path}),(0,K.jsx)(`small`,{role:e.error?`alert`:void 0,children:e.error??u(`filesOperationDone`)})]},e.path))}),G.length>0&&(0,K.jsx)(`button`,{type:`button`,disabled:B||!r,onClick:()=>void ut(G),children:u(`filesUndoTrash`)})]}),pe&&(0,K.jsxs)(`section`,{className:`file-trash-list`,"aria-label":u(`filesTrash`),children:[(0,K.jsx)(`p`,{children:u(`filesTrashDetail`)}),_e>0&&(0,K.jsx)(`p`,{role:`alert`,children:u(`filesTrashUnavailable`,{count:_e})}),ye&&he.length===0?(0,K.jsx)(`p`,{children:u(`loading`)}):he.length===0?(0,K.jsx)(`p`,{children:u(`filesTrashEmpty`)}):(0,K.jsx)(`ul`,{children:he.map(e=>(0,K.jsxs)(`li`,{children:[(0,K.jsx)(`span`,{title:e.path,children:e.path}),(0,K.jsx)(`button`,{type:`button`,disabled:!r||B,"aria-label":u(`filesRestoreItem`,{name:e.path}),onClick:()=>void ut([e]),children:u(`filesRestore`)})]},e.id))}),Se&&(0,K.jsx)(`button`,{type:`button`,disabled:ye,onClick:()=>void ft(),children:u(`filesLoadMore`)})]}),j&&(0,K.jsxs)(`form`,{className:`file-create-form`,onSubmit:e=>void ot(e),onKeyDown:e=>{e.key===`Escape`&&!e.nativeEvent.isComposing&&(e.preventDefault(),e.stopPropagation(),at())},children:[(0,K.jsxs)(`label`,{children:[u(j===`create-file`?`filesFileName`:`filesDirectoryName`),(0,K.jsx)(`input`,{ref:Pe,value:N,maxLength:255,disabled:B,"aria-invalid":!!(F&&R),onChange:e=>P(e.currentTarget.value)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`button`,{type:`submit`,disabled:!r||B,children:u(B?`filesCreating`:`filesCreate`)}),(0,K.jsx)(`button`,{type:`button`,disabled:B,onClick:at,children:u(`cancel`)})]})]}),F&&(0,K.jsx)(`p`,{className:`file-tree-note${R?` evidence-warning`:``}`,role:R?`alert`:`status`,children:F}),H.length>0&&(0,K.jsxs)(`div`,{className:`file-import-results`,children:[(0,K.jsx)(`p`,{children:u(`filesImportLimit`)}),(0,K.jsx)(`ol`,{"aria-label":u(`filesImportResults`),"aria-live":`polite`,children:H.map(e=>(0,K.jsxs)(`li`,{"data-import-state":e.state,children:[(0,K.jsx)(`span`,{title:`${e.directory}/${e.name}`,children:e.name}),(0,K.jsx)(`small`,{children:e.message??u(e.state===`running`?`filesImporting`:`filesImportPending`)}),e.state===`error`&&(e.file||e.kind===`directory`)&&(0,K.jsx)(`button`,{type:`button`,disabled:!r||B,onClick:()=>void st([e]),children:u(`filesRetryImport`)})]},e.id))}),(0,K.jsx)(`button`,{type:`button`,disabled:B,onClick:()=>te(e=>e.filter(e=>e.state!==`done`)),children:u(`filesClearImported`)})]}),(0,K.jsx)(`span`,{className:`sr-only`,role:`status`,children:Ae}),C&&(0,K.jsx)(`p`,{className:`file-tree-note evidence-warning`,role:`alert`,children:C}),(0,K.jsxs)(`section`,{className:`file-tree`,"aria-label":u(`filesExplorer`),ref:Ke,onKeyDown:xt,onScroll:e=>{f?.files&&(f.files.treeScroll=e.currentTarget.scrollTop)},"aria-busy":T,children:[(0,K.jsxs)(`ul`,{children:[St(nt?x?.entries??[]:y[`.`]?.entries??[]),bt(`.`,nt?x:y[`.`])]}),(nt?x?.truncated:y[`.`]?.truncated)&&(0,K.jsx)(`p`,{className:`file-tree-note`,children:u(`filesTruncated`)}),!T&&!C&&(nt?x?.entries.length===0:y[`.`]?.entries.length===0)&&(0,K.jsx)(`p`,{className:`file-tree-note`,children:u(nt?`filesNoMatches`:`filesEmpty`)})]})]})}function nz({sessionId:e,sessionPath:t,cwd:n,active:r,canWrite:i=!0}){let{t:a}=cr(),o=wk(),[s,c]=(0,_.useState)(o?.files?.selected??``),[l,u]=(0,_.useState)(o?.files?.treeVisible??!0),d=(0,_.useRef)(null),f=(0,_.useRef)(null);return(0,_.useLayoutEffect)(()=>{o&&(o.files={query:``,expanded:[`.`],treeScroll:0,...o.files,selected:s,treeVisible:l})},[o,s,l]),(0,K.jsx)(`div`,{ref:d,className:`files-workspace`,"data-tree-visible":l,"data-preview-open":!!s,children:(0,K.jsxs)(Bk,{ref:f,sessionId:e,sessionPath:t,embedded:!0,active:r,onClose:()=>{c(``),u(!0)},children:[(0,K.jsx)(Cd,{content:a(l?`filesHideTree`:`filesShowTree`),placement:`below`,children:(0,K.jsx)(`button`,{type:`button`,className:`files-tree-toggle icon-button`,"aria-label":a(l?`filesHideTree`:`filesShowTree`),"aria-pressed":l,onClick:()=>u(e=>!e),children:l?(0,K.jsx)(G,{"aria-hidden":`true`}):(0,K.jsx)(De,{"aria-hidden":`true`})})}),!s&&(0,K.jsxs)(`div`,{className:`files-empty-header`,title:n,children:[(0,K.jsx)(G,{"aria-hidden":`true`}),n.split(/[\\/]/u).filter(Boolean).at(-1)||n]}),!s&&(0,K.jsxs)(`div`,{className:`files-preview-empty`,children:[(0,K.jsx)(Se,{"aria-hidden":`true`}),(0,K.jsx)(`h3`,{children:a(`filesChoose`)}),(0,K.jsx)(`p`,{children:a(`filesChooseDetail`)})]}),(0,K.jsx)(`div`,{className:`files-tree-container`,hidden:!l,children:(0,K.jsx)(tz,{sessionId:e,sessionPath:t,cwd:n,canWrite:i,active:r&&l,selected:s,onSelect:c,dropTarget:d,onShowTree:u,onRemoved:e=>{e.some(e=>e===s||s.startsWith(`${e}/`))&&f.current?.close({restoreFocus:!1})}},JSON.stringify([e,t,n]))})]})})}var rz=(0,_.createContext)(null);rz.displayName=`CollapsibleGroupContext`;var iz=(0,_.createContext)(null);iz.displayName=`CollapsibleGroupPresentationContext`;function az(e){let{isCollapsible:t,value:n}=e,r=(0,_.use)(rz),i=r!=null&&n!=null,a=t===!0?{}:t||null,o=a!=null,[s,c]=(0,_.useState)(()=>i?!0:a?.isOpen===void 0?a?.defaultIsOpen??!0:a.isOpen),l;return l=i&&n!=null?r.isOpen(n):a?.isOpen===void 0?s:a.isOpen,{isEnabled:o,isOpen:l,toggle:()=>{if(i&&n!=null){r.toggle(n);return}let e=!l;a?.isOpen===void 0&&c(e),a?.onOpenChange?.(e)}}}var oz={info:`info`,warning:`warning`,error:`error`,success:`success`},sz={info:`status`,warning:`alert`,error:`alert`,success:`status`},cz=`status`,lz={info:`accent`,warning:`warning`,error:`error`,success:`success`},uz={root:{k1xSpc:`x78zum5`,kXwgrk:`xdt5ytf`,kMv6JI:`xjb2p0i`,$$css:!0},rootElevatedCard:{kaIpWk:`x1vf2byn`,$$css:!0},header:{k1xSpc:`x78zum5`,kGNEyG:`x1cy8zhl`,kwnvtZ:`x1a02dak`,k1C7PZ:`xak3so`,khm7nJ:`x4olc9o`,k8WAf4:`x8o8v82`,kg3NbH:`x1pzlopt`,$$css:!0},headerCardStandalone:{kaIpWk:`x1vf2byn`,$$css:!0},headerCardWithContent:{krdFHd:`xwxb7qi`,kfmiAY:`x13nour3`,kVL7Gh:`xbiv7yw`,kT0f0o:`x16uus16`,$$css:!0},headerCentered:{kGNEyG:`x6s0dn4`,$$css:!0},endArea:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,kwnvtZ:`x1a02dak`,kjj79g:`x13a6bvl`,kOIVth:`x1txdalj`,kmuXW:`x2lah0s`,ks0D6T:`x193iq5w`,keTefX:`xvc5jky`,kqGvvJ:`x81ka23`,$$css:!0},chevron:{k1ekBW:`x11xpdln`,kIyJzY:`xuedmi6 x12w9bfk`,kAMwcw:`xlr8y92`,$$css:!0},chevronExpanded:{k3aq6I:`x19jd1h0`,$$css:!0}},dz={info:{kWkggS:`xgcxg3y`,$$css:!0},warning:{kWkggS:`x24i8r5`,$$css:!0},error:{kWkggS:`x1pritpl`,$$css:!0},success:{kWkggS:`xu13z74`,$$css:!0}};function fz(e){return Object.prototype.hasOwnProperty.call(dz,e)}var pz={none:{kGVxlE:`x1gnnqk1`,$$css:!0},low:{kGVxlE:`x1i5ehqx`,$$css:!0},med:{kGVxlE:`x14hfi27`,$$css:!0},high:{kGVxlE:`x1kcpxr7`,$$css:!0}};function mz({status:e,title:t,description:n,icon:r,isDismissable:i=!1,onDismiss:a,dismissLabel:o,endContent:s,container:c=`card`,elevation:l=`none`,collapsible:u=!0,children:d,xstyle:f,className:p,style:m,ref:h,onFocusCapture:g,onPointerDownCapture:v,...y}){let b=Rc(),[x,S]=(0,_.useState)(!1),C=typeof u==`object`&&u?u:{},{isEnabled:w,isOpen:T,toggle:E}=az({isCollapsible:u!==!1&&{...C,defaultIsOpen:C.defaultIsOpen??!1}}),D=(0,_.useRef)(null),O=(0,_.useId)(),k=oz[e],A=sz[e]??cz,j=lz[e],M=Ea(d),N=b(`@astryx.banner.dismiss`),P=o??N,F=o??(typeof t==`string`?b(`@astryx.banner.dismissTitled`,{dismiss:N,title:t}):N);if(x)return null;let I=(e,t)=>{e instanceof HTMLElement&&e!==document.body&&!t.contains(e)&&(D.current=e)},L=e=>{I(e.relatedTarget,e.currentTarget)},R=e=>{I(document.activeElement,e.currentTarget)},ee=()=>{let e=D.current;S(!0),a?.(),e?.isConnected&&e.focus()},z=w&&M,B=Ea(s)||i||z,V=Ea(s)||i,H=!Ea(n)&&V,te=M&&(!w||T),ne=c===`card`;return(0,K.jsxs)(`div`,{ref:h,role:A,onFocusCapture:ca(g,L),onPointerDownCapture:ca(v,R),...oa(Sr(uz.root,pz[l],ne&&l!==`none`&&uz.rootElevatedCard,f),p,m),...y,children:[(0,K.jsxs)(`div`,{...oa(ba(`banner`,{container:c,status:e}),Sr(uz.header,H&&uz.headerCentered,fz(e)&&dz[e],ne&&(te?uz.headerCardWithContent:uz.headerCardStandalone))),children:[(0,K.jsx)(`div`,{...Ea(r)?oa(ba(`banner-icon`,{status:e}),{className:`x78zum5 x6s0dn4 x2lah0s`}):{className:`x78zum5 x6s0dn4 x2lah0s`},"aria-hidden":`true`,children:Ea(r)?r:k==null?null:(0,K.jsx)(xu,{icon:k,size:`md`,color:j,...ba(`banner-icon`,{status:e})})}),(0,K.jsxs)(`div`,{...{0:{className:`x78zum5 xdt5ytf xxhr3t x98rzlu xeuugli`},1:{className:`x78zum5 xdt5ytf xxhr3t x98rzlu xeuugli xgualba`}}[!!Ea(s)<<0],children:[(0,K.jsx)(`div`,{className:`x1ghz6dp xjb2p0i xcr08ib x2mo6ok x1kq96og x1tgivj0 xj0a0fe`,children:t}),Ea(n)&&(0,K.jsx)(`div`,{className:`x1ghz6dp xjb2p0i x141an7d x1sodnla x1ltkj2j xv1l7n4 xj0a0fe`,children:n})]}),B&&(0,K.jsxs)(`div`,{...Sr(uz.endArea,rs.inset(Br[`--spacing-2`])),children:[s,z&&(0,K.jsx)(qc,{variant:`ghost`,size:`sm`,label:b(T?`@astryx.banner.collapse`:`@astryx.banner.expand`),tooltip:b(T?`@astryx.banner.collapse`:`@astryx.banner.expand`),icon:(0,K.jsx)(xu,{icon:`chevronDown`,size:`sm`,color:`inherit`,xstyle:[uz.chevron,T&&uz.chevronExpanded]}),onClick:E,"aria-expanded":T,"aria-controls":te?O:void 0,isIconOnly:!0}),i&&(0,K.jsx)(qc,{variant:`ghost`,size:`sm`,label:F,tooltip:P,icon:(0,K.jsx)(xu,{icon:`close`,size:`sm`,color:`inherit`}),onClick:ee,isIconOnly:!0})]})]}),te&&(0,K.jsx)(`div`,{id:z?O:void 0,...oa(ba(`banner-content`,{container:c,status:e}),{0:{className:`x1de1mus x8o8v82 x1pzlopt xgbv0en xw8tdv1 x92x3c3 x1t7ytsu x18b5jzi x1q0q8m5 x1j92z86 x1gejf6u xw8gpjh`},1:{className:`x1de1mus x8o8v82 x1pzlopt xgbv0en xw8tdv1 x92x3c3 x1t7ytsu x18b5jzi x1q0q8m5 x1j92z86 x1gejf6u xw8gpjh x1k5g1gk x1eprgri`}}[!!ne<<0]),children:d})]})}mz.displayName=`Banner`;var hz={container:{k1xSpc:`x78zum5`,kXwgrk:`xdt5ytf`,kGNEyG:`x6s0dn4`,kjj79g:`xl56j7k`,k9WMMc:`x2b8uid`,kOIVth:`x18g69wz`,k8WAf4:`xmfvnks`,kg3NbH:`xm7rs69`,$$css:!0},containerCompact:{kOIVth:`x1txdalj`,k8WAf4:`x1na6nto`,kg3NbH:`x1pzlopt`,$$css:!0}};function gz({title:e,description:t,icon:n,actions:r,headingLevel:i=3,isCompact:a=!1,xstyle:o,className:s,style:c,ref:l,...u}){let d=`h${i}`;return(0,K.jsxs)(`div`,{ref:l,...u,role:`status`,...oa(ba(`empty-state`,{variant:a?`compact`:null}),Sr(hz.container,a&&hz.containerCompact,o),s,c),children:[n!=null&&(0,K.jsx)(`div`,{"aria-hidden":`true`,children:n}),(0,K.jsxs)(`div`,{className:`x78zum5 xdt5ytf x6s0dn4 xxc7z9f`,children:[(0,_.createElement)(d,oa(ba(`empty-state-title`,{variant:a?`compact`:null}),{0:{className:`x1ghz6dp xjb2p0i x18juvz8 x2mo6ok xf74fhv x1tgivj0`},1:{className:`x1ghz6dp xjb2p0i x2mo6ok xf74fhv x1tgivj0 xcr08ib`}}[!!a<<0]),e),t!=null&&(0,K.jsx)(`div`,{...oa(ba(`empty-state-description`,{variant:a?`compact`:null}),{0:{className:`x1ghz6dp xjb2p0i xjm74w1 x1sodnla xw6l6zx xv1l7n4`},1:{className:`x1ghz6dp xjb2p0i x1sodnla xw6l6zx xv1l7n4 x141an7d`}}[!!a<<0]),children:t})]}),r!=null&&(0,K.jsx)(`div`,{...{0:{className:`x78zum5 x1q0g3np x6s0dn4 x1txdalj xcsaf9d`},1:{className:`x78zum5 x6s0dn4 x1txdalj xcsaf9d xdt5ytf`}}[!!a<<0],children:r})]})}gz.displayName=`EmptyState`;var _z=1e3,vz=100,yz={root:{kWkggS:`xprdx6m x1j0df82 x1o55y2u`,kSiTet:`xvpkmg4 x1tbh5bv`,$$css:!0},animate:{kILWW9:`xpz12be`,k44tkh:`xqgcaz`,ko0y90:`xa4qsjk`,kKVMdj:`xeuoslp x1aquc0h`,kyAemX:`x193epu2`,$$css:!0}},bz={0:{kaIpWk:`xwksslw`,$$css:!0},1:{kaIpWk:`xx3sua9`,$$css:!0},2:{kaIpWk:`xh6dtrn`,$$css:!0},3:{kaIpWk:`x1hviunn`,$$css:!0},4:{kaIpWk:`x1hviunn`,$$css:!0},none:{kaIpWk:`x2u8bby`,$$css:!0},rounded:{kaIpWk:`xjspbzw`,$$css:!0}},xz={kKxzle:`xvo38ju`,$$css:!0},Sz={animationDelay:e=>[xz,{"--x-animationDelay":(e=>typeof e==`number`?e+`ms`:e??void 0)(`${_z+vz*e}ms`)}],dimensions:(e,t)=>[{kzqmXN:(typeof e==`number`?`${e}px`:e)==null?typeof e==`number`?`${e}px`:e:`x5lhr3w`,kZKoxP:(typeof t==`number`?`${t}px`:t)==null?typeof t==`number`?`${t}px`:t:`x16ye13r`,$$css:!0},{"--x-width":(e=>typeof e==`number`?e+`px`:e??void 0)(typeof e==`number`?`${e}px`:e),"--x-height":(e=>typeof e==`number`?e+`px`:e??void 0)(typeof t==`number`?`${t}px`:t)}]};function Cz({width:e=`100%`,height:t=`100%`,radius:n=3,index:r=0,"data-testid":i,xstyle:a,className:o,style:s,ref:c,...l}){return(0,K.jsx)(`div`,{ref:c,"aria-hidden":`true`,"data-testid":i,...oa(ba(`skeleton`),Sr(yz.root,yz.animate,bz[n],Sz.dimensions(e,t),Sz.animationDelay(r),a),o,s),...l})}Cz.displayName=`Skeleton`;function wz({branches:e,value:t,loading:n,onChange:r}){let{t:i}=cr(),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(!1),l=(0,_.useRef)(null),u=(0,_.useRef)([]),d=(0,_.useRef)(null),f=(0,_.useId)(),p=e.options.filter(e=>`${e.label} ${e.ref}`.toLocaleLowerCase().includes(a.toLocaleLowerCase()));(0,_.useEffect)(()=>{if(!s)return;let e=requestAnimationFrame(()=>l.current?.focus());return()=>cancelAnimationFrame(e)},[s]),(0,_.useEffect)(()=>{if(!s)return;let e=e=>{let t=e.target;d.current=t instanceof Element&&!t.closest(`.review-base-picker, .review-base-popup`)?t.closest(`button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select:not(:disabled), a[href], [tabindex], [contenteditable='true']`):null};return document.addEventListener(`pointerdown`,e,!0),()=>document.removeEventListener(`pointerdown`,e,!0)},[s]);let m=e.options.find(e=>e.ref===t)?.label??t;return(0,K.jsx)($M,{className:`review-base-picker`,label:i(`gitReviewBaseBranch`),isLabelHidden:!0,value:t??``,triggerLabel:(0,K.jsx)(`span`,{className:`review-base-label`,title:t,children:m||i(`gitReviewChooseBase`)}),variant:`ghost`,size:`sm`,isDisabled:e.options.length===0,isLoading:n,onOpenChange:e=>{c(e),e||(o(``),d.current?.isConnected&&d.current.focus({preventScroll:!0}),d.current=null)},children:(s,c,d)=>(0,K.jsxs)(`div`,{className:`review-base-popup`,children:[(0,K.jsxs)(`label`,{className:`review-base-search`,children:[(0,K.jsx)(ht,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`sr-only`,children:i(`gitReviewSearchBranches`)}),(0,K.jsx)(`input`,{ref:l,type:`search`,value:a,"aria-controls":f,placeholder:i(`gitReviewSearchBranches`),onChange:e=>o(e.currentTarget.value),onKeyDown:e=>{e.nativeEvent.isComposing||e.keyCode===229||(e.key===`Escape`?(e.preventDefault(),e.stopPropagation(),d()):e.key===`ArrowDown`&&p.length&&!n&&(e.preventDefault(),u.current[0]?.focus()))}})]}),e.truncated&&(0,K.jsx)(`p`,{role:`status`,children:i(`gitReviewBranchesTruncated`)}),(0,K.jsxs)(`div`,{id:f,role:`listbox`,"aria-label":i(`gitReviewBaseBranch`),className:`review-base-options`,children:[p.map((e,a)=>(0,K.jsxs)(`button`,{type:`button`,disabled:n,role:`option`,"aria-selected":t===e.ref,title:e.ref,ref:e=>{u.current[a]=e},onClick:()=>{r(e.ref),d()},onKeyDown:e=>{if(!(e.nativeEvent.isComposing||e.keyCode===229)){if(e.key===`Escape`)e.preventDefault(),e.stopPropagation(),d();else if(e.key===`ArrowDown`||e.key===`ArrowUp`||e.key===`Home`||e.key===`End`){e.preventDefault();let t=e.key===`Home`?0:e.key===`End`?p.length-1:(a+(e.key===`ArrowDown`?1:p.length-1))%p.length;u.current[t]?.focus()}}},children:[(0,K.jsxs)(`span`,{children:[e.label,(0,K.jsx)(`small`,{children:e.ref.startsWith(`refs/heads/`)?i(`gitReviewLocalBranch`):i(`gitReviewRemoteBranch`)})]}),t===e.ref&&(0,K.jsx)(I,{"aria-hidden":`true`})]},e.ref)),!p.length&&(0,K.jsx)(`p`,{role:`status`,children:i(`gitReviewNoMatchingBranches`)})]})]})})}function Tz(e,t){return{path:e,name:t,directories:new Map,files:[]}}function Ez({files:e,selectedPath:t,collapsed:n,searching:r,onToggle:i,onSelect:a,viewed:o,onViewedChange:s,viewedLimitReached:c=!1}){let{t:l}=cr(),u=(0,_.useMemo)(()=>{let t=Tz(``,``);for(let n of e){let e=t;for(let t of n.path.split(`/`).slice(0,-1)){let n=e.path?`${e.path}/${t}`:t,r=e.directories.get(t);r||(r=Tz(n,t),e.directories.set(t,r)),e=r}e.files.push(n)}return t},[e]),d=(e,u)=>(0,K.jsxs)(`ul`,{children:[[...e.directories.values()].map(e=>{let t=e,a=t.name;for(;t.files.length===0&&t.directories.size===1;){let e=t.directories.values().next().value;if(!e)break;t=e,a+=`/${t.name}`}let o=t.path,s=r||!n.has(o);return(0,K.jsxs)(`li`,{children:[(0,K.jsxs)(`button`,{type:`button`,className:`review-tree-directory`,style:{paddingLeft:8+u*16},title:o,"aria-expanded":s,disabled:r,onClick:()=>i(o),children:[(0,K.jsx)(ee,{"aria-hidden":`true`,"data-open":s}),(0,K.jsx)(`span`,{children:a})]}),s&&d(t,u+1)]},e.path)}),e.files.map(e=>{let n=e.path.split(`/`).at(-1)??e.path,r=/\.(png|jpe?g|gif|webp|svg)$/iu.test(n)?Ne:/\.(md|txt|log)$/iu.test(n)?Se:ve;return(0,K.jsxs)(`li`,{className:`review-tree-file-row`,children:[(0,K.jsxs)(`button`,{className:`session-review-file review-tree-file`,type:`button`,style:{paddingLeft:8+u*16},"data-review-file":e.path,title:e.path,"aria-label":e.path,"aria-description":l(`gitFileStatus_${e.status}`),"aria-current":t===e.path?`true`:void 0,onClick:()=>a(e.path),children:[(0,K.jsx)(r,{"aria-hidden":`true`,className:`review-tree-icon`}),(0,K.jsx)(`span`,{className:`review-tree-name`,children:n}),(0,K.jsx)(`span`,{className:`review-tree-status`,"aria-hidden":`true`,children:l(`gitFileStatus_${e.status}`)}),(0,K.jsx)(`span`,{className:`session-review-stats`,"aria-hidden":`true`,children:e.binary?(0,K.jsx)(`span`,{children:l(`gitReviewBinaryShort`)}):e.statsUnavailable?(0,K.jsx)(`span`,{title:l(`turnEditStatsUnknown`),children:`—`}):(0,K.jsxs)(K.Fragment,{children:[e.additions>0&&(0,K.jsxs)(`span`,{className:`review-additions`,children:[`+`,e.additions]}),e.deletions>0&&(0,K.jsxs)(`span`,{className:`review-deletions`,children:[`-`,e.deletions]})]})})]}),s&&(0,K.jsx)(`label`,{className:`review-viewed-control`,title:l(`gitReviewMarkViewed`,{path:e.path}),children:(0,K.jsx)(`input`,{type:`checkbox`,"aria-label":l(`gitReviewMarkViewed`,{path:e.path}),checked:o?.has(e.path)??!1,disabled:c&&!o?.has(e.path),onChange:t=>s(e.path,t.currentTarget.checked)})})]},e.path)})]});return(0,K.jsx)(`div`,{className:`session-review-list review-file-tree`,children:d(u,0)})}var Dz=20,Oz=200,kz=[0,1,2,3];function Az(e){return e.split(/[\\/]/u).at(-1)||e}function jz(e,t){return e?e.reason===`not_git_repository`?t(`gitReviewNotRepository`):e.reason===`unborn_repository`?t(`gitReviewUnborn`):e.reason===`baseline_unavailable`?t(`gitReviewBaselineUnavailable`):e.reason===`base_branch_unavailable`?t(`gitReviewBaseUnavailable`):e.reason===`invalid_base_branch`?t(`gitReviewBaseInvalid`):t(`gitReviewFailed`):null}function Mz({review:e,initialFilePath:t,onClose:n,onOpenTools:r,embedded:i=!1,active:a=!0,onOpenFiles:o,readingScope:s,onReferenceLine:c}){let{t:l}=cr(),u=wk(),d=(0,_.useRef)(void 0);e.result?.branches?d.current=e.result.branches:e.result&&!e.loading&&(d.current=void 0);let f=e.result?.branches??(e.loading?d.current:void 0),p=`${s??e.source??`unstaged`}:${e.baseRef??``}`,m=u?.review?.scope===p?u.review:void 0,h=(0,_.useRef)(JSON.stringify([p,t])),g=(0,_.useRef)(null),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(new Set(m?.collapsedDirectories));(0,_.useEffect)(()=>{let e=g.current;if(!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(([e])=>{e&&y(e.contentRect.width>=720)});return t.observe(e),()=>t.disconnect()},[]);let S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=(0,_.useRef)(null),E=(0,_.useRef)(!0),D=(0,_.useRef)(!1),O=(0,_.useRef)(m?.listScroll??null),k=(0,_.useRef)(null),[A,j]=(0,_.useState)(m?.visibleFiles??Dz),[M,N]=(0,_.useState)(m?.query??``),[P,F]=(0,_.useState)(null),[I,L]=(0,_.useState)(m?m.selected:t??null),[R,ee]=(0,_.useState)(()=>m?.viewed?{scope:p,revision:m.viewed.revision,paths:new Set(m.viewed.paths.slice(0,Oz))}:null),z=(0,_.useRef)(m?{list:m.listScroll,preview:m.previewScroll}:null);(0,_.useLayoutEffect)(()=>{u&&(u.review={source:e.source??`unstaged`,baseRef:e.baseRef,scope:p,selected:I,query:M,collapsedDirectories:[...b],visibleFiles:A,listScroll:u.review?.scope===p?u.review.listScroll:0,previewScroll:u.review?.scope===p?u.review.previewScroll:0,viewed:R?.scope===p?{revision:R.revision,paths:[...R.paths].slice(0,Oz)}:void 0})},[u,e.source,e.baseRef,p,I,M,b,A,R]);let[B,V]=(0,_.useState)(null),[H,te]=(0,_.useState)(null),[ne,re]=(0,_.useState)(0),[ie,ae]=(0,_.useState)(()=>window.matchMedia?.(`(max-width: 1100px)`).matches??!1);(0,_.useEffect)(()=>{let e=window.matchMedia?.(`(max-width: 1100px)`);if(!e)return;let t=()=>ae(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,_.useEffect)(()=>{let e=JSON.stringify([p,t]);h.current!==e&&(h.current=e,E.current=!!t||!(document.activeElement instanceof Element&&document.activeElement.closest(`.review-base-picker, .review-base-popup`)),O.current=null,L(t??null),N(``),x(new Set),F(null),ee(null))},[t,p]);let U=i?`section`:ie?`main`:`aside`,oe=e.result?.ok?e.result.snapshot:null,se=!e.historical&&I&&P&&P.comparison===(e.source??oe?.comparison)?oe?.revision===P.revision?oe:P:oe,ce=!!(I&&se&&oe&&se.revision!==oe.revision);(0,_.useEffect)(()=>{I&&!P&&oe&&F(oe)},[I,P,oe]);let le=e.source??se?.comparison??`unstaged`,ue=jz(e.result&&!e.result.ok?e.result:null,l),de=se?.files.find(e=>e.path===I),fe=B?.source===le&&B?.revision===se?.revision&&B?.file.path===I?B.file:de,pe=se?.revision,me=R?.scope===p&&R.revision===pe?R.paths:new Set;(0,_.useEffect)(()=>{pe&&R&&(R.scope!==p||R.revision!==pe)&&ee(null)},[pe,p,R]);let W=(e,t)=>{!pe||!se?.files.some(t=>t.path===e)||ee(n=>{let r=new Set(n?.scope===p&&n.revision===pe?n.paths:[]);if(t){if(r.size>=Oz)return n;r.add(e)}else r.delete(e);return{scope:p,revision:pe,paths:r}})};(0,_.useLayoutEffect)(()=>{!a||!se||!z.current||I&&fe?.diffLoaded===!1||(C.current&&(C.current.scrollTop=z.current.list),w.current&&(w.current.scrollTop=z.current.preview),z.current=null)},[a,se,I,fe?.diffLoaded]);let he=H?.source===le&&H?.path===I&&H?.revision===pe&&de?.diffLoaded===!1?H.message:null;(0,_.useEffect)(()=>{let t=de?.path;if(!a||!t||de?.diffLoaded!==!1||!e.readFile||!pe)return;let n=new AbortController;return te(null),e.readFile(t,n.signal,pe).then(e=>{n.signal.aborted||(e?V({source:le,revision:pe,file:e}):te({source:le,path:t,revision:pe,message:l(`gitReviewFileMissing`)}))},e=>{n.signal.aborted||te({source:le,path:t,revision:pe,message:e instanceof Error?e.message:l(`gitReviewFailed`)})}),()=>n.abort()},[de?.path,a,de?.diffLoaded,pe,le,e.readFile,ne,l]);let ge=(0,_.useMemo)(()=>(se?.files??[]).filter(e=>e.path.toLocaleLowerCase().includes(M.toLocaleLowerCase())).sort((e,t)=>e.path.localeCompare(t.path,`en`,{numeric:!0})),[se?.files,M]),_e=v?ge:ge.slice(0,A);(0,_.useEffect)(()=>{!v||I||!se?.files.length||(E.current=!1,L(se.files[0].path))},[v,I,se]);let be=Math.max(0,ge.length-_e.length),xe=se?.listComplete===!1||se?.listComplete===void 0&&se?.truncated,Se=xe||se?.nextOffset!==void 0,Ce=e.historical?l(se?.evidenceSource===`file-tools`?`turnEditsScope`:`turnChangesScope`):se?se.comparison===`session`?l(`gitReviewSessionSnapshot`):se.comparison===`unstaged`?l(`gitReviewUnstaged`):se.comparison===`staged`?l(`gitReviewStaged`):se.baseBranch?l(`gitReviewComparison`,{current:se.currentBranch??l(`gitReviewDetached`),base:se.baseBranch.replace(/^refs\/(?:heads|remotes)\//u,``)}):l(`gitReviewWorkingTree`):null;(0,_.useEffect)(()=>{let e=a&&!D.current;D.current=a,a&&(!e&&!E.current||(E.current=!1,I?w.current?.focus():i?C.current?.focus():S.current?.focus()))},[a,i,I]);let we=e=>{O.current=C.current?.scrollTop??null,e!==I&&(z.current={list:O.current??0,preview:0},w.current&&(w.current.scrollTop=0),u?.review?.scope===p&&(u.review.previewScroll=0)),E.current=!v,F(se),L(e)};(0,_.useLayoutEffect)(()=>{let e=k.current;if(I||!e||!a)return;k.current=null;let t=C.current;if(!t?.isConnected||t.closest(`[hidden], [inert]`))return;let n=[...t.querySelectorAll(`[data-review-file]`)].find(t=>t.dataset.reviewFile===e);O.current!==null&&(t.scrollTop=O.current),n?n.focus({preventScroll:O.current!==null}):i?t.focus():S.current?.focus()},[a,i,I]);let Te=()=>{let e=I,t=ge.findIndex(t=>t.path===e);t>=A&&j(Math.ceil((t+1)/Dz)*Dz),E.current=!1,k.current=e,L(null),F(null)};return(0,K.jsxs)(U,{ref:g,className:`review-panel${i?` embedded`:``}${v?` review-wide`:``}`,"aria-label":l(`changeEvidence`),"aria-busy":e.loading||void 0,onKeyDown:e=>{e.key!==`Escape`||e.nativeEvent.isComposing||e.keyCode===229||e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.defaultPrevented||(!I||v)&&i||(e.preventDefault(),e.stopPropagation(),I&&!v?Te():i||n())},children:[(0,K.jsxs)(`div`,{className:`review-source-picker`,children:[e.setSource&&(0,K.jsxs)(`label`,{children:[l(`gitReviewSource`),` `,(0,K.jsxs)(`select`,{value:e.historical?`turn`:e.source??`unstaged`,onChange:t=>e.setSource?.(t.currentTarget.value),children:[e.historical&&(0,K.jsx)(`option`,{value:`turn`,children:l(`turnChangesReview`)}),(0,K.jsx)(`option`,{value:`unstaged`,children:l(`gitReviewUnstaged`)}),(0,K.jsx)(`option`,{value:`staged`,children:l(`gitReviewStaged`)}),(0,K.jsx)(`option`,{value:`branch`,children:l(`gitReviewBranch`)}),(0,K.jsx)(`option`,{value:`session`,children:l(`gitReviewSessionSnapshot`)})]})]}),e.source===`branch`&&e.setBaseRef&&f&&(0,K.jsx)(wz,{branches:f,value:e.baseRef??(e.result?.ok?e.result.snapshot.baseBranch??void 0:void 0),loading:e.loading,onChange:e.setBaseRef}),Ce&&(!e.setSource||e.historical||se?.comparison===`branch`)&&(0,K.jsx)(`span`,{className:`review-source-summary`,title:Ce,children:Ce}),(0,K.jsxs)(`div`,{className:`review-source-actions`,children:[o&&(0,K.jsx)(`button`,{type:`button`,onClick:o,children:l(`sessionFileRecords`)}),(0,K.jsx)(`button`,{type:`button`,className:`icon-button`,"aria-label":l(`gitReviewRefresh`),title:l(`gitReviewRefresh`),disabled:e.loading,"aria-busy":e.loading||void 0,onClick:()=>{e.loading||e.refresh()},children:(0,K.jsx)(dt,{"aria-hidden":`true`})})]})]}),ce&&(0,K.jsxs)(`div`,{className:`review-update`,role:`status`,children:[(0,K.jsx)(`span`,{children:l(`gitReviewNewVersion`)}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{w.current?.focus(),F(oe),V(null)},children:l(`gitReviewShowLatest`)})]}),(e.error||ue)&&(0,K.jsx)(mz,{status:`error`,container:`section`,title:e.error||ue,description:se?l(`gitReviewOlderResult`):void 0,className:`review-banner`,endContent:(0,K.jsx)(qc,{variant:`ghost`,size:`sm`,label:l(`gitReviewRetry`),isDisabled:e.loading,isLoading:e.loading,onClick:()=>{e.loading||e.refresh()}})}),(0,K.jsxs)(`div`,{className:`review-workspace`,children:[I&&(0,K.jsxs)(`div`,{className:`review-file-screen`,children:[(0,K.jsxs)(`header`,{className:`review-file-header`,children:[!v&&(0,K.jsx)(qc,{label:l(`gitReviewBackToFiles`),variant:`ghost`,size:`sm`,isIconOnly:!0,icon:(0,K.jsx)(T,{"aria-hidden":`true`}),onClick:Te}),(0,K.jsxs)(`div`,{className:`review-file-heading`,children:[(0,K.jsx)(`strong`,{title:I,children:Az(I)}),(0,K.jsx)(`span`,{title:I,children:I})]}),fe&&pe&&(0,K.jsxs)(`label`,{className:`review-file-viewed`,children:[(0,K.jsx)(`input`,{type:`checkbox`,"aria-label":l(`gitReviewMarkCurrentViewed`,{path:I}),checked:me.has(I),disabled:me.size>=Oz&&!me.has(I),onChange:e=>W(I,e.currentTarget.checked)}),(0,K.jsx)(`span`,{children:l(`gitReviewViewedLabel`)})]}),!i&&(0,K.jsxs)(`div`,{className:`review-file-actions`,children:[r&&(0,K.jsx)(qc,{label:l(`openTools`),variant:`ghost`,size:`sm`,isIconOnly:!0,icon:(0,K.jsx)(lt,{"aria-hidden":`true`}),onClick:r}),(0,K.jsx)(qc,{label:l(`close`),variant:`ghost`,size:`sm`,isIconOnly:!0,icon:(0,K.jsx)(Lt,{"aria-hidden":`true`}),onClick:n})]})]}),(0,K.jsxs)(`div`,{className:`review-file-toolbar`,children:[(0,K.jsx)(`div`,{className:`review-file-context`,children:fe&&(0,K.jsx)(`span`,{children:l(`gitFileStatus_${fe.status}`)})}),(0,K.jsxs)(RP,{gap:2,align:`center`,className:`session-review-stats`,children:[fe&&!fe.binary&&!fe.statsUnavailable&&fe.additions>0&&(0,K.jsxs)(zo,{type:`supporting`,hasTabularNumbers:!0,className:`review-additions`,children:[`+`,fe.additions]}),fe&&!fe.binary&&!fe.statsUnavailable&&fe.deletions>0&&(0,K.jsxs)(zo,{type:`supporting`,hasTabularNumbers:!0,className:`review-deletions`,children:[`-`,fe.deletions]})]})]}),(0,K.jsx)(`section`,{ref:w,className:`review-file-preview`,"aria-label":l(`gitReviewFilePreview`,{file:I}),tabIndex:-1,onScroll:e=>{u?.review&&(u.review.previewScroll=e.currentTarget.scrollTop)},children:fe?he?(0,K.jsxs)(`div`,{role:`alert`,children:[(0,K.jsx)(`p`,{children:he}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>re(e=>e+1),children:l(`retryAdmissionCheck`)})]}):fe.diffLoaded===!1&&e.readFile?(0,K.jsx)(`p`,{role:`status`,children:l(`gitReviewLoading`)}):fe.binary?(0,K.jsx)(gz,{icon:(0,K.jsx)(ve,{"aria-hidden":`true`}),title:l(`gitReviewBinary`),isCompact:!0}):fe.statsUnavailable?(0,K.jsx)(gz,{icon:(0,K.jsx)(ve,{"aria-hidden":`true`}),title:l(`turnEditStatsUnknown`),description:l(`turnEditReason_${fe.statsUnavailable}`),isCompact:!0}):fe.diff?(0,K.jsxs)(K.Fragment,{children:[fe.diffTruncated&&(0,K.jsx)(`p`,{className:`review-hidden-lines`,children:l(`gitReviewDiffTruncated`)}),(0,K.jsx)(VL,{file:fe,onReferenceLine:c})]}):(0,K.jsx)(gz,{icon:(0,K.jsx)(ve,{"aria-hidden":`true`}),title:l(fe.diffTruncated?`gitReviewDiffTruncated`:`gitReviewNoDiff`),description:fe.diffTruncated?l(`gitReviewDiffTruncated`):void 0,isCompact:!0}):(0,K.jsx)(`p`,{role:`status`,children:l(e.loading?`gitReviewLoading`:`gitReviewFileMissing`)})})]}),(!I||v)&&(0,K.jsxs)(`div`,{className:`review-navigation`,children:[!i&&!v&&(0,K.jsxs)(`header`,{className:`review-heading`,children:[(0,K.jsx)(`div`,{children:(0,K.jsxs)(`h2`,{children:[(0,K.jsx)(ye,{"aria-hidden":`true`}),` `,l(`changeEvidence`)]})}),(0,K.jsxs)(`div`,{className:`review-heading-actions`,children:[r&&(0,K.jsx)(`button`,{type:`button`,className:`icon-button`,"aria-label":l(`openTools`),title:l(`openTools`),onClick:r,children:(0,K.jsx)(lt,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{ref:S,type:`button`,className:`icon-button review-close`,"aria-label":l(`close`),title:l(`close`),onClick:n,children:(0,K.jsx)(Lt,{"aria-hidden":`true`})})]})]}),(0,K.jsxs)(`div`,{ref:C,onScroll:e=>{u?.review&&(u.review.listScroll=e.currentTarget.scrollTop)},className:`review-body`,tabIndex:i?-1:void 0,children:[se&&(0,K.jsxs)(zP,{gap:1,align:`stretch`,className:`review-summary`,children:[(0,K.jsxs)(RP,{gap:3,align:`center`,justify:`between`,children:[(0,K.jsx)(zo,{type:`label`,children:l(xe?`gitReviewLoadedCount`:`filesChanged`,{count:xe?se.files.length:se.totalFiles??se.files.length})}),se.nextOffset!==void 0&&!xe&&(0,K.jsx)(zo,{type:`supporting`,color:`secondary`,children:l(`gitReviewLoadedCount`,{count:se.files.length})}),!xe&&!se.truncated&&se.nextOffset===void 0&&(se.additions>0||se.deletions>0)&&!se.files.some(e=>e.binary||e.statsUnavailable||e.status===`untracked`&&e.diffLoaded===!1)&&(0,K.jsxs)(RP,{gap:2,align:`center`,className:`review-summary-counts`,"aria-hidden":`true`,children:[se.additions>0&&(0,K.jsxs)(zo,{type:`supporting`,hasTabularNumbers:!0,className:`review-additions`,children:[`+`,se.additions]}),se.deletions>0&&(0,K.jsxs)(zo,{type:`supporting`,hasTabularNumbers:!0,className:`review-deletions`,children:[`-`,se.deletions]})]})]}),me.size>=Oz&&(0,K.jsx)(zo,{type:`supporting`,color:`secondary`,children:l(`gitReviewViewedLimit`,{count:Oz})})]}),e.loading&&!se&&(0,K.jsxs)(`div`,{className:`review-loading`,role:`status`,children:[(0,K.jsx)(`span`,{className:`sr-only`,children:l(`gitReviewLoading`)}),(0,K.jsxs)(zP,{gap:2,align:`stretch`,"aria-hidden":`true`,children:[(0,K.jsx)(Cz,{width:`42%`,height:16,radius:`rounded`,index:0}),(0,K.jsx)(`div`,{className:`review-loading-list`,children:kz.map(e=>(0,K.jsx)(Cz,{width:`100%`,height:36,radius:0,index:e+1},e))})]})]}),se?.truncated&&(0,K.jsx)(mz,{status:`info`,title:l(`gitReviewTruncated`),className:`review-banner`}),se&&se.files.length>0&&(0,K.jsxs)(`label`,{className:`review-search`,children:[(0,K.jsx)(ht,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`sr-only`,children:l(Se?`gitReviewSearchLoaded`:`gitReviewSearch`)}),(0,K.jsx)(`input`,{type:`search`,value:M,placeholder:l(Se?`gitReviewSearchLoaded`:`gitReviewSearch`),onChange:e=>{N(e.target.value),j(Dz)}})]}),M&&ge.length===0&&(0,K.jsx)(`p`,{className:`review-search-empty`,role:`status`,children:l(Se?`gitReviewNoLoadedMatch`:`gitReviewNoMatch`)}),se&&se.files.length===0&&(0,K.jsx)(gz,{icon:(0,K.jsx)(Ae,{"aria-hidden":`true`}),title:l(`gitReviewEmpty`),isCompact:!0,className:`review-empty`}),_e.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Ez,{files:_e,selectedPath:I,collapsed:b,searching:!!M,onToggle:e=>x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),onSelect:we,viewed:me,onViewedChange:W,viewedLimitReached:me.size>=Oz}),be>0&&(0,K.jsx)(`div`,{className:`session-review-more`,children:(0,K.jsx)(qc,{variant:`ghost`,size:`sm`,width:`100%`,label:l(`gitReviewShowMore`,{count:Math.min(Dz,be)}),onClick:()=>j(e=>Math.min(e+Dz,ge.length))})})]}),se?.nextOffset!==void 0&&e.loadMore&&(0,K.jsx)(`div`,{className:`session-review-more`,children:(0,K.jsx)(qc,{variant:`ghost`,size:`sm`,width:`100%`,label:l(`gitReviewLoadNext`),isLoading:e.loading,isDisabled:e.loading,onClick:()=>{e.loadMore?.()}})})]})]})]})]})}function Nz(e,t,n,r){let{t:i}=cr(),a=(0,_.useMemo)(()=>new rf,[]),[o,s]=(0,_.useState)(0),[c,l]=(0,_.useState)({identity:``,result:null,error:null}),u=JSON.stringify([e,t,r,o]);(0,_.useEffect)(()=>{if(!r)return;let o=new AbortController;return a.turnChanges(e,t,r,o.signal).then(t=>{if(o.signal.aborted)return;if(!t.ok||t.changes.sessionId!==e||t.changes.promptEntryId!==r||t.changes.state===`unavailable`){l({identity:u,result:null,error:i(`turnChangesUnavailable`)});return}let a=t.changes;l({identity:u,error:null,result:{ok:!0,snapshot:{...a.source?{evidenceSource:a.source}:{},...a.fileCount===null?{}:{totalFiles:a.fileCount,listComplete:!0},repositoryRoot:n,currentBranch:null,baseBranch:null,comparison:`session`,revision:u,files:a.files,additions:a.additions,deletions:a.deletions,truncated:a.state===`partial`}}})},()=>{o.signal.aborted||l({identity:u,result:null,error:i(`turnChangesUnavailable`)})}),()=>o.abort()},[a,e,t,r,u,n,i]);let d=(0,_.useCallback)(async()=>s(e=>e+1),[]);return{result:c.identity===u?c.result:null,error:c.identity===u?c.error:null,loading:!!r&&c.identity!==u,refresh:d,historical:!0}}function Pz(e,t,n){let r=(0,_.useRef)({onState:t,onOpen:n});r.current={onState:t,onOpen:n};let[i,a]=(0,_.useState)(),[o,s]=(0,_.useState)(!1);return(0,_.useEffect)(()=>{let t=()=>{let e=document.documentElement.dataset.openpiBrowserExtension===`ready`;s(e),e||a(void 0)};t();let n=new MutationObserver(t);n.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-openpi-browser-extension`]});let i=t=>{if(t.source!==window||t.origin!==location.origin)return;let n=t.data;if(!n||n.source!==`openpi-browser-extension`||n.id!==e)return;if(n.type===`lost`){a(void 0);return}if(typeof n.url!=`string`)return;let i=YR(n.url,location.origin);if(i&&(n.type===`open`&&r.current.onOpen(i),n.type===`state`&&typeof n.title==`string`)){let t={id:e,document:typeof n.document==`string`?n.document:void 0,url:i,title:n.title.slice(0,256),canGoBack:n.canGoBack===!0,canGoForward:n.canGoForward===!0};a(t),r.current.onState(t)}};return window.addEventListener(`message`,i),()=>{n.disconnect(),window.removeEventListener(`message`,i)}},[e]),{ready:o,page:o&&i?.id===e?i:void 0,command:t=>window.postMessage({source:`openpi-browser-ui`,type:`command`,id:e,action:t},location.origin)}}var Fz=8;function Iz({onTitle:e,onOpen:t,initialUrl:n=``,readingId:r}){let{t:i}=cr(),a=(0,_.useId)(),o=(0,_.useRef)(null),s=wk(),c=s?.browser?.pages[r],[l,u]=(0,_.useState)(c?.draft??n),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)({history:c?.history??(n?[n]:[]),index:c?.index??(n?0:-1),revision:0,loaded:!1,unknown:!1}),h=p.history[p.index],g=(0,_.useRef)(h);(0,_.useLayoutEffect)(()=>{s?.browser&&(s.browser.pages[r]={draft:l,history:p.history.map((e,t)=>t===p.index?g.current??e:e),index:p.index})},[s,r,l,p]);let v=`${a}-${p.revision}`,y=Pz(v,t=>{g.current=t.url;let n=s?.browser?.pages[r];n&&(n.history=n.history.map((e,r)=>r===n.index?t.url:e)),document.activeElement!==o.current&&u(t.url),e(t.title||new URL(t.url).host)},t),b=y.page?.url??h,x=(t,n)=>{let r=t[n];r&&(g.current=r,m(e=>({history:t,index:n,revision:e.revision+1,loaded:!1,unknown:!1})),u(r),f(null),e(new URL(r).host))};return(0,K.jsxs)(`div`,{className:`browser-tool browser-direct-tool`,children:[(0,K.jsxs)(`form`,{className:`browser-toolbar`,onSubmit:e=>{e.preventDefault();let t=YR(l,window.location.origin);if(!t){f(i(`browserAddressNotAllowed`));return}if(t===h)x(p.history,p.index);else{let e=[...p.history.slice(0,p.index+1),t].slice(-64);x(e,e.length-1)}},children:[(0,K.jsxs)(`div`,{className:`browser-navigation`,children:[(0,K.jsx)(`button`,{type:`button`,"aria-label":i(`browserBack`),title:i(`browserBack`),disabled:y.page?!y.page.canGoBack:p.unknown||p.index<=0,onClick:()=>y.page?y.command(`back`):x(p.history,p.index-1),children:(0,K.jsx)(T,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{type:`button`,"aria-label":i(`browserForward`),title:i(`browserForward`),disabled:y.page?!y.page.canGoForward:p.unknown||p.index>=p.history.length-1,onClick:()=>y.page?y.command(`forward`):x(p.history,p.index+1),children:(0,K.jsx)(E,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{type:`button`,"aria-label":i(`browserReload`),title:i(`browserReload`),disabled:!h,onClick:()=>y.page?y.command(`reload`):x(p.history,p.index),children:(0,K.jsx)(dt,{"aria-hidden":`true`})})]}),(0,K.jsx)(`input`,{ref:o,"aria-label":i(`browserAddress`),title:i(y.page?`browserAddress`:`browserEnteredAddress`),value:l,placeholder:`https://`,spellCheck:!1,onChange:e=>{u(e.currentTarget.value),f(null)}}),(0,K.jsx)(`button`,{type:`submit`,"aria-label":i(`browserGo`),title:i(`browserGo`),disabled:!l.trim(),children:(0,K.jsx)(E,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{type:`button`,"aria-label":i(`openExternalBrowser`),title:i(`openExternalBrowser`),disabled:!b||!y.page&&p.unknown,onClick:()=>b&&window.open(b,`_blank`,`noopener,noreferrer`),children:(0,K.jsx)(he,{"aria-hidden":`true`})})]}),(0,K.jsxs)(`div`,{className:`browser-feedback`,children:[d&&(0,K.jsx)(`p`,{className:`workbar-error`,role:`alert`,children:d}),p.unknown&&!y.page&&(0,K.jsx)(`p`,{className:`browser-notice`,role:`status`,children:i(`browserLocationUnknown`)})]}),(0,K.jsx)(`div`,{className:`browser-direct-viewport`,children:h?(0,K.jsx)(`iframe`,{"data-openpi-browser-page":v,"data-openpi-browser-document":y.page?.document,"data-openpi-browser-url":y.page?.url,"data-openpi-browser-title":y.page?.title,src:h,title:i(`browserPageTitle`,{address:new URL(h).host}),referrerPolicy:`no-referrer`,sandbox:`allow-scripts allow-forms allow-same-origin allow-popups allow-popups-to-escape-sandbox`,onLoad:()=>m(e=>e.revision===p.revision?{...e,loaded:!0,unknown:e.loaded}:e)},p.revision):(0,K.jsxs)(`div`,{className:`workbar-empty`,children:[(0,K.jsx)(me,{"aria-hidden":`true`}),(0,K.jsx)(`strong`,{children:i(`browserReady`)}),(0,K.jsx)(`p`,{children:i(`browserDirectDescription`)})]})}),(0,K.jsx)(`p`,{className:`browser-notice`,children:i(y.ready?`browserEnhancedHint`:`browserDirectHint`)})]})}function Lz({onReady:e}={}){let{t}=cr(),n=(0,_.useId)(),r=wk(),[i,a]=(0,_.useState)(r?.browser?.tabs??[{id:0,title:``}]),o=(0,_.useRef)(Math.max(...i.map(e=>e.id))+1),s=(0,_.useRef)(i);s.current=i;let[c,l]=(0,_.useState)(),[u,d]=(0,_.useState)(r?.browser?.selected??0);(0,_.useLayoutEffect)(()=>{r&&(r.browser={tabs:i,selected:u,pages:r.browser?.pages??{}})},[r,i,u]);let f=e=>{requestAnimationFrame(()=>document.getElementById(`${n}-tab-${e}`)?.focus())},p=(e=``)=>{if(s.current.length>=Fz){e&&l(e);return}let t={id:o.current++,title:e?new URL(e).host:``,initialUrl:e},r=[...s.current,t];return s.current=r,a(r),d(t.id),l(void 0),f(t.id),`${n}-page-${t.id}`},m=(0,_.useRef)(p);m.current=p,(0,_.useEffect)(()=>(e?.(e=>m.current(e)),()=>e?.(void 0)),[e]);let h=e=>{r?.browser&&delete r.browser.pages[e],l(void 0);let t=i.filter(t=>t.id!==e);if(!t.length){let e={id:o.current++,title:``};a([e]),d(e.id),f(e.id)}else if(a(t),u===e){let n=i.findIndex(t=>t.id===e),r=t[Math.min(n,t.length-1)];d(r.id),f(r.id)}};return(0,K.jsxs)(`div`,{className:`browser-workspace`,children:[(0,K.jsxs)(`div`,{className:`browser-tabs-header`,children:[(0,K.jsx)(`div`,{role:`tablist`,"aria-label":t(`browserTabs`),className:`browser-tabs`,onKeyDown:e=>{if(!(e.target instanceof HTMLElement)||e.target.getAttribute(`role`)!==`tab`)return;let t=e.target.id,r=i.findIndex(e=>`${n}-tab-${e.id}`===t),a=r;if(e.key===`ArrowRight`)a=(r+1)%i.length;else if(e.key===`ArrowLeft`)a=(r+i.length-1)%i.length;else if(e.key===`Home`)a=0;else if(e.key===`End`)a=i.length-1;else if(e.key===`Delete`){e.preventDefault(),e.stopPropagation(),h(i[r].id);return}else return;e.preventDefault(),e.stopPropagation(),d(i[a].id),f(i[a].id)},children:i.map(e=>(0,K.jsxs)(`div`,{className:`browser-tab`,"data-active":e.id===u,children:[(0,K.jsxs)(`button`,{type:`button`,role:`tab`,id:`${n}-tab-${e.id}`,"aria-selected":e.id===u,"aria-controls":`${n}-page-${e.id}`,tabIndex:e.id===u?0:-1,onClick:()=>d(e.id),children:[(0,K.jsx)(me,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:e.title||t(`browserNewTab`)})]}),(0,K.jsx)(`button`,{type:`button`,"aria-label":t(`browserCloseTab`,{title:e.title||t(`browserNewTab`)}),title:t(`close`),onClick:()=>h(e.id),children:(0,K.jsx)(Lt,{"aria-hidden":`true`})})]},e.id))}),(0,K.jsx)(`button`,{type:`button`,className:`browser-add-tab`,"aria-label":t(`browserAddTab`),title:i.length>=Fz?t(`browserTabLimit`,{count:Fz}):t(`browserAddTab`),disabled:i.length>=Fz,onClick:()=>p(),children:(0,K.jsx)(lt,{"aria-hidden":`true`})})]}),c&&(0,K.jsxs)(`p`,{className:`browser-notice`,role:`status`,children:[t(`browserTabLimit`,{count:Fz}),` ·`,` `,(0,K.jsx)(`a`,{href:c,target:`_blank`,rel:`noopener noreferrer`,children:t(`openExternalBrowser`)})]}),(0,K.jsx)(`div`,{className:`browser-pages`,children:i.map(e=>(0,K.jsx)(`div`,{role:`tabpanel`,id:`${n}-page-${e.id}`,"aria-labelledby":`${n}-tab-${e.id}`,className:`browser-page`,hidden:u!==e.id,children:(0,K.jsx)(Iz,{readingId:e.id,initialUrl:e.initialUrl,onOpen:p,onTitle:t=>a(n=>n.map(n=>n.id===e.id?{...n,title:t}:n))})},e.id))})]})}var Rz=2,zz=1,Bz=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(Rz,Math.floor(u/e.css.cell.width)),rows:Math.max(zz,Math.floor(l/e.css.cell.height))}}},Vz=Object.defineProperty,Hz=Object.getOwnPropertyDescriptor,Uz=(e,t)=>{for(var n in t)Vz(e,n,{get:t[n],enumerable:!0})},Wz=(e,t,n,r)=>{for(var i=r>1?void 0:r?Hz(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&Vz(t,n,i),i},Gz=(e,t)=>(n,r)=>t(n,r,e),Kz=`Terminal input`,qz={get:()=>Kz,set:e=>Kz=e},Jz=`Too much output to announce, navigate to rows manually to read`,Yz={get:()=>Jz,set:e=>Jz=e};function Xz(e){return e.replace(/\r?\n/g,`\r`)}function Zz(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function Qz(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function $z(e,t,n,r){e.stopPropagation(),e.clipboardData&&eB(e.clipboardData.getData(`text/plain`),t,n,r)}function eB(e,t,n,r){e=Xz(e),e=Zz(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function tB(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function nB(e,t,n,r,i){tB(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function rB(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function iB(e,t=0,n=e.length){let r=``;for(let i=t;i65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var aB=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o);continue}i!==65279&&(t[r++]=i)}return r}},oB=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(c=(i&31)<<6|a&63,c<128){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},sB=``,cB=` `,lB=class e{constructor(){this.fg=0,this.bg=0,this.extended=new uB}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},uB=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},dB=class e extends lB{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new uB,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?rB(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},fB=`di$target`,pB=`di$dependencies`,mB=new Map;function hB(e){return e[pB]||[]}function gB(e){if(mB.has(e))return mB.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);_B(t,e,r)};return t._id=e,mB.set(e,t),t}function _B(e,t,n){t[fB]===t?t[pB].push({id:e,index:n}):(t[pB]=[{id:e,index:n}],t[fB]=t)}var vB=gB(`BufferService`),yB=gB(`CoreMouseService`),bB=gB(`CoreService`),xB=gB(`CharsetService`),SB=gB(`InstantiationService`),CB=gB(`LogService`),wB=gB(`OptionsService`),TB=gB(`OscLinkService`),EB=gB(`UnicodeService`),DB=gB(`DecorationService`),OB=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new dB,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;ti?i.activate(e,t,a):kB(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};OB=Wz([Gz(0,vB),Gz(1,wB),Gz(2,TB)],OB);function kB(e,t){if(confirm(`Do you want to navigate to ${t}? -WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var TB=dB(`CharSizeService`),EB=dB(`CoreBrowserService`),DB=dB(`MouseService`),OB=dB(`RenderService`),kB=dB(`SelectionService`),AB=dB(`CharacterJoinerService`),jB=dB(`ThemeService`),MB=dB(`LinkProviderService`),NB=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?zB.isErrorNoTelemetry(e)?new zB(e.message+` +WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var AB=gB(`CharSizeService`),jB=gB(`CoreBrowserService`),MB=gB(`MouseService`),NB=gB(`RenderService`),PB=gB(`SelectionService`),FB=gB(`CharacterJoinerService`),IB=gB(`ThemeService`),LB=gB(`LinkProviderService`),RB=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?WB.isErrorNoTelemetry(e)?new WB(e.message+` `+e.stack):Error(e.message+` -`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function PB(e){IB(e)||NB.onUnexpectedError(e)}var FB=`Canceled`;function IB(e){return e instanceof LB||e instanceof Error&&e.name===FB&&e.message===FB}var LB=class extends Error{constructor(){super(FB),this.name=this.message}};function RB(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var zB=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},BB=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function VB(e,t=0){return e[e.length-(1+t)]}var HB;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(HB||={});var UB=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||HB.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};UB.empty=new UB(e=>{});function WB(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var GB;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function QB(...e){return $B(()=>ZB(e))}function $B(e){let t=qB({dispose:WB(()=>{JB(t),e()})});return t}var eV=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,qB(this)}dispose(){this._isDisposed||(JB(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{ZB(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return YB(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),YB(e,null))}};eV.DISABLE_DISPOSED_WARNING=!1;var tV=eV,nV=class{constructor(){this._store=new tV,qB(this),YB(this._store,this)}dispose(){JB(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};nV.None=Object.freeze({dispose(){}});var rV=class{constructor(){this._isDisposed=!1,qB(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&YB(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,JB(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&YB(e,null),e}},iV=typeof window==`object`?window:globalThis,aV=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};aV.Undefined=new aV(void 0);var oV=aV,sV=class{constructor(){this._first=oV.Undefined,this._last=oV.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===oV.Undefined}clear(){let e=this._first;for(;e!==oV.Undefined;){let t=e.next;e.prev=oV.Undefined,e.next=oV.Undefined,e=t}this._first=oV.Undefined,this._last=oV.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new oV(e);if(this._first===oV.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==oV.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==oV.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==oV.Undefined&&e.next!==oV.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===oV.Undefined&&e.next===oV.Undefined?(this._first=oV.Undefined,this._last=oV.Undefined):e.next===oV.Undefined?(this._last=this._last.prev,this._last.next=oV.Undefined):e.prev===oV.Undefined&&(this._first=this._first.next,this._first.prev=oV.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==oV.Undefined;)yield e.element,e=e.next}},cV=globalThis.performance&&typeof globalThis.performance.now==`function`,lV=class e{static create(t){return new e(t)}constructor(e){this._now=cV&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},uV;(e=>{e.None=()=>nV.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(QB(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new CV({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new CV({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new CV({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new CV({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new CV({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new CV;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new CV(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function E(e,t){return new T(e,t).emitter.event}e.fromObservable=E;function D(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof tV?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=D})(uV||={});var dV=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new lV,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};dV.all=new Set,dV._idPool=0;var fV=dV,pV=-1,mV=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function zB(e){VB(e)||RB.onUnexpectedError(e)}var BB=`Canceled`;function VB(e){return e instanceof HB||e instanceof Error&&e.name===BB&&e.message===BB}var HB=class extends Error{constructor(){super(BB),this.name=this.message}};function UB(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var WB=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},GB=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function KB(e,t=0){return e[e.length-(1+t)]}var qB;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(qB||={});var JB=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||qB.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};JB.empty=new JB(e=>{});function YB(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var XB;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function rV(...e){return iV(()=>nV(e))}function iV(e){let t=QB({dispose:YB(()=>{$B(t),e()})});return t}var aV=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,QB(this)}dispose(){this._isDisposed||($B(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{nV(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return eV(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),eV(e,null))}};aV.DISABLE_DISPOSED_WARNING=!1;var oV=aV,sV=class{constructor(){this._store=new oV,QB(this),eV(this._store,this)}dispose(){$B(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};sV.None=Object.freeze({dispose(){}});var cV=class{constructor(){this._isDisposed=!1,QB(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&eV(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,$B(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&eV(e,null),e}},lV=typeof window==`object`?window:globalThis,uV=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};uV.Undefined=new uV(void 0);var dV=uV,fV=class{constructor(){this._first=dV.Undefined,this._last=dV.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===dV.Undefined}clear(){let e=this._first;for(;e!==dV.Undefined;){let t=e.next;e.prev=dV.Undefined,e.next=dV.Undefined,e=t}this._first=dV.Undefined,this._last=dV.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new dV(e);if(this._first===dV.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==dV.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==dV.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==dV.Undefined&&e.next!==dV.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===dV.Undefined&&e.next===dV.Undefined?(this._first=dV.Undefined,this._last=dV.Undefined):e.next===dV.Undefined?(this._last=this._last.prev,this._last.next=dV.Undefined):e.prev===dV.Undefined&&(this._first=this._first.next,this._first.prev=dV.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==dV.Undefined;)yield e.element,e=e.next}},pV=globalThis.performance&&typeof globalThis.performance.now==`function`,mV=class e{static create(t){return new e(t)}constructor(e){this._now=pV&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},hV;(e=>{e.None=()=>sV.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(rV(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new OV({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new OV({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new OV({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new OV({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new OV({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new OV;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new OV(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function E(e,t){return new T(e,t).emitter.event}e.fromObservable=E;function D(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof oV?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=D})(hV||={});var gV=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new mV,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};gV.all=new Set,gV._idPool=0;var _V=gV,vV=-1,yV=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t0||this._options?.leakWarningThreshold?new hV(e?.onListenerError??PB,this._options?.leakWarningThreshold??pV):void 0,this._perfMon=this._options?._profName?new fV(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new vV(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||PB)(n),nV.None}if(this._disposed)return nV.None;t&&(e=e.bind(t));let r=new bV(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=gV.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof bV?(this._deliveryQueue??=new wV,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=$B(()=>{SV?.unregister(a),i?.(),this._removeListener(r)});if(n instanceof tV?n.add(a):Array.isArray(n)&&n.push(a),SV){let e=Error().stack.split(` +`))}},SV=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},CV=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},wV=0,TV=class{constructor(e){this.value=e,this.id=wV++}},EV=2,DV,OV=class{constructor(e){this._size=0,this._options=e,this._leakageMon=vV>0||this._options?.leakWarningThreshold?new bV(e?.onListenerError??zB,this._options?.leakWarningThreshold??vV):void 0,this._perfMon=this._options?._profName?new _V(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new CV(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||zB)(n),sV.None}if(this._disposed)return sV.None;t&&(e=e.bind(t));let r=new TV(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=xV.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof TV?(this._deliveryQueue??=new kV,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=iV(()=>{DV?.unregister(a),i?.(),this._removeListener(r)});if(n instanceof oV?n.add(a):Array.isArray(n)&&n.push(a),DV){let e=Error().stack.split(` `).slice(2,3).join(` -`).trim(),t=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(e);SV.register(a,t?.[2]??e,a)}return a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*xV<=t.length){let e=0;for(let n=0;n0}},wV=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},TV=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new CV,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new CV,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};TV.INSTANCE=new TV;var EV=TV;function DV(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}EV.INSTANCE.onDidChangeZoomLevel;function OV(e){return EV.INSTANCE.getZoomFactor(e)}EV.INSTANCE.onDidChangeFullscreen;var kV=typeof navigator==`object`?navigator.userAgent:``,AV=kV.indexOf(`Firefox`)>=0,jV=kV.indexOf(`AppleWebKit`)>=0,MV=kV.indexOf(`Chrome`)>=0,NV=!MV&&kV.indexOf(`Safari`)>=0;kV.indexOf(`Electron/`),kV.indexOf(`Android`);var PV=!1;if(typeof iV.matchMedia==`function`){let e=iV.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=iV.matchMedia(`(display-mode: fullscreen)`);PV=e.matches,DV(iV,e,({matches:e})=>{PV&&t.matches||(PV=e)})}function FV(){return PV}var IV=`en`,LV=!1,RV=!1,zV=!1,BV=!1,VV=!1,HV=IV,UV,WV=globalThis,GV;typeof WV.vscode<`u`&&typeof WV.vscode.process<`u`?GV=WV.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(GV=process);var KV=typeof GV?.versions?.electron==`string`&&GV?.type===`renderer`;if(typeof GV==`object`){LV=GV.platform===`win32`,RV=GV.platform===`darwin`,zV=GV.platform===`linux`,zV&&GV.env.SNAP&&GV.env.SNAP_REVISION,GV.env.CI||GV.env.BUILD_ARTIFACTSTAGINGDIRECTORY,HV=IV;let e=GV.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,HV=t.resolvedLanguage||IV,t.languagePack?.translationsConfigFile}catch{}BV=!0}else typeof navigator==`object`&&!KV?(UV=navigator.userAgent,LV=UV.indexOf(`Windows`)>=0,RV=UV.indexOf(`Macintosh`)>=0,(UV.indexOf(`Macintosh`)>=0||UV.indexOf(`iPad`)>=0||UV.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,zV=UV.indexOf(`Linux`)>=0,UV?.indexOf(`Mobi`),VV=!0,HV=globalThis._VSCODE_NLS_LANGUAGE||IV,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var qV=LV,JV=RV,YV=zV,XV=BV;VV&&typeof WV.importScripts==`function`&&WV.origin;var ZV=UV,QV=HV,$V;(e=>{function t(){return QV}e.value=t;function n(){return QV.length===2?QV===`en`:QV.length>=3&&QV[0]===`e`&&QV[1]===`n`&&QV[2]===`-`}e.isDefaultVariant=n;function r(){return QV===`en`}e.isDefault=r})($V||={});var eH=typeof WV.postMessage==`function`&&!WV.importScripts;(()=>{if(eH){let e=[];WV.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n{let r=++t;e.push({id:r,callback:n}),WV.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var tH=!!(ZV&&ZV.indexOf(`Chrome`)>=0);ZV&&ZV.indexOf(`Firefox`),!tH&&ZV&&ZV.indexOf(`Safari`),ZV&&ZV.indexOf(`Edg/`),ZV&&ZV.indexOf(`Android`);var nH=typeof navigator==`object`?navigator:{};XV||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||nH&&nH.clipboard&&nH.clipboard.writeText,XV||nH&&nH.clipboard&&nH.clipboard.readText,XV||FV()||nH.keyboard,`ontouchstart`in iV||nH.maxTouchPoints,iV.PointerEvent&&(`ontouchstart`in iV||navigator.maxTouchPoints);var rH=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},iH=new rH,aH=new rH,oH=new rH,sH=Array(230),cH;(e=>{function t(e){return iH.keyCodeToStr(e)}e.toString=t;function n(e){return iH.strToKeyCode(e)}e.fromString=n;function r(e){return aH.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return oH.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return aH.strToKeyCode(e)||oH.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return iH.keyCodeToStr(e)}e.toElectronAccelerator=o})(cH||={});var lH=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new uH([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},uH=class{constructor(e){if(e.length===0)throw RB(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t{function t(t){return t===e.None||t===e.Cancelled||t instanceof wH?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:uV.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:SH})})(CH||={});var wH=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?SH:(this._emitter||=new CV,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},TH=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new BB(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new BB(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},EH=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new BB(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=$B(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var DH;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(DH||={});var OH=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new CV,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};OH.EMPTY=OH.fromArray([]);function kH(e){return AH(e,0)}function AH(e,t){switch(typeof e){case`object`:return e===null?jH(349,t):Array.isArray(e)?PH(e,t):FH(e,t);case`string`:return NH(e,t);case`boolean`:return MH(e,t);case`number`:return jH(e,t);case`undefined`:return jH(937,t);default:return jH(617,t)}}function jH(e,t){return(t<<5)-t+e|0}function MH(e,t){return jH(e?433:863,t)}function NH(e,t){t=jH(149417,t);for(let n=0,r=e.length;nAH(t,e),t)}function FH(e,t){return t=jH(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=NH(n,t),AH(e[n],t)),t)}var{registerWindow:IH,getWindow:LH,getDocument:RH,getWindows:zH,getWindowsCount:BH,getWindowId:VH,getWindowById:HH,hasWindow:UH,onDidRegisterWindow:WH,onWillUnregisterWindow:GH,onDidUnregisterWindow:KH}=function(){let e=new Map,t={window:iV,disposables:new tV};e.set(iV.vscodeWindowId,t);let n=new CV,r=new CV,i=new CV;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return nV.None;let a=new tV,o={window:t,disposables:a.add(new tV)};return e.set(t.vscodeWindowId,o),a.add($B(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(JH(t,rU.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:iV},getDocument(e){return LH(e).document}}}(),qH=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function JH(e,t,n,r){return new qH(e,t,n,r)}function YH(e,t){return function(n){return t(new bH(e,n))}}function XH(e){return function(t){return e(new gH(t))}}var ZH=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=YH(LH(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=XH(n)),JH(e,t,i,r)},QH,$H=class extends EH{constructor(e){super(),this.defaultTarget=e&&LH(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},eU=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){PB(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(eU.sort),a.shift().execute();r.set(i,!1)};QH=(t,r,a=0)=>{let o=VH(t),s=new eU(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var tU=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};tU.None=new tU(0,0);function nU(e){let t=e.getBoundingClientRect(),n=LH(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=kH(n),a=r.get(i);if(a)a.users+=1;else{let o=new CV,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add($B(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var rU={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:jV?`webkitAnimationStart`:`animationstart`,ANIMATION_END:jV?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:jV?`webkitAnimationIteration`:`animationiteration`},iU=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=aU(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=aU(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=aU(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=aU(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=aU(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=aU(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=aU(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=aU(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=aU(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=aU(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=aU(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=aU(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=aU(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=aU(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function aU(e){return typeof e==`number`?`${e}px`:e}function oU(e){return new iU(e)}var sU=class{constructor(){this._hooks=new tV,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add($B(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=LH(e)}this._hooks.add(JH(a,rU.POINTER_MOVE,e=>{if(e.buttons!==n){this.stopMonitoring(!0);return}e.preventDefault(),this._pointerMoveCallback(e)})),this._hooks.add(JH(a,rU.POINTER_UP,e=>this.stopMonitoring(!0)))}};function cU(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var lU;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(lU||={});var uU=class e extends nV{constructor(){super(),this.dispatched=!1,this.targets=new sV,this.ignoreTargets=new sV,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(uV.runAndSubscribe(WH,({window:e,disposables:t})=>{t.add(JH(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(JH(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(JH(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:iV,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=XB(new e),$B(e.INSTANCE.targets.push(t))):nV.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=XB(new e),$B(e.INSTANCE.ignoreTargets.push(t))):nV.None}static isTouchDevice(){return`ontouchstart`in iV||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n=e.HOLD_DELAY&&Math.abs(s.initialPageX-VB(s.rollingPageX))<30&&Math.abs(s.initialPageY-VB(s.rollingPageY))<30){let e=this.newGestureEvent(lU.Contextmenu,s.initialTarget);e.pageX=VB(s.rollingPageX),e.pageY=VB(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=VB(s.rollingPageX),n=VB(s.rollingPageY),i=VB(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(lU.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===lU.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===lU.Change||t.type===lU.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=QH(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(lU.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};uU.SCROLL_FRICTION=-.005,uU.HOLD_DELAY=700,uU.CLEAR_TAP_COUNT_TIME=400,zz([cU],uU,`isTouchDevice`,1);var dU=uU,fU=class extends nV{onclick(e,t){this._register(JH(e,rU.CLICK,n=>t(new bH(LH(e),n))))}onmousedown(e,t){this._register(JH(e,rU.MOUSE_DOWN,n=>t(new bH(LH(e),n))))}onmouseover(e,t){this._register(JH(e,rU.MOUSE_OVER,n=>t(new bH(LH(e),n))))}onmouseleave(e,t){this._register(JH(e,rU.MOUSE_LEAVE,n=>t(new bH(LH(e),n))))}onkeydown(e,t){this._register(JH(e,rU.KEY_DOWN,e=>t(new gH(e))))}onkeyup(e,t){this._register(JH(e,rU.KEY_UP,e=>t(new gH(e))))}oninput(e,t){this._register(JH(e,rU.INPUT,t))}onblur(e,t){this._register(JH(e,rU.BLUR,t))}onfocus(e,t){this._register(JH(e,rU.FOCUS,t))}onchange(e,t){this._register(JH(e,rU.CHANGE,t))}ignoreGesture(e){return dU.ignoreTarget(e)}},pU=11,mU=class extends fU{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=pU+`px`,this.domNode.style.height=pU+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new sU),this._register(ZH(this.bgDomNode,rU.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(ZH(this.domNode,rU.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new $H),this._pointerdownScheduleRepeatTimer=this._register(new TH)}_arrowPointerDown(e){!e.target||!(e.target instanceof Element)||(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,LH(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},hU=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},gU=class extends nV{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new CV),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new hU(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new bU(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=bU.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},_U=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function vU(e,t){let n=t-e;return function(t){return e+n*SU(t)}}function yU(e,t,n){return function(r){return r2.5*n){let r,i;return e{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},wU=140,TU=class extends fU{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new CU(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new sU),this._shouldRender=!0,this.domNode=oU(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(JH(this.domNode.domNode,rU.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new mU(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=oU(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(JH(this.slider.domNode,rU.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=nU(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(qV&&a>wU){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},EU=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};NU.INSTANCE=new NU;var PU=NU,FU=class extends fU{constructor(e,t,n){super(),this._onScroll=this._register(new CV),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new CV),this.onWillScroll=this._onWillScroll.event,this._options=LU(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new OU(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new DU(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=oU(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=oU(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=oU(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new TH),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=ZB(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,JV&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new xH(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=ZB(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(JH(this._listenOnDomNode,rU.MOUSE_WHEEL,e=>{this._onMouseWheel(new xH(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=PU.INSTANCE;jU&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!JV&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=AU*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=AU*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(jU&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),kU)}},IU=class extends FU{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function LU(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`&&e.horizontalHasArrows,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,JV&&(t.className+=` mac`),t}var RU=class extends nV{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new CV),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new gU({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>QH(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new IU(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(uV.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register($B(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register($B(()=>this._styleElement.remove())),this._register(uV.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(` -`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};RU=zz([Bz(2,pB),Bz(3,EB),Bz(4,mB),Bz(5,jB),Bz(6,yB),Bz(7,OB)],RU);var zU=class extends nV{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register($B(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};zU=zz([Bz(1,pB),Bz(2,EB),Bz(3,SB),Bz(4,OB)],zU);var BU=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},VU={full:0,left:0,center:0,right:0},HU={full:0,left:0,center:0,right:0},UU={full:0,left:0,center:0,right:0},WU=class extends nV{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new BU,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register($B(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);HU.full=this._canvas.width,HU.left=e,HU.center=t,HU.right=e,this._refreshDrawHeightConstants(),UU.full=1,UU.left=1,UU.center=1+HU.left,UU.right=1+HU.left+HU.center}_refreshDrawHeightConstants(){VU.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);VU.left=t,VU.center=t,VU.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*VU.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*VU.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*VU.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*VU.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(UU[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-VU[e.position||`full`]/2),HU[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+VU[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};WU=zz([Bz(2,pB),Bz(3,SB),Bz(4,OB),Bz(5,yB),Bz(6,jB),Bz(7,EB)],WU);var $;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=` -`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var GU;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(GU||={});var KU;(e=>e.ST=`${$.ESC}\\`)(KU||={});var qU=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.lengththis.updateCompositionElements(!0),0)}}};qU=zz([Bz(2,pB),Bz(3,yB),Bz(4,hB),Bz(5,OB)],qU);var JU=0,YU=0,XU=0,ZU=0,QU={css:`#00000000`,rgba:0},$U;(e=>{function t(e,t,n,r){return r===void 0?`#${iW(e)}${iW(t)}${iW(n)}`:`#${iW(e)}${iW(t)}${iW(n)}${iW(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})($U||={});var eW;(e=>{function t(e,t){if(ZU=(t.rgba&255)/255,ZU===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return JU=a+Math.round((n-a)*ZU),YU=o+Math.round((r-o)*ZU),XU=s+Math.round((i-s)*ZU),{css:$U.toCss(JU,YU,XU),rgba:$U.toRgba(JU,YU,XU)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=rW.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return $U.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[JU,YU,XU]=rW.toChannels(t),{css:$U.toCss(JU,YU,XU),rgba:t}}e.opaque=i;function a(e,t){return ZU=Math.round(t*255),[JU,YU,XU]=rW.toChannels(e.rgba),{css:$U.toCss(JU,YU,XU,ZU),rgba:$U.toRgba(JU,YU,XU,ZU)}}e.opacity=a;function o(e,t){return ZU=e.rgba&255,a(e,ZU*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(eW||={});var tW;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return JU=parseInt(e.slice(1,2).repeat(2),16),YU=parseInt(e.slice(2,3).repeat(2),16),XU=parseInt(e.slice(3,4).repeat(2),16),$U.toColor(JU,YU,XU);case 5:return JU=parseInt(e.slice(1,2).repeat(2),16),YU=parseInt(e.slice(2,3).repeat(2),16),XU=parseInt(e.slice(3,4).repeat(2),16),ZU=parseInt(e.slice(4,5).repeat(2),16),$U.toColor(JU,YU,XU,ZU);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return JU=parseInt(r[1]),YU=parseInt(r[2]),XU=parseInt(r[3]),ZU=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),$U.toColor(JU,YU,XU,ZU);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[JU,YU,XU,ZU]=t.getImageData(0,0,1,1).data,ZU!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:$U.toRgba(JU,YU,XU,ZU),css:e}}e.toColor=r})(tW||={});var nW;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(nW||={});var rW;(e=>{function t(e,t){if(ZU=(t&255)/255,ZU===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return JU=a+Math.round((n-a)*ZU),YU=o+Math.round((r-o)*ZU),XU=s+Math.round((i-s)*ZU),$U.toRgba(JU,YU,XU)}e.blend=t;function n(e,t,n){let a=nW.relativeLuminance(e>>8),o=nW.relativeLuminance(t>>8);if(aW(a,o)>8));if(saW(a,nW.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=aW(a,nW.relativeLuminance(s>>8));if(caW(a,nW.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=aW(nW.relativeLuminance2(o,s,c),nW.relativeLuminance2(r,i,a));for(;l0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=aW(nW.relativeLuminance2(o,s,c),nW.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=aW(nW.relativeLuminance2(o,s,c),nW.relativeLuminance2(r,i,a));for(;l>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(rW||={});function iW(e){let t=e.toString(16);return t.length<2?`0`+t:t}function aW(e,t){return e1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t=E,M=k,N=this._workCell;if(f.length>0&&k===f[0][0]&&j){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v=r[1],j?(A=!0,N=new oW(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),M=r[1]-1,m=N.getWidth()):E=r[1]}let P=this._isCellInSelection(k,t),F=n&&k===a,I=O&&k>=l&&k<=u,L=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{L=!0});let R=N.getChars()||rB;if(R===` `&&(N.isUnderline()||N.isOverline())&&(R=`\xA0`),T=m*s-c.get(R,N.isBold(),N.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(P&&w||!P&&!w&&N.bg===y)&&(P&&w&&p.selectionForeground||N.fg===b)&&N.extended.ext===x&&I===S&&T===C&&!F&&!A&&!L&&j){N.isInvisible()?_+=rB:_+=R,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=N.bg,b=N.fg,x=N.extended.ext,S=I,C=T,w=P,A&&a>=k&&a<=M&&(a=k),!this._coreService.isCursorHidden&&F&&this._coreService.isCursorInitialized){if(D.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&D.push(`xterm-cursor-blink`),D.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:D.push(`xterm-cursor-outline`);break;case`block`:D.push(`xterm-cursor-block`);break;case`bar`:D.push(`xterm-cursor-bar`);break;case`underline`:D.push(`xterm-cursor-underline`);break;default:break}}if(N.isBold()&&D.push(`xterm-bold`),N.isItalic()&&D.push(`xterm-italic`),N.isDim()&&D.push(`xterm-dim`),_=N.isInvisible()?rB:N.getChars()||rB,N.isUnderline()&&(D.push(`xterm-underline-${N.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!N.isUnderlineColorDefault()))if(N.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${iB.toColorRGB(N.getUnderlineColor()).join(`,`)})`;else{let e=N.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&N.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}N.isOverline()&&(D.push(`xterm-overline`),_===` `&&(_=`\xA0`)),N.isStrikethrough()&&D.push(`xterm-strikethrough`),I&&(h.style.textDecoration=`underline`);let ee=N.getFgColor(),z=N.getFgColorMode(),B=N.getBgColor(),V=N.getBgColorMode(),H=!!N.isInverse();if(H){let e=ee;ee=B,B=e;let t=z;z=V,V=t}let te,ne,re=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{e.options.layer!==`top`&&re||(e.backgroundColorRGB&&(V=50331648,B=e.backgroundColorRGB.rgba>>8&16777215,te=e.backgroundColorRGB),e.foregroundColorRGB&&(z=50331648,ee=e.foregroundColorRGB.rgba>>8&16777215,ne=e.foregroundColorRGB),re=e.options.layer===`top`)}),!re&&P&&(te=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,B=te.rgba>>8&16777215,V=50331648,re=!0,p.selectionForeground&&(z=50331648,ee=p.selectionForeground.rgba>>8&16777215,ne=p.selectionForeground)),re&&D.push(`xterm-decoration-top`);let ie;switch(V){case 16777216:case 33554432:ie=p.ansi[B],D.push(`xterm-bg-${B}`);break;case 50331648:ie=$U.toColor(B>>16,B>>8&255,B&255),this._addStyle(h,`background-color:#${mW((B>>>0).toString(16),`0`,6)}`);break;default:H?(ie=p.foreground,D.push(`xterm-bg-257`)):ie=p.background}switch(te||N.isDim()&&(te=eW.multiplyOpacity(ie,.5)),z){case 16777216:case 33554432:N.isBold()&&ee<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ee+=8),this._applyMinimumContrast(h,ie,p.ansi[ee],N,te,void 0)||D.push(`xterm-fg-${ee}`);break;case 50331648:let e=$U.toColor(ee>>16&255,ee>>8&255,ee&255);this._applyMinimumContrast(h,ie,e,N,te,ne)||this._addStyle(h,`color:#${mW(ee.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,ie,p.foreground,N,te,ne)||H&&D.push(`xterm-fg-257`)}D.length&&=(h.className=D.join(` `),0),!F&&!A&&!L&&j?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),k=M}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||uW(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=eW.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t=n[0]&&e=n[0]}};pW=zz([Bz(1,AB),Bz(2,yB),Bz(3,EB),Bz(4,hB),Bz(5,SB),Bz(6,jB)],pW);function mW(e,t,n){for(;e.length0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},gW=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);if(s>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n=this.startCol&&t=this.startCol):!1}};function _W(){return new gW}var vW=`xterm-dom-renderer-owner-`,yW=`xterm-rows`,bW=`xterm-fg-`,xW=`xterm-bg-`,SW=`xterm-focus`,CW=`xterm-selection`,wW=1,TW=class extends nV{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=wW++,this._rowElements=[],this._selectionRenderModel=_W(),this.onRequestRedraw=this._register(new CV).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(yW),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(CW),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=dW(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(pW,document),this._element.classList.add(vW+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register($B(()=>{this._element.classList.remove(vW+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new hW(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${yW} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${yW} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${yW} .xterm-dim { color: ${eW.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${yW}.${SW} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${yW}.${SW} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${yW}.${SW} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${yW} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${yW} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${yW} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${yW} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${yW} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${CW} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${CW} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${CW} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${bW}${n} { color: ${r.css}; }${this._terminalSelector} .${bW}${n}.xterm-dim { color: ${eW.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${xW}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${bW}257 { color: ${eW.opaque(e.background).css}; }${this._terminalSelector} .${bW}257.xterm-dim { color: ${eW.multiplyOpacity(eW.opaque(e.background),.5).css}; }${this._terminalSelector} .${xW}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(SW),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(SW),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${vW}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};TW=zz([Bz(7,_B),Bz(8,TB),Bz(9,yB),Bz(10,pB),Bz(11,hB),Bz(12,EB),Bz(13,jB)],TW);var EW=class extends nV{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new CV),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new kW(this._optionsService))}catch{this._measureStrategy=this._register(new OW(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};EW=zz([Bz(2,yB)],EW);var DW=class extends nV{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},OW=class extends DW{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},kW=class extends DW{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},AW=class extends nV{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new jW(this._window)),this._onDprChange=this._register(new CV),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new CV),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(uV.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(JH(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(JH(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},jW=class extends nV{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new rV),this._onDprChange=this._register(new CV),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register($B(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=JH(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},MW=class extends nV{constructor(){super(),this.linkProviders=[],this._register($B(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function NW(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function PW(e,t,n,r,i,a,o,s,c){if(!a)return;let l=NW(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var FW=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return PW(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=NW(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};FW=zz([Bz(0,OB),Bz(1,TB)],FW);var IW=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();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),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},LW={};Rz(LW,{getSafariVersion:()=>WW,isChromeOS:()=>XW,isFirefox:()=>VW,isIpad:()=>KW,isIphone:()=>qW,isLegacyEdge:()=>HW,isLinux:()=>YW,isMac:()=>GW,isNode:()=>RW,isSafari:()=>UW,isWindows:()=>JW});var RW=typeof process<`u`&&`title`in process,zW=RW?`node`:navigator.userAgent,BW=RW?`node`:navigator.platform,VW=zW.includes(`Firefox`),HW=zW.includes(`Edge`),UW=/^((?!chrome|android).)*safari/i.test(zW);function WW(){if(!UW)return 0;let e=zW.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var GW=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(BW),KW=BW===`iPad`,qW=BW===`iPhone`,JW=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(BW),YW=BW.indexOf(`Linux`)>=0,XW=/\bCrOS\b/.test(zW),ZW=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ii){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},QW=class extends ZW{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},$W=class extends ZW{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},eG=!RW&&`requestIdleCallback`in window?$W:QW,tG=class{constructor(){this._queue=new eG}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},nG=class extends nV{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new rV),this._pausedResizeTask=new tG,this._observerDisposable=this._register(new rV),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new CV),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new CV),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new CV),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new CV),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new IW((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new rG(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register($B(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=$B(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};nG=zz([Bz(2,yB),Bz(3,TB),Bz(4,hB),Bz(5,SB),Bz(6,pB),Bz(7,EB),Bz(8,jB)],nG);var rG=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function iG(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return sG(i,a,e,t,n,r)+cG(a,t,n,r)+lG(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,gG(Math.abs(i-e),hG(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return gG(oG(a>t?e:i,n)+(s-1)*n.cols+1+aG(a>t?i:e,n),hG(o,r))}function aG(e,t){return e-1}function oG(e,t){return t.cols-e}function sG(e,t,n,r,i,a){return cG(t,r,i,a).length===0?``:gG(mG(e,t,e,t-dG(t,i),!1,i).length,hG(`D`,a))}function cG(e,t,n,r){let i=e-dG(e,n),a=t-dG(t,n);return gG(Math.abs(i-a)-uG(e,t,n),hG(pG(e,t),r))}function lG(e,t,n,r,i,a){let o;o=cG(t,r,i,a).length>0?r-dG(r,i):t;let s=r,c=fG(e,t,n,r,i,a);return gG(mG(e,o,n,s,c===`C`,i).length,hG(c,a))}function uG(e,t,n){let r=0,i=e-dG(e,n),a=t-dG(t,n);for(let o=0;o=0&&e0?r-dG(r,i):t,e=n&&ot?`A`:`B`}function mG(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&sa.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function hG(e,t){let n=t?`O`:`[`;return $.ESC+n+e}function gG(e,t){e=Math.floor(e);let n=``;for(let r=0;rthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function vG(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var yG=50,bG=15,xG=50,SG=500,CG=RegExp(`\xA0`,`g`),wG=class extends nV{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new oB,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new CV),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new CV),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new CV),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new CV),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new _G(this._bufferService),this._activeSelectionMode=0,this._register($B(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]e.replace(CG,` `)).join(JW?`\r +`).trim(),t=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(e);DV.register(a,t?.[2]??e,a)}return a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*EV<=t.length){let e=0;for(let n=0;n0}},kV=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},AV=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new OV,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new OV,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};AV.INSTANCE=new AV;var jV=AV;function MV(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}jV.INSTANCE.onDidChangeZoomLevel;function NV(e){return jV.INSTANCE.getZoomFactor(e)}jV.INSTANCE.onDidChangeFullscreen;var PV=typeof navigator==`object`?navigator.userAgent:``,FV=PV.indexOf(`Firefox`)>=0,IV=PV.indexOf(`AppleWebKit`)>=0,LV=PV.indexOf(`Chrome`)>=0,RV=!LV&&PV.indexOf(`Safari`)>=0;PV.indexOf(`Electron/`),PV.indexOf(`Android`);var zV=!1;if(typeof lV.matchMedia==`function`){let e=lV.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=lV.matchMedia(`(display-mode: fullscreen)`);zV=e.matches,MV(lV,e,({matches:e})=>{zV&&t.matches||(zV=e)})}function BV(){return zV}var VV=`en`,HV=!1,UV=!1,WV=!1,GV=!1,KV=!1,qV=VV,JV,YV=globalThis,XV;typeof YV.vscode<`u`&&typeof YV.vscode.process<`u`?XV=YV.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(XV=process);var ZV=typeof XV?.versions?.electron==`string`&&XV?.type===`renderer`;if(typeof XV==`object`){HV=XV.platform===`win32`,UV=XV.platform===`darwin`,WV=XV.platform===`linux`,WV&&XV.env.SNAP&&XV.env.SNAP_REVISION,XV.env.CI||XV.env.BUILD_ARTIFACTSTAGINGDIRECTORY,qV=VV;let e=XV.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,qV=t.resolvedLanguage||VV,t.languagePack?.translationsConfigFile}catch{}GV=!0}else typeof navigator==`object`&&!ZV?(JV=navigator.userAgent,HV=JV.indexOf(`Windows`)>=0,UV=JV.indexOf(`Macintosh`)>=0,(JV.indexOf(`Macintosh`)>=0||JV.indexOf(`iPad`)>=0||JV.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,WV=JV.indexOf(`Linux`)>=0,JV?.indexOf(`Mobi`),KV=!0,qV=globalThis._VSCODE_NLS_LANGUAGE||VV,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var QV=HV,$V=UV,eH=WV,tH=GV;KV&&typeof YV.importScripts==`function`&&YV.origin;var nH=JV,rH=qV,iH;(e=>{function t(){return rH}e.value=t;function n(){return rH.length===2?rH===`en`:rH.length>=3&&rH[0]===`e`&&rH[1]===`n`&&rH[2]===`-`}e.isDefaultVariant=n;function r(){return rH===`en`}e.isDefault=r})(iH||={});var aH=typeof YV.postMessage==`function`&&!YV.importScripts;(()=>{if(aH){let e=[];YV.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n{let r=++t;e.push({id:r,callback:n}),YV.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var oH=!!(nH&&nH.indexOf(`Chrome`)>=0);nH&&nH.indexOf(`Firefox`),!oH&&nH&&nH.indexOf(`Safari`),nH&&nH.indexOf(`Edg/`),nH&&nH.indexOf(`Android`);var sH=typeof navigator==`object`?navigator:{};tH||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||sH&&sH.clipboard&&sH.clipboard.writeText,tH||sH&&sH.clipboard&&sH.clipboard.readText,tH||BV()||sH.keyboard,`ontouchstart`in lV||sH.maxTouchPoints,lV.PointerEvent&&(`ontouchstart`in lV||navigator.maxTouchPoints);var cH=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},lH=new cH,uH=new cH,dH=new cH,fH=Array(230),pH;(e=>{function t(e){return lH.keyCodeToStr(e)}e.toString=t;function n(e){return lH.strToKeyCode(e)}e.fromString=n;function r(e){return uH.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return dH.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return uH.strToKeyCode(e)||dH.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return lH.keyCodeToStr(e)}e.toElectronAccelerator=o})(pH||={});var mH=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new hH([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},hH=class{constructor(e){if(e.length===0)throw UB(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t{function t(t){return t===e.None||t===e.Cancelled||t instanceof kH?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:hV.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:DH})})(OH||={});var kH=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?DH:(this._emitter||=new OV,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},AH=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new GB(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new GB(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},jH=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new GB(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=iV(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var MH;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(MH||={});var NH=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new OV,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};NH.EMPTY=NH.fromArray([]);function PH(e){return FH(e,0)}function FH(e,t){switch(typeof e){case`object`:return e===null?IH(349,t):Array.isArray(e)?zH(e,t):BH(e,t);case`string`:return RH(e,t);case`boolean`:return LH(e,t);case`number`:return IH(e,t);case`undefined`:return IH(937,t);default:return IH(617,t)}}function IH(e,t){return(t<<5)-t+e|0}function LH(e,t){return IH(e?433:863,t)}function RH(e,t){t=IH(149417,t);for(let n=0,r=e.length;nFH(t,e),t)}function BH(e,t){return t=IH(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=RH(n,t),FH(e[n],t)),t)}var{registerWindow:VH,getWindow:HH,getDocument:UH,getWindows:WH,getWindowsCount:GH,getWindowId:KH,getWindowById:qH,hasWindow:JH,onDidRegisterWindow:YH,onWillUnregisterWindow:XH,onDidUnregisterWindow:ZH}=function(){let e=new Map,t={window:lV,disposables:new oV};e.set(lV.vscodeWindowId,t);let n=new OV,r=new OV,i=new OV;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return sV.None;let a=new oV,o={window:t,disposables:a.add(new oV)};return e.set(t.vscodeWindowId,o),a.add(iV(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add($H(t,cU.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:lV},getDocument(e){return HH(e).document}}}(),QH=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function $H(e,t,n,r){return new QH(e,t,n,r)}function eU(e,t){return function(n){return t(new TH(e,n))}}function tU(e){return function(t){return e(new xH(t))}}var nU=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=eU(HH(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=tU(n)),$H(e,t,i,r)},rU,iU=class extends jH{constructor(e){super(),this.defaultTarget=e&&HH(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},aU=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){zB(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(aU.sort),a.shift().execute();r.set(i,!1)};rU=(t,r,a=0)=>{let o=KH(t),s=new aU(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var oU=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};oU.None=new oU(0,0);function sU(e){let t=e.getBoundingClientRect(),n=HH(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=PH(n),a=r.get(i);if(a)a.users+=1;else{let o=new OV,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(iV(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var cU={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:IV?`webkitAnimationStart`:`animationstart`,ANIMATION_END:IV?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:IV?`webkitAnimationIteration`:`animationiteration`},lU=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=uU(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=uU(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=uU(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=uU(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=uU(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=uU(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=uU(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=uU(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=uU(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=uU(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=uU(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=uU(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=uU(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=uU(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function uU(e){return typeof e==`number`?`${e}px`:e}function dU(e){return new lU(e)}var fU=class{constructor(){this._hooks=new oV,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(iV(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=HH(e)}this._hooks.add($H(a,cU.POINTER_MOVE,e=>{if(e.buttons!==n){this.stopMonitoring(!0);return}e.preventDefault(),this._pointerMoveCallback(e)})),this._hooks.add($H(a,cU.POINTER_UP,e=>this.stopMonitoring(!0)))}};function pU(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var mU;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(mU||={});var hU=class e extends sV{constructor(){super(),this.dispatched=!1,this.targets=new fV,this.ignoreTargets=new fV,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(hV.runAndSubscribe(YH,({window:e,disposables:t})=>{t.add($H(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add($H(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add($H(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:lV,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=tV(new e),iV(e.INSTANCE.targets.push(t))):sV.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=tV(new e),iV(e.INSTANCE.ignoreTargets.push(t))):sV.None}static isTouchDevice(){return`ontouchstart`in lV||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n=e.HOLD_DELAY&&Math.abs(s.initialPageX-KB(s.rollingPageX))<30&&Math.abs(s.initialPageY-KB(s.rollingPageY))<30){let e=this.newGestureEvent(mU.Contextmenu,s.initialTarget);e.pageX=KB(s.rollingPageX),e.pageY=KB(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=KB(s.rollingPageX),n=KB(s.rollingPageY),i=KB(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(mU.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===mU.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===mU.Change||t.type===mU.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=rU(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(mU.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};hU.SCROLL_FRICTION=-.005,hU.HOLD_DELAY=700,hU.CLEAR_TAP_COUNT_TIME=400,Wz([pU],hU,`isTouchDevice`,1);var gU=hU,_U=class extends sV{onclick(e,t){this._register($H(e,cU.CLICK,n=>t(new TH(HH(e),n))))}onmousedown(e,t){this._register($H(e,cU.MOUSE_DOWN,n=>t(new TH(HH(e),n))))}onmouseover(e,t){this._register($H(e,cU.MOUSE_OVER,n=>t(new TH(HH(e),n))))}onmouseleave(e,t){this._register($H(e,cU.MOUSE_LEAVE,n=>t(new TH(HH(e),n))))}onkeydown(e,t){this._register($H(e,cU.KEY_DOWN,e=>t(new xH(e))))}onkeyup(e,t){this._register($H(e,cU.KEY_UP,e=>t(new xH(e))))}oninput(e,t){this._register($H(e,cU.INPUT,t))}onblur(e,t){this._register($H(e,cU.BLUR,t))}onfocus(e,t){this._register($H(e,cU.FOCUS,t))}onchange(e,t){this._register($H(e,cU.CHANGE,t))}ignoreGesture(e){return gU.ignoreTarget(e)}},vU=11,yU=class extends _U{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=vU+`px`,this.domNode.style.height=vU+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new fU),this._register(nU(this.bgDomNode,cU.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(nU(this.domNode,cU.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new iU),this._pointerdownScheduleRepeatTimer=this._register(new AH)}_arrowPointerDown(e){!e.target||!(e.target instanceof Element)||(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,HH(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},bU=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},xU=class extends sV{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new OV),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new bU(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new TU(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=TU.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},SU=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function CU(e,t){let n=t-e;return function(t){return e+n*DU(t)}}function wU(e,t,n){return function(r){return r2.5*n){let r,i;return e{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},kU=140,AU=class extends _U{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new OU(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new fU),this._shouldRender=!0,this.domNode=dU(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register($H(this.domNode.domNode,cU.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new yU(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=dU(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register($H(this.slider.domNode,cU.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=sU(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(QV&&a>kU){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},jU=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};RU.INSTANCE=new RU;var zU=RU,BU=class extends _U{constructor(e,t,n){super(),this._onScroll=this._register(new OV),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new OV),this.onWillScroll=this._onWillScroll.event,this._options=HU(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new NU(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new MU(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=dU(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=dU(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=dU(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new AH),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=nV(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,$V&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new EH(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=nV(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push($H(this._listenOnDomNode,cU.MOUSE_WHEEL,e=>{this._onMouseWheel(new EH(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=zU.INSTANCE;IU&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!$V&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=FU*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=FU*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(IU&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),PU)}},VU=class extends BU{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function HU(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`&&e.horizontalHasArrows,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,$V&&(t.className+=` mac`),t}var UU=class extends sV{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new OV),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new xU({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>rU(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new VU(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(hV.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(iV(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(iV(()=>this._styleElement.remove())),this._register(hV.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(` +`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};UU=Wz([Gz(2,vB),Gz(3,jB),Gz(4,yB),Gz(5,IB),Gz(6,wB),Gz(7,NB)],UU);var WU=class extends sV{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(iV(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};WU=Wz([Gz(1,vB),Gz(2,jB),Gz(3,DB),Gz(4,NB)],WU);var GU=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},KU={full:0,left:0,center:0,right:0},qU={full:0,left:0,center:0,right:0},JU={full:0,left:0,center:0,right:0},YU=class extends sV{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new GU,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(iV(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);qU.full=this._canvas.width,qU.left=e,qU.center=t,qU.right=e,this._refreshDrawHeightConstants(),JU.full=1,JU.left=1,JU.center=1+qU.left,JU.right=1+qU.left+qU.center}_refreshDrawHeightConstants(){KU.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);KU.left=t,KU.center=t,KU.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*KU.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*KU.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*KU.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*KU.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(JU[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-KU[e.position||`full`]/2),qU[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+KU[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};YU=Wz([Gz(2,vB),Gz(3,DB),Gz(4,NB),Gz(5,wB),Gz(6,IB),Gz(7,jB)],YU);var $;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=` +`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var XU;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(XU||={});var ZU;(e=>e.ST=`${$.ESC}\\`)(ZU||={});var QU=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.lengththis.updateCompositionElements(!0),0)}}};QU=Wz([Gz(2,vB),Gz(3,wB),Gz(4,bB),Gz(5,NB)],QU);var $U=0,eW=0,tW=0,nW=0,rW={css:`#00000000`,rgba:0},iW;(e=>{function t(e,t,n,r){return r===void 0?`#${lW(e)}${lW(t)}${lW(n)}`:`#${lW(e)}${lW(t)}${lW(n)}${lW(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(iW||={});var aW;(e=>{function t(e,t){if(nW=(t.rgba&255)/255,nW===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return $U=a+Math.round((n-a)*nW),eW=o+Math.round((r-o)*nW),tW=s+Math.round((i-s)*nW),{css:iW.toCss($U,eW,tW),rgba:iW.toRgba($U,eW,tW)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=cW.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return iW.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[$U,eW,tW]=cW.toChannels(t),{css:iW.toCss($U,eW,tW),rgba:t}}e.opaque=i;function a(e,t){return nW=Math.round(t*255),[$U,eW,tW]=cW.toChannels(e.rgba),{css:iW.toCss($U,eW,tW,nW),rgba:iW.toRgba($U,eW,tW,nW)}}e.opacity=a;function o(e,t){return nW=e.rgba&255,a(e,nW*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(aW||={});var oW;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return $U=parseInt(e.slice(1,2).repeat(2),16),eW=parseInt(e.slice(2,3).repeat(2),16),tW=parseInt(e.slice(3,4).repeat(2),16),iW.toColor($U,eW,tW);case 5:return $U=parseInt(e.slice(1,2).repeat(2),16),eW=parseInt(e.slice(2,3).repeat(2),16),tW=parseInt(e.slice(3,4).repeat(2),16),nW=parseInt(e.slice(4,5).repeat(2),16),iW.toColor($U,eW,tW,nW);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return $U=parseInt(r[1]),eW=parseInt(r[2]),tW=parseInt(r[3]),nW=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),iW.toColor($U,eW,tW,nW);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[$U,eW,tW,nW]=t.getImageData(0,0,1,1).data,nW!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:iW.toRgba($U,eW,tW,nW),css:e}}e.toColor=r})(oW||={});var sW;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(sW||={});var cW;(e=>{function t(e,t){if(nW=(t&255)/255,nW===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return $U=a+Math.round((n-a)*nW),eW=o+Math.round((r-o)*nW),tW=s+Math.round((i-s)*nW),iW.toRgba($U,eW,tW)}e.blend=t;function n(e,t,n){let a=sW.relativeLuminance(e>>8),o=sW.relativeLuminance(t>>8);if(uW(a,o)>8));if(suW(a,sW.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=uW(a,sW.relativeLuminance(s>>8));if(cuW(a,sW.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=uW(sW.relativeLuminance2(o,s,c),sW.relativeLuminance2(r,i,a));for(;l0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=uW(sW.relativeLuminance2(o,s,c),sW.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=uW(sW.relativeLuminance2(o,s,c),sW.relativeLuminance2(r,i,a));for(;l>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(cW||={});function lW(e){let t=e.toString(16);return t.length<2?`0`+t:t}function uW(e,t){return e1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t=E,M=k,N=this._workCell;if(f.length>0&&k===f[0][0]&&j){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v=r[1],j?(A=!0,N=new dW(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),M=r[1]-1,m=N.getWidth()):E=r[1]}let P=this._isCellInSelection(k,t),F=n&&k===a,I=O&&k>=l&&k<=u,L=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{L=!0});let R=N.getChars()||cB;if(R===` `&&(N.isUnderline()||N.isOverline())&&(R=`\xA0`),T=m*s-c.get(R,N.isBold(),N.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(P&&w||!P&&!w&&N.bg===y)&&(P&&w&&p.selectionForeground||N.fg===b)&&N.extended.ext===x&&I===S&&T===C&&!F&&!A&&!L&&j){N.isInvisible()?_+=cB:_+=R,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=N.bg,b=N.fg,x=N.extended.ext,S=I,C=T,w=P,A&&a>=k&&a<=M&&(a=k),!this._coreService.isCursorHidden&&F&&this._coreService.isCursorInitialized){if(D.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&D.push(`xterm-cursor-blink`),D.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:D.push(`xterm-cursor-outline`);break;case`block`:D.push(`xterm-cursor-block`);break;case`bar`:D.push(`xterm-cursor-bar`);break;case`underline`:D.push(`xterm-cursor-underline`);break;default:break}}if(N.isBold()&&D.push(`xterm-bold`),N.isItalic()&&D.push(`xterm-italic`),N.isDim()&&D.push(`xterm-dim`),_=N.isInvisible()?cB:N.getChars()||cB,N.isUnderline()&&(D.push(`xterm-underline-${N.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!N.isUnderlineColorDefault()))if(N.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${lB.toColorRGB(N.getUnderlineColor()).join(`,`)})`;else{let e=N.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&N.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}N.isOverline()&&(D.push(`xterm-overline`),_===` `&&(_=`\xA0`)),N.isStrikethrough()&&D.push(`xterm-strikethrough`),I&&(h.style.textDecoration=`underline`);let ee=N.getFgColor(),z=N.getFgColorMode(),B=N.getBgColor(),V=N.getBgColorMode(),H=!!N.isInverse();if(H){let e=ee;ee=B,B=e;let t=z;z=V,V=t}let te,ne,re=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{e.options.layer!==`top`&&re||(e.backgroundColorRGB&&(V=50331648,B=e.backgroundColorRGB.rgba>>8&16777215,te=e.backgroundColorRGB),e.foregroundColorRGB&&(z=50331648,ee=e.foregroundColorRGB.rgba>>8&16777215,ne=e.foregroundColorRGB),re=e.options.layer===`top`)}),!re&&P&&(te=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,B=te.rgba>>8&16777215,V=50331648,re=!0,p.selectionForeground&&(z=50331648,ee=p.selectionForeground.rgba>>8&16777215,ne=p.selectionForeground)),re&&D.push(`xterm-decoration-top`);let ie;switch(V){case 16777216:case 33554432:ie=p.ansi[B],D.push(`xterm-bg-${B}`);break;case 50331648:ie=iW.toColor(B>>16,B>>8&255,B&255),this._addStyle(h,`background-color:#${yW((B>>>0).toString(16),`0`,6)}`);break;default:H?(ie=p.foreground,D.push(`xterm-bg-257`)):ie=p.background}switch(te||N.isDim()&&(te=aW.multiplyOpacity(ie,.5)),z){case 16777216:case 33554432:N.isBold()&&ee<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ee+=8),this._applyMinimumContrast(h,ie,p.ansi[ee],N,te,void 0)||D.push(`xterm-fg-${ee}`);break;case 50331648:let e=iW.toColor(ee>>16&255,ee>>8&255,ee&255);this._applyMinimumContrast(h,ie,e,N,te,ne)||this._addStyle(h,`color:#${yW(ee.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,ie,p.foreground,N,te,ne)||H&&D.push(`xterm-fg-257`)}D.length&&=(h.className=D.join(` `),0),!F&&!A&&!L&&j?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),k=M}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||hW(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=aW.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t=n[0]&&e=n[0]}};vW=Wz([Gz(1,FB),Gz(2,wB),Gz(3,jB),Gz(4,bB),Gz(5,DB),Gz(6,IB)],vW);function yW(e,t,n){for(;e.length0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},xW=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);if(s>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n=this.startCol&&t=this.startCol):!1}};function SW(){return new xW}var CW=`xterm-dom-renderer-owner-`,wW=`xterm-rows`,TW=`xterm-fg-`,EW=`xterm-bg-`,DW=`xterm-focus`,OW=`xterm-selection`,kW=1,AW=class extends sV{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=kW++,this._rowElements=[],this._selectionRenderModel=SW(),this.onRequestRedraw=this._register(new OV).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(wW),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(OW),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=gW(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(vW,document),this._element.classList.add(CW+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(iV(()=>{this._element.classList.remove(CW+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new bW(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${wW} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${wW} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${wW} .xterm-dim { color: ${aW.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${wW}.${DW} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${wW}.${DW} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${wW}.${DW} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${wW} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${wW} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${wW} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${wW} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${wW} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${OW} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${OW} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${OW} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${TW}${n} { color: ${r.css}; }${this._terminalSelector} .${TW}${n}.xterm-dim { color: ${aW.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${EW}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${TW}257 { color: ${aW.opaque(e.background).css}; }${this._terminalSelector} .${TW}257.xterm-dim { color: ${aW.multiplyOpacity(aW.opaque(e.background),.5).css}; }${this._terminalSelector} .${EW}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(DW),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(DW),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${CW}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};AW=Wz([Gz(7,SB),Gz(8,AB),Gz(9,wB),Gz(10,vB),Gz(11,bB),Gz(12,jB),Gz(13,IB)],AW);var jW=class extends sV{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new OV),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new PW(this._optionsService))}catch{this._measureStrategy=this._register(new NW(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};jW=Wz([Gz(2,wB)],jW);var MW=class extends sV{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},NW=class extends MW{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},PW=class extends MW{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},FW=class extends sV{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new IW(this._window)),this._onDprChange=this._register(new OV),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new OV),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(hV.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register($H(this._textarea,`focus`,()=>this._isFocused=!0)),this._register($H(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},IW=class extends sV{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new cV),this._onDprChange=this._register(new OV),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(iV(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=$H(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},LW=class extends sV{constructor(){super(),this.linkProviders=[],this._register(iV(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function RW(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function zW(e,t,n,r,i,a,o,s,c){if(!a)return;let l=RW(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var BW=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return zW(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=RW(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};BW=Wz([Gz(0,NB),Gz(1,AB)],BW);var VW=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();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),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},HW={};Uz(HW,{getSafariVersion:()=>YW,isChromeOS:()=>tG,isFirefox:()=>KW,isIpad:()=>ZW,isIphone:()=>QW,isLegacyEdge:()=>qW,isLinux:()=>eG,isMac:()=>XW,isNode:()=>UW,isSafari:()=>JW,isWindows:()=>$W});var UW=typeof process<`u`&&`title`in process,WW=UW?`node`:navigator.userAgent,GW=UW?`node`:navigator.platform,KW=WW.includes(`Firefox`),qW=WW.includes(`Edge`),JW=/^((?!chrome|android).)*safari/i.test(WW);function YW(){if(!JW)return 0;let e=WW.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var XW=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(GW),ZW=GW===`iPad`,QW=GW===`iPhone`,$W=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(GW),eG=GW.indexOf(`Linux`)>=0,tG=/\bCrOS\b/.test(WW),nG=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ii){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},rG=class extends nG{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},iG=class extends nG{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},aG=!UW&&`requestIdleCallback`in window?iG:rG,oG=class{constructor(){this._queue=new aG}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},sG=class extends sV{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new cV),this._pausedResizeTask=new oG,this._observerDisposable=this._register(new cV),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new OV),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new OV),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new OV),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new OV),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new VW((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new cG(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(iV(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=iV(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};sG=Wz([Gz(2,wB),Gz(3,AB),Gz(4,bB),Gz(5,DB),Gz(6,vB),Gz(7,jB),Gz(8,IB)],sG);var cG=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function lG(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return fG(i,a,e,t,n,r)+pG(a,t,n,r)+mG(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,xG(Math.abs(i-e),bG(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return xG(dG(a>t?e:i,n)+(s-1)*n.cols+1+uG(a>t?i:e,n),bG(o,r))}function uG(e,t){return e-1}function dG(e,t){return t.cols-e}function fG(e,t,n,r,i,a){return pG(t,r,i,a).length===0?``:xG(yG(e,t,e,t-gG(t,i),!1,i).length,bG(`D`,a))}function pG(e,t,n,r){let i=e-gG(e,n),a=t-gG(t,n);return xG(Math.abs(i-a)-hG(e,t,n),bG(vG(e,t),r))}function mG(e,t,n,r,i,a){let o;o=pG(t,r,i,a).length>0?r-gG(r,i):t;let s=r,c=_G(e,t,n,r,i,a);return xG(yG(e,o,n,s,c===`C`,i).length,bG(c,a))}function hG(e,t,n){let r=0,i=e-gG(e,n),a=t-gG(t,n);for(let o=0;o=0&&e0?r-gG(r,i):t,e=n&&ot?`A`:`B`}function yG(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&sa.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function bG(e,t){let n=t?`O`:`[`;return $.ESC+n+e}function xG(e,t){e=Math.floor(e);let n=``;for(let r=0;rthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function CG(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var wG=50,TG=15,EG=50,DG=500,OG=RegExp(`\xA0`,`g`),kG=class extends sV{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new dB,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new OV),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new OV),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new OV),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new OV),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new SG(this._bufferService),this._activeSelectionMode=0,this._register(iV(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]e.replace(OG,` `)).join($W?`\r `:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),YW&&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),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=vG(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,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=NW(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-yG),yG),t/=yG,t/Math.abs(t)+Math.round(t*(bG-1)))}shouldForceSelection(e){return GW?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(),xG)}_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&&!(GW&&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]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]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&&tthis._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(!(!t&&o.slice(s,c).trim()===``)){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={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=vG(n,this._bufferService.cols)}};wG=zz([Bz(3,pB),Bz(4,hB),Bz(5,DB),Bz(6,yB),Bz(7,OB),Bz(8,EB)],wG);var TG=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},EG=class{constructor(){this._color=new TG,this._css=new TG}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},DG=Object.freeze((()=>{let e=[tW.toColor(`#2e3436`),tW.toColor(`#cc0000`),tW.toColor(`#4e9a06`),tW.toColor(`#c4a000`),tW.toColor(`#3465a4`),tW.toColor(`#75507b`),tW.toColor(`#06989a`),tW.toColor(`#d3d7cf`),tW.toColor(`#555753`),tW.toColor(`#ef2929`),tW.toColor(`#8ae234`),tW.toColor(`#fce94f`),tW.toColor(`#729fcf`),tW.toColor(`#ad7fa8`),tW.toColor(`#34e2e2`),tW.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:$U.toCss(r,i,a),rgba:$U.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:$U.toCss(n,n,n),rgba:$U.toRgba(n,n,n)})}return e})()),OG=tW.toColor(`#ffffff`),kG=tW.toColor(`#000000`),AG=tW.toColor(`#ffffff`),jG=kG,MG={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},NG=OG,PG=class extends nV{constructor(e){super(),this._optionsService=e,this._contrastCache=new EG,this._halfContrastCache=new EG,this._onChangeColors=this._register(new CV),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:OG,background:kG,cursor:AG,cursorAccent:jG,selectionForeground:void 0,selectionBackgroundTransparent:MG,selectionBackgroundOpaque:eW.blend(kG,MG),selectionInactiveBackgroundTransparent:MG,selectionInactiveBackgroundOpaque:eW.blend(kG,MG),scrollbarSliderBackground:eW.opacity(OG,.2),scrollbarSliderHoverBackground:eW.opacity(OG,.4),scrollbarSliderActiveBackground:eW.opacity(OG,.5),overviewRulerBorder:OG,ansi:DG.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=FG(e.foreground,OG),t.background=FG(e.background,kG),t.cursor=eW.blend(t.background,FG(e.cursor,AG)),t.cursorAccent=eW.blend(t.background,FG(e.cursorAccent,jG)),t.selectionBackgroundTransparent=FG(e.selectionBackground,MG),t.selectionBackgroundOpaque=eW.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=FG(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=eW.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?FG(e.selectionForeground,QU):void 0,t.selectionForeground===QU&&(t.selectionForeground=void 0),eW.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=eW.opacity(t.selectionBackgroundTransparent,.3)),eW.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=eW.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=FG(e.scrollbarSliderBackground,eW.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=FG(e.scrollbarSliderHoverBackground,eW.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=FG(e.scrollbarSliderActiveBackground,eW.opacity(t.foreground,.5)),t.overviewRulerBorder=FG(e.overviewRulerBorder,NG),t.ansi=DG.slice(),t.ansi[0]=FG(e.black,DG[0]),t.ansi[1]=FG(e.red,DG[1]),t.ansi[2]=FG(e.green,DG[2]),t.ansi[3]=FG(e.yellow,DG[3]),t.ansi[4]=FG(e.blue,DG[4]),t.ansi[5]=FG(e.magenta,DG[5]),t.ansi[6]=FG(e.cyan,DG[6]),t.ansi[7]=FG(e.white,DG[7]),t.ansi[8]=FG(e.brightBlack,DG[8]),t.ansi[9]=FG(e.brightRed,DG[9]),t.ansi[10]=FG(e.brightGreen,DG[10]),t.ansi[11]=FG(e.brightYellow,DG[11]),t.ansi[12]=FG(e.brightBlue,DG[12]),t.ansi[13]=FG(e.brightMagenta,DG[13]),t.ansi[14]=FG(e.brightCyan,DG[14]),t.ansi[15]=FG(e.brightWhite,DG[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;re.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},RG={trace:0,debug:1,info:2,warn:3,error:4,off:5},zG=`xterm.js: `,BG=class extends nV{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),VG=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=RG[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;tthis._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*UG+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*UG+0]=e|2097152|t[2]<<22):this._data[e*UG+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*UG+0]>>22}hasWidth(e){return this._data[e*UG+0]&12582912}getFg(e){return this._data[e*UG+1]}getBg(e){return this._data[e*UG+2]}hasContent(e){return this._data[e*UG+0]&4194303}getCodePoint(e){let t=this._data[e*UG+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*UG+0]&2097152}getString(e){let t=this._data[e*UG+0];return t&2097152?this._combined[e]:t&2097151?Qz(t&2097151):``}isProtected(e){return this._data[e*UG+2]&536870912}loadCell(e,t){return GG=e*UG,t.content=this._data[GG+0],t.fg=this._data[GG+1],t.bg=this._data[GG+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*UG+0]=t.content,this._data[e*UG+1]=t.fg,this._data[e*UG+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*UG+0]=t|n<<22,this._data[e*UG+1]=r.fg,this._data[e*UG+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*UG+0];r&2097152?this._combined[e]+=Qz(t):r&2097151?(this._combined[e]=Qz(r&2097151)+Qz(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*UG+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;rthis.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*KG=0;--e)if(this._data[e*UG+0]&4194303)return e+(this._data[e*UG+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*UG+0]&4194303||this._data[e*UG+2]&50331648)return e+(this._data[e*UG+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t>22||1}return r&&r.push(t),i}};function JG(e,t,n,r,i,a){let o=[];for(let s=0;s=s&&r0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function YG(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;oQG(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;sc&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function QG(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var $G=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new CV),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),ZB(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};$G._nextId=1;var eK=$G,tK={},nK=tK.B;tK[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:`␤`,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},tK.A={"#":`£`},tK.B=void 0,tK[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},tK.C=tK[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},tK.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},tK.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},tK.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},tK.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},tK.E=tK[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},tK.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},tK.H=tK[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},tK[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var rK=4294967295,iK=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=WG.clone(),this.savedCharset=nK,this.markers=[],this._nullCell=oB.fromCharData([0,nB,1,0]),this._whitespaceCell=oB.fromCharData([0,rB,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new eG,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new HG(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 aB),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 aB),this._whitespaceCell}getBlankLine(e,t){return new qG(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&&erK?rK:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=WG);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 HG(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(WG),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new qG(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),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 t=0;t.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._memoryCleanupPosition100)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 n=this._optionsService.rawOptions.reflowCursorLine,r=JG(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(WG),n);if(r.length>0){let n=YG(this.lines,r);XG(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(WG),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=QG(c,Math.max(g,0),this._cols))}for(let t=0;t0;)this.ybase===0?this.y0){let e=[],t=[];for(let e=0;e=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.linee.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},aK=class extends nV{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new CV),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 iK(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new iK(!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)}},oK=2,sK=1,cK=class extends nV{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new CV),this.onResize=this._onResize.event,this._onScroll=this._register(new CV),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,oK),this.rows=Math.max(e.rawOptions.rows||0,sK),this.buffers=this._register(new aK(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};cK=zz([Bz(0,yB)],cK);var lK={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:GW,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},uK=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],dK=class extends nV{constructor(e){super(),this._onOptionChange=this._register(new CV),this.onOptionChange=this._onOptionChange.event;let t={...lK};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register($B(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in lK))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in lK))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=lK[e],!fK(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=lK[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=uK.includes(t)?t:lK[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw 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 Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function fK(e){return e===`block`||e===`underline`||e===`bar`}function pK(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&pK(e[r],t-1);return n}var mK=Object.freeze({insertMode:!1}),hK=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),gK=class extends nV{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new CV),this.onData=this._onData.event,this._onUserInput=this._register(new CV),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new CV),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new CV),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=pK(mK),this.decPrivateModes=pK(hK)}reset(){this.modes=pK(mK),this.decPrivateModes=pK(hK)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.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(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};gK=zz([Bz(0,pB),Bz(1,vB),Bz(2,yB)],gK);var _K={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 vK(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var yK=String.fromCharCode,bK={DEFAULT:e=>{let t=[vK(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${yK(t[0])}${yK(t[1])}${yK(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${vK(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${vK(e,!0)};${e.x};${e.y}${t}`}},xK=class extends nV{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new CV),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(_K))this.addProtocol(e,_K[e]);for(let e of Object.keys(bK))this.addEncoding(e,bK[e]);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 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 Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+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,n){if(n){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}};xK=zz([Bz(0,pB),Bz(1,hB),Bz(2,yB)],xK);var SK=[[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]],CK=[[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]],wK;function TK(e,t){let n=0,r=t.length-1,i;if(et[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=DK.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return DK.createPropertyValue(0,n,r)}},DK=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new CV,this.onChange=this._onChange.event;let e=new EK;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},OK=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 kK(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var AK=2147483647,jK=256,MK=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>jK)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>AK?AK:e}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>AK?AK:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,AK):e}},NK=[],PK=class{constructor(){this._state=0,this._active=NK,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 n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,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=NK}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=NK,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||NK,!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,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,$z(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,n)}}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 n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=NK,this._id=-1,this._state=0}}},FK=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=$z(e,t,n),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(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},IK=[],LK=class{constructor(){this._handlers=Object.create(null),this._active=IK,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=IK}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,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=IK,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||IK,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,$z(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=IK,this._ident=0}},RK=new MK;RK.addParam(0);var zK=class{constructor(e){this._handler=e,this._data=``,this._params=RK,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():RK,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=$z(e,t,n),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(e=>(this._params=RK,this._data=``,this._hitLimit=!1,e));return this._params=RK,this._data=``,this._hitLimit=!1,t}},BK=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;it),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,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(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,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(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(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(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(VK,0,2,0),e.add(VK,8,5,8),e.add(VK,6,0,6),e.add(VK,11,0,11),e.add(VK,13,13,13),e}(),UK=class extends nV{constructor(e=HK){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 MK,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register($B(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new PK),this._dcsParser=this._register(new LK),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;tr||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}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 n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,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 n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,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,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let n=a;n>4){case 2:for(let i=n+1;;++i){if(i>=t||(r=e[i])<32||r>126&&r=t||(r=e[i])<32||r>126&&r=t||(r=e[i])<32||r>126&&r=t||(r=e[i])<32||r>126&&r=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),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|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r=t||(r=e[i])<32||r>127&&r>4:i>>8}return n}}function qK(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function JK(e,t=16){let[n,r,i]=e;return`rgb:${qK(n,t)}/${qK(r,t)}/${qK(i,t)}`}var YK={"(":0,")":1,"*":2,"+":3,"-":1,".":2},XK=131072,ZK=10;function QK(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 $K=5e3,eq=0,tq=class extends nV{constructor(e,t,n,r,i,a,o,s,c=new UK){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new eB,this._utf8Decoder=new tB,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=WG.clone(),this._eraseAttrDataInternal=WG.clone(),this._onRequestBell=this._register(new CV),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new CV),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new CV),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new CV),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new CV),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new CV),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new CV),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new CV),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new CV),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new CV),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new CV),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new CV),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new CV),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 nq(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler($.BEL,()=>this.bell()),this._parser.setExecuteHandler($.LF,()=>this.lineFeed()),this._parser.setExecuteHandler($.VT,()=>this.lineFeed()),this._parser.setExecuteHandler($.FF,()=>this.lineFeed()),this._parser.setExecuteHandler($.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler($.BS,()=>this.backspace()),this._parser.setExecuteHandler($.HT,()=>this.tab()),this._parser.setExecuteHandler($.SO,()=>this.shiftOut()),this._parser.setExecuteHandler($.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(GU.IND,()=>this.index()),this._parser.setExecuteHandler(GU.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(GU.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new FK(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new FK(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new FK(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new FK(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new FK(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new FK(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new FK(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new FK(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new FK(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new FK(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new FK(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new FK(e=>this.restoreCursorColor(e))),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 e in tK)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new zK((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),$K))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${$K} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>XK&&(a=this._parseStack.position+XK)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.lengthXK)for(let t=a;t0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;ps){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,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),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof qG&&d.copyCellsFrom(e,t,0,m,!1);t=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!QK(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new zK(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new FK(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,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}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)}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.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let c=s;for(let e=1;e0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent($.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent($.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent($.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent($.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent($.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${$.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=iB.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=WG.fg,e.bg=WG.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,n,r=this._curAttrData;for(let i=0;i=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=WG.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=WG.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=WG.fg&16777215,r.bg&=-67108864,r.bg|=WG.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${$.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[?${e};${t}R`)}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=WG.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`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!QK(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(`${$.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>ZK&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>ZK&&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())}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=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(rq(n))if(r===`?`)t.push({type:0,index:n});else{let e=KK(r);e&&t.push({type:1,index:n,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,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 n=e.split(`;`);for(let e=0;e=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=KK(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}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=[],n=e.split(`;`);for(let e=0;e=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=WG.clone(),this._eraseAttrDataInternal=WG.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 oB;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${$.ESC}${e}${$.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},nq=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(eq=e,e=t,t=eq),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};nq=zz([Bz(0,pB)],nq);function rq(e){return 0<=e&&e<256}var iq=5e7,aq=12,oq=50,sq=class extends nV{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 CV),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 n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>iq)throw 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 n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=aq?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=aq)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>oq&&(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()}},cq=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 n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};cq=zz([Bz(0,pB)],cq);var lq=!1,uq=class extends nV{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new rV),this._onBinary=this._register(new CV),this.onBinary=this._onBinary.event,this._onData=this._register(new CV),this.onData=this._onData.event,this._onLineFeed=this._register(new CV),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new CV),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new CV),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new CV),this._instantiationService=new LG,this.optionsService=this._register(new dK(e)),this._instantiationService.setService(yB,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(cK)),this._instantiationService.setService(pB,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(BG)),this._instantiationService.setService(vB,this._logService),this.coreService=this._register(this._instantiationService.createInstance(gK)),this._instantiationService.setService(hB,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(xK)),this._instantiationService.setService(mB,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(DK)),this._instantiationService.setService(xB,this.unicodeService),this._charsetService=this._instantiationService.createInstance(OK),this._instantiationService.setService(gB,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(cq),this._instantiationService.setService(bB,this._oscLinkService),this._inputHandler=this._register(new tq(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(uV.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(uV.forward(this._bufferService.onResize,this._onResize)),this._register(uV.forward(this.coreService.onData,this._onData)),this._register(uV.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 sq((e,t)=>this._inputHandler.parse(e,t))),this._register(uV.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new CV),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&&!lq&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),lq=!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,oK),t=Math.max(t,sK),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(kK.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(kK(this._bufferService),!1))),this._windowsWrappingHeuristics.value=$B(()=>{for(let t of e)t.dispose()})}}},dq={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 fq(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?$.ESC+`OA`:$.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?$.ESC+`OD`:$.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?$.ESC+`OC`:$.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?$.ESC+`OB`:$.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:$.DEL,e.altKey&&(i.key=$.ESC+i.key);break;case 9:if(e.shiftKey){i.key=$.ESC+`[Z`;break}i.key=$.HT,i.cancel=!0;break;case 13:i.key=e.altKey?$.ESC+$.CR:$.CR,i.cancel=!0;break;case 27:i.key=$.ESC,e.altKey&&(i.key=$.ESC+$.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`D`:t?$.ESC+`OD`:$.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`C`:t?$.ESC+`OC`:$.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`A`:t?$.ESC+`OA`:$.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`B`:t?$.ESC+`OB`:$.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=$.ESC+`[2~`);break;case 46:i.key=a?$.ESC+`[3;`+(a+1)+`~`:$.ESC+`[3~`;break;case 36:i.key=a?$.ESC+`[1;`+(a+1)+`H`:t?$.ESC+`OH`:$.ESC+`[H`;break;case 35:i.key=a?$.ESC+`[1;`+(a+1)+`F`:t?$.ESC+`OF`:$.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?$.ESC+`[5;`+(a+1)+`~`:$.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?$.ESC+`[6;`+(a+1)+`~`:$.ESC+`[6~`;break;case 112:i.key=a?$.ESC+`[1;`+(a+1)+`P`:$.ESC+`OP`;break;case 113:i.key=a?$.ESC+`[1;`+(a+1)+`Q`:$.ESC+`OQ`;break;case 114:i.key=a?$.ESC+`[1;`+(a+1)+`R`:$.ESC+`OR`;break;case 115:i.key=a?$.ESC+`[1;`+(a+1)+`S`:$.ESC+`OS`;break;case 116:i.key=a?$.ESC+`[15;`+(a+1)+`~`:$.ESC+`[15~`;break;case 117:i.key=a?$.ESC+`[17;`+(a+1)+`~`:$.ESC+`[17~`;break;case 118:i.key=a?$.ESC+`[18;`+(a+1)+`~`:$.ESC+`[18~`;break;case 119:i.key=a?$.ESC+`[19;`+(a+1)+`~`:$.ESC+`[19~`;break;case 120:i.key=a?$.ESC+`[20;`+(a+1)+`~`:$.ESC+`[20~`;break;case 121:i.key=a?$.ESC+`[21;`+(a+1)+`~`:$.ESC+`[21~`;break;case 122:i.key=a?$.ESC+`[23;`+(a+1)+`~`:$.ESC+`[23~`;break;case 123:i.key=a?$.ESC+`[24;`+(a+1)+`~`:$.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=$.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=$.DEL:e.keyCode===219?i.key=$.ESC:e.keyCode===220?i.key=$.FS:e.keyCode===221&&(i.key=$.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=dq[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=$.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=$.ESC+n}else if(e.keyCode===32)i.key=$.ESC+(e.ctrlKey?$.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=$.ESC+t,i.cancel=!0}}else n&&!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=$.US),e.key===`@`&&(i.key=$.NUL))}return i}var pq=0,mq=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new eG,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new eG,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((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,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||(pq=this._search(t),pq===-1)||this._getKey(this._array[pq])!==t)return!1;do if(this._array[pq]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(pq),!0;while(++pqe-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(pq=this._search(e),!(pq<0||pq>=this._array.length)&&this._getKey(this._array[pq])===e))do yield this._array[pq];while(++pq=this._array.length)&&this._getKey(this._array[pq])===e))do t(this._array[pq]);while(++pq=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},hq=0,gq=0,_q=class extends nV{constructor(){super(),this._decorations=new mq(e=>e?.marker.line),this._onDecorationRegistered=this._register(new CV),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new CV),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register($B(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new vq(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.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,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e{hq=t.options.x??0,gq=hq+(t.options.width??1),e>=hq&&e=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_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)}},xq=20,Sq=class extends nV{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,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 e=0;ethis._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,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 bq(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` -`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(JH(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register($B(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` -`&&(this._liveRegionLineCount++,this._liveRegionLineCount===xq+1&&(this._liveRegion.textContent+=Wz.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 n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}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},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,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 r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(!(!a||!o)){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;ee;)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{ZB(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(JH(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(JH(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(JH(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(JH(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 n=e.composedPath();for(let e=0;e{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;re?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;tthis._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;ethis._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&wq(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,ZB(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||e.link.decorations.underline,pointerCursor:e.link.decorations===void 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:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){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(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){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(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};Cq=zz([Bz(1,DB),Bz(2,OB),Bz(3,pB),Bz(4,MB)],Cq);function wq(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 Tq=class extends uq{constructor(e={}){super(e),this._linkifier=this._register(new rV),this.browser=LW,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new rV),this._onCursorMove=this._register(new CV),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new CV),this.onKey=this._onKey.event,this._onRender=this._register(new CV),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new CV),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new CV),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new CV),this.onBell=this._onBell.event,this._onFocus=this._register(new CV),this._onBlur=this._register(new CV),this._onA11yCharEmitter=this._register(new CV),this._onA11yTabEmitter=this._register(new CV),this._onWillOpen=this._register(new CV),this._setup(),this._decorationService=this._instantiationService.createInstance(_q),this._instantiationService.setService(SB,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(MW),this._instantiationService.setService(MB,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(CB)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(uV.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(uV.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(uV.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(uV.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register($B(()=>{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 e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=eW.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${$.ESC}]${n};${JK(r)}${KU.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=$U.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=$U.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_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(Sq,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.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($.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 n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(JH(this.element,`copy`,e=>{this.hasSelection()&&qz(e,this._selectionService)}));let e=e=>Jz(e,this.textarea,this.coreService,this.optionsService);this._register(JH(this.textarea,`paste`,e)),this._register(JH(this.element,`paste`,e)),VW?this._register(JH(this.element,`mousedown`,e=>{e.button===2&&Zz(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(JH(this.element,`contextmenu`,e=>{Zz(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),YW&&this._register(JH(this.element,`auxclick`,e=>{e.button===1&&Xz(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(JH(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(JH(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(JH(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(JH(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(JH(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(JH(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(JH(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw 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(JH(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,Hz.get()),XW||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`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(AW,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(EB,this._coreBrowserService),this._register(JH(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(JH(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(EW,this._document,this._helperContainer),this._instantiationService.setService(TB,this._charSizeService),this._themeService=this._instantiationService.createInstance(PG),this._instantiationService.setService(jB,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(sW),this._instantiationService.setService(AB,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(nG,this.rows,this.screenElement)),this._instantiationService.setService(OB,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(qU,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(FW),this._instantiationService.setService(DB,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Cq,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(RU,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(wG,this.element,this.screenElement,r)),this._instantiationService.setService(kB,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(uV.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(zU,this.screenElement)),this._register(JH(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),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(Sq,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(WU,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(WU,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(TW,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),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()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(JH(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(e)))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(JH(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=$.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!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){Yz(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 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 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,n){this._selectionService.setSelection(e,t,n)}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 n=fq(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.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((n.key===$.ETX||n.key===$.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=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`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Eq(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=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new oB)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},kq=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 Oq(t)}getNullCell(){return new oB}},Aq=class extends nV{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new CV),this.onBufferChange=this._onBufferChange.event,this._normal=new kq(this._core.buffers.normal,`normal`),this._alternate=new kq(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},jq=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,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)}},Mq=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}},Nq=[`cols`,`rows`],Pq=0,Fq=class extends nV{constructor(e){super(),this._core=this._register(new Tq(e)),this._addonManager=this._register(new Dq),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(Nq.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get 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||=new jq(this._core),this._parser}get unicode(){return this._checkProposedApi(),new Mq(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._register(new Aq(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`}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,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}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 -`,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 Hz.get()},set promptLabel(e){Hz.set(e)},get tooMuchOutput(){return Wz.get()},set tooMuchOutput(e){Wz.set(e)}}}_verifyIntegers(...e){for(Pq of e)if(Pq===1/0||isNaN(Pq)||Pq%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(Pq of e)if(Pq&&(Pq===1/0||isNaN(Pq)||Pq%1!=0||Pq<0))throw Error(`This API only accepts positive integers`)}};function Iq(){return{background:`#101316`,foreground:`#d7dde3`,cursor:`#7db8ff`,selectionBackground:`#365b8a`,black:`#1d2227`,red:`#ff7b72`,green:`#56d364`,yellow:`#e3b341`,blue:`#79c0ff`,magenta:`#d2a8ff`,cyan:`#39c5cf`,white:`#e6edf3`,brightBlack:`#6e7681`,brightRed:`#ffa198`,brightGreen:`#7ee787`,brightYellow:`#f2cc60`,brightBlue:`#a5d6ff`,brightMagenta:`#d2a8ff`,brightCyan:`#56d4dd`,brightWhite:`#ffffff`}}function Lq({sessionId:e,cwd:t,tabId:n,active:r=!0,onConnectionChange:i}){let{t:a}=cr(),o=(0,_.useMemo)(()=>new rf,[]),s=wk(),c=n?s?.terminals?.[n]:s?.terminal,l=t.replace(/[\\/]+$/u,``).split(/[\\/]/u).pop()||t,u=(0,_.useRef)(r);u.current=r;let d=(0,_.useRef)(null),f=(0,_.useRef)(null),p=(0,_.useRef)(c?.id??null),[m,h]=(0,_.useState)(`connecting`),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(null),[x,S]=(0,_.useState)(!1),[C,T]=(0,_.useState)(!1),[E,D]=(0,_.useState)(0),O=(0,_.useRef)(null),k=(0,_.useRef)(null),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(null),I=(0,_.useRef)(i);I.current=i,(0,_.useEffect)(()=>{I.current?.({id:p.current,pending:[`connecting`,`reconnecting`,`restarting`].includes(m)})},[m]),(0,_.useEffect)(()=>{let r=d.current;if(!r)return;let i=n?s?.terminals?.[n]:s?.terminal;p.current??=i?.id??null;let c=!1,l=!1,m=!1,g=!1,_,y=!1,x=Promise.resolve(void 0),C=null,w=new AbortController;h(`connecting`),v(null),b(null),S(!1),T(!1),j(!1),N(!1),F(null);let D=new Fq({cursorBlink:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace`,fontSize:13,lineHeight:1.25,scrollback:8e3,screenReaderMode:!0,disableStdin:!0,theme:Iq()}),A=i?{...i}:void 0,M=new Fz;D.loadAddon(M),D.open(r);let P=f.current;f.current=null,!r.closest(`[hidden], [inert]`)&&(E===0||r.closest(`.interactive-terminal`)?.contains(document.activeElement)||P?.sessionId===e&&P.cwd===t&&P.generation===E&&document.activeElement===document.body)&&D.focus(),D.attachCustomKeyEventHandler(e=>{if(e.type!==`keydown`)return!0;let t=e.key.toLowerCase();return t===`escape`&&e.stopPropagation(),!((e.ctrlKey||e.metaKey)&&t===`v`||(e.ctrlKey||e.metaKey)&&t===`c`&&D.hasSelection())});let I=e=>!c&&w===e&&!e.signal.aborted,L=()=>{m=!1,y=!0,C=null,D.options.disableStdin=!0,w.abort()},R=e=>{c||(L(),v(e instanceof Error?e.message:a(`terminalError`)),h(`error`))},ee=e=>{if(y||c)return;let t=w;x=x.then(()=>{if(I(t)&&!y&&m&&!l)return e()}).catch(e=>{I(t)&&R(e)})},z=t=>{let n=p.current;if(!(!n||!u.current||!m||l||y))for(let r of t.match(/[\s\S]{1,32768}/gu)??[]){if(C&&C.data.length+r.length<=65536){C.data+=r;continue}let t={data:r};C=t,ee(async()=>{C===t&&(C=null),await o.writeInteractiveTerminal(e,n,t.data)})}},B=(t,n)=>{let r=p.current;!r||!m||l||y||(C=null,ee(()=>o.resizeInteractiveTerminal(e,r,t,n)))},V=()=>{if(!(!r.offsetWidth||!r.offsetHeight))try{M.fit()}catch{}},H=(e=D.buffer.active.viewportY)=>{let t=e>=D.buffer.active.baseY;S(!t);let r=p.current;if(s&&r&&!A){let i={...n?s.terminals?.[n]:s.terminal,id:r,viewport:e,atBottom:t};n?(s.terminals??={})[n]=i:s.terminal=i}},te=e=>{if(!c){if(e.type===`output`){if(e.reset)D.reset(),_!==void 0&&T(!0);else if(_!==void 0&&e.offset<=_)return;D.write(e.data,()=>{c||(A&&=(A.atBottom?D.scrollToBottom():D.scrollToLine(A.viewport),void 0),H())}),_=e.offset;return}l=!0,m=!1,D.options.disableStdin=!0,w.abort(),b(e.type===`exit`?e.exitCode:null),h(`exited`)}},ne=D.onData(z),re=D.onScroll(H),ie=D.onResize(({cols:e,rows:t})=>B(e,t)),ae=typeof ResizeObserver>`u`?void 0:new ResizeObserver(V);ae?.observe(r);let U=async()=>{if(c||g||m)return;g=!0,L();let r=new AbortController;w=r,x=Promise.resolve();let i=p.current;h(i?`reconnecting`:`connecting`),v(null),V();try{let c=i?await o.interactiveTerminal(e,i,r.signal):await o.createInteractiveTerminal(e,D.cols,D.rows,r.signal,n?`${n}:${E}`:void 0);if(!I(r))return;if(!c.id||c.sessionId!==e||c.cwd!==t||i&&c.id!==i)throw Error(a(`inspectionChanged`));if(g=!1,p.current=c.id,s){let e={viewport:0,atBottom:!0,...n?s.terminals?.[n]:s.terminal,id:c.id};n?(s.terminals??={})[n]=e:s.terminal=e}l=c.exited,m=!c.exited,y=c.exited,D.options.disableStdin=c.exited,h(c.exited?`exited`:`ready`),b(c.exitCode),V(),c.exited||B(D.cols,D.rows),await o.streamInteractiveTerminal(e,c.id,_,r.signal,e=>{I(r)&&te(e)}),I(r)&&!l&&R(Error(a(`terminalDisconnected`)))}catch(e){I(r)&&R(e)}finally{w===r&&(g=!1)}},oe={reconnect:()=>{U()},suspend:L,scrollToBottom:()=>{c||(D.scrollToBottom(),D.focus())}};return O.current=oe,U(),()=>{c=!0,L(),O.current===oe&&(O.current=null),k.current===oe&&(k.current=null),ae?.disconnect(),ne.dispose(),re.dispose(),ie.dispose(),x.catch(()=>void 0),D.dispose(),p.current=null}},[o,t,E,e,a,s,n]);let L=async r=>{let i=O.current;if(!i||k.current)return;k.current=i,N(!0),F(null),h(`restarting`),v(null),i.suspend();let c=p.current;try{if(c&&await o.closeInteractiveTerminal(e,c),O.current!==i)return;if(p.current=null,s)if(n){let e=s.terminals?.[n]?.title;(s.terminals??={})[n]={viewport:0,atBottom:!0,title:e}}else s.terminal=void 0;r&&(f.current={sessionId:e,cwd:t,generation:E+1}),j(!1),D(e=>e+1)}catch(e){if(O.current===i){let t=e instanceof Error?e.message:a(`terminalError`);v(t),F(t),h(`error`),k.current=null,N(!1)}}};return(0,K.jsxs)(`section`,{className:`interactive-terminal`,"aria-label":a(`terminal`),children:[(0,K.jsxs)(`header`,{className:`interactive-terminal-status`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{className:`terminal-status-dot ${m}`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`terminal-cwd`,title:t,children:l}),m===`ready`&&(0,K.jsx)(`span`,{className:`terminal-connection-state`,children:a(`connected`)})]}),(0,K.jsxs)(`div`,{className:`interactive-terminal-actions`,children:[m===`error`&&(0,K.jsxs)(`button`,{type:`button`,"aria-label":a(`reconnectTerminal`),title:a(`reconnectTerminal`),className:`terminal-reconnect-action`,disabled:M,onClick:()=>O.current?.reconnect(),children:[(0,K.jsx)(dt,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:a(`reconnectTerminal`)})]}),(0,K.jsx)(`button`,{type:`button`,"aria-label":a(`restartTerminal`),title:a(`restartTerminal`),disabled:M||m===`connecting`||m===`reconnecting`,onClick:()=>{F(null),j(!0)},children:(0,K.jsx)(ft,{"aria-hidden":`true`})})]})]}),(0,K.jsxs)(`div`,{className:`interactive-terminal-notice`,"aria-live":`polite`,children:[g?(0,K.jsx)(`span`,{className:`error`,children:g}):m===`exited`?(0,K.jsx)(`span`,{children:y===null?a(`terminalExited`):a(`terminalExitCode`,{code:y})}):m===`connecting`?(0,K.jsx)(`span`,{children:a(`terminalConnecting`)}):m===`reconnecting`?(0,K.jsx)(`span`,{children:a(`terminalReconnecting`)}):m===`restarting`?(0,K.jsx)(`span`,{children:a(`terminalRestarting`)}):null,C&&(0,K.jsx)(`span`,{className:`terminal-output-resynced`,children:a(`terminalOutputResynced`)})]}),(0,K.jsxs)(`div`,{className:`interactive-terminal-viewport`,children:[(0,K.jsx)(`div`,{ref:d,className:`interactive-terminal-host`}),x&&(0,K.jsxs)(`button`,{type:`button`,className:`terminal-scroll-bottom`,onClick:()=>O.current?.scrollToBottom(),children:[(0,K.jsx)(w,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:a(`terminalScrollToBottom`)})]})]}),(0,K.jsx)($j,{isOpen:A,purpose:`form`,width:430,"aria-label":a(`restartTerminalTitle`),onOpenChange:e=>{!e&&!k.current&&j(!1)},children:(0,K.jsxs)(`form`,{className:`openpi-dialog`,"aria-busy":M,onSubmit:e=>{e.preventDefault(),L(e.currentTarget.contains(document.activeElement))},children:[(0,K.jsx)(`strong`,{children:a(`restartTerminalTitle`)}),(0,K.jsx)(`p`,{children:a(`restartTerminalDetail`)}),P&&(0,K.jsx)(`p`,{className:`terminal-restart-error`,role:`alert`,children:P}),(0,K.jsxs)(`div`,{className:`dialog-actions`,children:[(0,K.jsx)(`button`,{type:`button`,disabled:M,onClick:()=>{k.current||j(!1)},children:a(`cancel`)}),(0,K.jsx)(`button`,{type:`submit`,className:`danger`,disabled:M,children:a(M?`terminalRestarting`:`restartTerminal`)})]})]})},`${e}:${t}`)]})}function Rq(e){return e.startsWith(`terminal:`)?`terminal`:e}function zq(e){return e===`launcher`?{tabs:[],active:null,launcherOpen:!0,activationHistory:[]}:{tabs:[e],active:e,launcherOpen:!1,activationHistory:[e]}}function Bq(e,t){return t===`launcher`?{...e,launcherOpen:!0}:{tabs:e.tabs.includes(t)?e.tabs:[...e.tabs,t],active:t,launcherOpen:!1,activationHistory:[...e.activationHistory.filter(e=>e!==t),t]}}function Vq(e,t){return e.tabs.includes(t)?Bq(e,t):e}function Hq(e,t){if(!e.tabs.includes(t))return e;let n=e.tabs.filter(e=>e!==t),r=e.activationHistory.filter(e=>e!==t);if(e.active!==t)return{...e,tabs:n,activationHistory:r};let i=r.at(-1),a=e.tabs.indexOf(t),o=n[Math.min(a,n.length-1)],s=i??o??null;return{tabs:n,active:s,launcherOpen:e.launcherOpen||s===null,activationHistory:r}}function Uq(e){return{...e,launcherOpen:e.active===null}}var Wq=[{kind:`side-conversation`,icon:qe,title:`sideConversation`,description:`sideConversationDescription`},{kind:`review`,icon:ye,title:`changeEvidence`,description:`workbarChangesDescription`},{kind:`terminal`,icon:Tt,title:`terminal`,description:`workbarTerminalDescription`},{kind:`browser`,icon:me,title:`browser`,description:`workbarBrowserDescription`},{kind:`files`,icon:G,title:`files`,description:`workbarFilesDescription`}];function Gq({onSelect:e}){let{t}=cr();return(0,K.jsx)(`section`,{className:`workbar-launcher`,"aria-label":t(`openTools`),children:(0,K.jsx)(`div`,{className:`workbar-launcher-list`,children:Wq.map(n=>{let r=n.icon;return(0,K.jsxs)(`button`,{type:`button`,onClick:()=>e(n.kind),children:[(0,K.jsx)(r,{"aria-hidden":`true`}),(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`strong`,{children:t(n.title)}),(0,K.jsx)(`small`,{children:t(n.description)})]}),(0,K.jsx)(ee,{"aria-hidden":`true`})]},n.kind)})})})}function Kq({sessionId:e,cwd:t,snapshot:n,activity:r}){let{t:i}=cr(),a=(0,_.useMemo)(()=>new rf,[]),o=wk(),[s,c]=(0,_.useState)(o?.sideConversation?.selectedId??null),[l,u]=(0,_.useState)(o?.sideConversation?.drafts??{});(0,_.useLayoutEffect)(()=>{o&&(o.sideConversation={selectedId:s,drafts:l})},[o,s,l]);let d=l[s??``]??``,f=(0,_.useRef)(0),[p,m]=(0,_.useState)(null),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(!1),b=(0,_.useRef)(!1),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(0),[E,D]=(0,_.useState)(null),O=(0,_.useRef)(null);(0,_.useEffect)(()=>()=>O.current?.abort(),[]);let A=(r?.items??[]).filter(e=>e.origin===`btw`),j=A.find(e=>e.id===s),M=j?.status??E,N=p?.id===s?p:null,P=n?.models.find(e=>s?`${e.provider}/${e.id}`===N?.model:e.current),F=s?N?.model:P&&`${P.provider}/${P.id}`,I=P?.name||P?.id||F||i(`usageUnknown`),L=!s&&n?.thinking?.supported?n.thinking.level:void 0,R=N?.cwd??t,z=n?.workspaces.find(e=>e.path===R)?.name??QA(R),B=i(s?`continueSideConversation`:`startSideConversation`),V=i(v?`sideConversationPending`:s?`send`:`start`),H=e=>{f.current++,c(e),D(null),S(null),g(null)},te=async t=>{t.preventDefault();let n=d.trim();if(!n||b.current)return;b.current=!0,O.current?.abort();let r=new AbortController,o=f.current,l=s??``;O.current=r,y(!0),S(null);try{let t=await a.subagentAction(e,s?{kind:`subagents`,action:`send-btw`,id:s,text:n}:{kind:`subagents`,action:`spawn-btw`,prompt:n},r.signal);if(r.signal.aborted)return;if(t.sessionId!==e||s&&t.detail.id!==s)throw Error(i(`inspectionChanged`));if(u(e=>e[l]===d?{...e,[l]:``}:e),o!==f.current)return;c(t.detail.id),D(t.detail.status),w(e=>e+1)}catch(e){!r.signal.aborted&&o===f.current&&S(e instanceof Error?e.message:i(`inspectionUnavailable`))}finally{r.signal.aborted||(b.current=!1,y(!1))}},ne=async()=>{if(!s||b.current)return;b.current=!0,O.current?.abort();let t=new AbortController,n=f.current;O.current=t,y(!0),S(null);try{let r=await a.subagentAction(e,{kind:`subagents`,action:`cancel-btw`,id:s},t.signal);if(t.signal.aborted||n!==f.current)return;if(r.sessionId!==e||r.detail.id!==s)throw Error(i(`inspectionChanged`));D(r.detail.status),w(e=>e+1)}catch(e){!t.signal.aborted&&n===f.current&&S(e instanceof Error?e.message:i(`inspectionUnavailable`))}finally{t.signal.aborted||(b.current=!1,y(!1))}};return(0,K.jsxs)(`div`,{className:`side-conversation-body`,children:[s?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`button`,{type:`button`,className:`workbar-back`,onClick:()=>H(null),children:[(0,K.jsx)(T,{"aria-hidden":`true`}),` `,i(`backToSideConversations`)]}),(0,K.jsx)(JI,{sessionId:e,id:s,activity:j,client:a,liveAvailable:!0,refreshRevision:C,fullView:!1,readOnlyNote:!1,onDetail:e=>m({id:e.id,cwd:e.cwd,model:e.model})},`${e}:${s}`)]}):(0,K.jsxs)(`div`,{className:`side-conversation-list`,"data-empty":A.length===0,children:[(0,K.jsxs)(`div`,{className:`side-conversation-intro`,children:[(0,K.jsx)(qe,{"aria-hidden":`true`}),(0,K.jsx)(`h3`,{children:i(`sideConversation`)}),(0,K.jsx)(`p`,{children:i(`sideConversationDescription`)})]}),A.length>0&&(0,K.jsx)(`ul`,{children:A.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsxs)(`button`,{type:`button`,onClick:()=>H(e.id),children:[(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`strong`,{children:e.title||e.id}),(0,K.jsx)(`small`,{children:i(`subagentState_${e.status}`)})]}),(0,K.jsx)(ee,{"aria-hidden":`true`})]})},e.id))})]}),x&&(0,K.jsx)(`p`,{className:`workbar-error`,role:`alert`,children:x}),(0,K.jsx)(`div`,{className:`composer-dock`,children:(0,K.jsxs)(`form`,{className:`composer composer-m02 side-conversation-composer`,onSubmit:te,"aria-busy":v,children:[(0,K.jsx)(`textarea`,{rows:1,value:d,disabled:v,"aria-label":B,placeholder:B,onChange:e=>{let t=e.currentTarget.value;u(e=>({...e,[s??``]:t}))},onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.defaultPrevented&&!e.nativeEvent.isComposing&&e.nativeEvent.keyCode!==229&&(e.preventDefault(),e.currentTarget.form?.requestSubmit())}}),(0,K.jsxs)(`div`,{className:`composer-toolbar`,children:[(0,K.jsxs)(`div`,{className:`composer-toolbar-context`,children:[(0,K.jsx)(`button`,{type:`button`,className:`composer-context-trigger icon-button`,"aria-label":i(`addContext`),title:i(`fileReference`),disabled:v,onClick:()=>g({key:s??``,generation:f.current}),children:(0,K.jsx)(lt,{"aria-hidden":`true`})}),(0,K.jsxs)(`span`,{className:`composer-workspace-label`,title:R,children:[(0,K.jsx)(De,{"aria-hidden":`true`}),` `,z]})]}),(0,K.jsxs)(`div`,{className:`composer-toolbar-controls`,children:[(0,K.jsx)(`div`,{className:`model-picker-wrap`,children:(0,K.jsx)($M,{className:`model-selector model-picker`,label:`${i(`model`)}: ${I}`,isLabelHidden:!0,value:F??``,triggerLabel:(0,K.jsxs)(`span`,{className:`model-thinking-label`,title:F||I,children:[(0,K.jsx)(`span`,{className:`model-picker-label`,children:I}),L&&(0,K.jsx)(`span`,{className:`model-picker-thinking`,children:L[0].toUpperCase()+L.slice(1)})]}),variant:`ghost`,size:`sm`,placement:`above`,alignment:`end`,isDisabled:!F,children:()=>(0,K.jsxs)(`div`,{className:`side-conversation-model-details`,children:[(0,K.jsx)(`strong`,{children:I}),(0,K.jsx)(`code`,{children:F}),(0,K.jsx)(`p`,{children:i(s?`sideConversationModelFixed`:`sideConversationModelInherited`)})]})},s??`new`)}),s&&M===`running`&&(0,K.jsx)(`button`,{type:`button`,className:`send-button`,"aria-label":i(`stop`),title:i(`stop`),disabled:v,onClick:()=>void ne(),children:(0,K.jsx)(Et,{"aria-hidden":`true`})}),(!s||M!==`running`||!!d.trim())&&(0,K.jsx)(`button`,{type:`submit`,className:`send-button`,disabled:v||!d.trim(),"aria-label":V,title:V,children:(0,K.jsx)(k,{"aria-hidden":`true`})})]})]})]})}),(0,K.jsx)(JM,{open:h!==null,sessionId:e,onClose:()=>g(null),onInsert:e=>{if(!h||h.generation!==f.current||h.key!==(s??``)||b.current)return i(`fileReferenceDraftChanged`);let t=h.key;u(n=>({...n,[t]:`${n[t]??``}${n[t]?` -`:``}${YM(e)}`}))}})]})}function qq({sessionId:e,cwd:t,activity:n,tabId:r,active:i,onConnectionChange:a}){let{t:o}=cr(),s=n?.items??[];return(0,K.jsxs)(`div`,{className:`terminal-workspace`,children:[(0,K.jsx)(Lq,{sessionId:e,cwd:t,tabId:r,active:i,onConnectionChange:a}),s.length>0&&(0,K.jsxs)(`details`,{className:`terminal-agent-activity`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(Tt,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:o(`backgroundTerminalActivity`)}),(0,K.jsx)(`small`,{children:s.length}),(0,K.jsx)(ee,{"aria-hidden":`true`})]}),(0,K.jsx)(`ul`,{children:s.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`strong`,{children:e.title||e.id}),(0,K.jsx)(`small`,{children:o(`execution_${e.status}`,{defaultValue:e.status})})]})},e.id))})]})]})}function Jq({visible:e,requestedTool:t,requestRevision:n,sessionId:r,sessionPath:i,cwd:a,snapshot:o,capabilities:s,review:c,reviewInitialFilePath:l,reviewTurn:u,onWorkspaceReview:d,conversationCollapsed:f,onRestoreConversation:p,onExpandReview:m,onClose:h,onActiveToolChange:g,canControl:v=!0,onActivateSession:y,readingState:b,onReferenceLine:x,onBrowserReady:S}){let{t:C}=cr(),w=(0,_.useRef)({}),E=b??w.current;E.terminal&&!E.terminals?.terminal&&((E.terminals??={}).terminal=E.terminal,E.terminal=void 0);let[D,O]=(0,_.useState)(()=>E?.tabs?E.requestRevision===n?E.tabs:Bq(E.tabs,t):zq(t)),k=JSON.stringify([r,i]),A=(0,_.useRef)(new Map),j=(0,_.useRef)(null),M=(0,_.useRef)(null),N=(0,_.useRef)(null),P=(0,_.useMemo)(()=>new rf,[]),[F,I]=(0,_.useState)({}),[L,R]=(0,_.useState)([]),ee=(0,_.useRef)(new Set),z=(0,_.useRef)(0);(0,_.useEffect)(()=>()=>{z.current++},[]);let[B,V]=(0,_.useState)(null),[H,te]=(0,_.useState)(null),[ne,re]=(0,_.useState)(``),[ie,ae]=(0,_.useState)(()=>Object.fromEntries(Object.entries(E.terminals??{}).flatMap(([e,t])=>t.title?[[e,t.title]]:[]))),U=e=>ie[e]??(e===`terminal`?C(`terminal`):`${C(`terminal`)} ${D.tabs.filter(e=>Rq(e)===`terminal`).indexOf(e)+1}`);(0,_.useLayoutEffect)(()=>{let t=N.current;if(N.current=null,!t||t.scope!==k||!e||(t.tool?D.launcherOpen||D.active!==t.tool:!D.launcherOpen))return;let n=requestAnimationFrame(()=>{let e=t.tool?A.current.get(t.tool):j.current;!e?.isConnected||e.closest(`[hidden], [inert]`)||document.activeElement!==document.body&&!e.closest(`.workbar-panel`)?.contains(document.activeElement)&&!document.getElementById(j.current?.getAttribute(`aria-controls`)??``)?.contains(document.activeElement)||e.focus({preventScroll:!0})});return()=>cancelAnimationFrame(n)},[D,k,e]);let oe=e&&!D.launcherOpen&&D.active===`browser`&&v,[se,ce]=(0,_.useState)(null);(0,_.useLayoutEffect)(()=>{oe?ce(k):(!e||!v||!D.tabs.includes(`browser`)||se!==k)&&ce(null)},[oe,k,e,v,D,se]),(0,_.useLayoutEffect)(()=>{E&&(E.tabs=D,E.requestRevision=n)},[E,D,n]);let le=Oz(r,i,a,u?.promptEntryId),ue=(0,_.useRef)(n);(0,_.useEffect)(()=>(g?.(e?D.launcherOpen?`launcher`:D.active?Rq(D.active):null:null),()=>g?.(null)),[e,D.launcherOpen,D.active,g]),(0,_.useEffect)(()=>{ue.current!==n&&(ue.current=n,O(e=>Bq(e,t)))},[n,t]);let de=e=>{let t=e===`terminal`&&D.tabs.some(e=>Rq(e)===`terminal`)?`terminal:${crypto.randomUUID()}`:e;if(t!==`launcher`&&(N.current={tool:t,scope:k}),t.startsWith(`terminal:`)){let e=Math.max(1,...Object.values(ie).map(e=>Number(e.match(/\s(\d+)$/u)?.[1])||0))+1,n=`${C(`terminal`)} ${e}`;ae(e=>({...e,[t]:n})),(E.terminals??={})[t]={viewport:0,atBottom:!0,title:n}}O(e=>Bq(e,t))},fe=async(e,t)=>{let n=z.current,i=t.contains(document.activeElement);if(Rq(e)===`terminal`&&v){if(ee.current.has(e)||F[e]?.pending)return;let t=F[e]?.id??E.terminals?.[e]?.id;if(t){ee.current.add(e),R(t=>[...t,e]),V(null);try{await P.closeInteractiveTerminal(r,t)}catch(e){n===z.current&&V(e instanceof Error?e.message:C(`terminalError`));return}finally{n===z.current&&(ee.current.delete(e),R(t=>t.filter(t=>t!==e)))}if(n!==z.current)return}}Rq(e)===`terminal`&&E.terminals&&delete E.terminals[e],O(n=>{let r=Hq(n,e);return(t.contains(document.activeElement)||i&&document.activeElement===document.body)&&(N.current={tool:r.launcherOpen?null:r.active,scope:k}),r})},pe=D.active?Rq(D.active):null,me=D.launcherOpen?`openTools`:Wq.find(e=>e.kind===pe)?.title??`openTools`;return Ki({isActive:e,onDismiss:()=>{D.launcherOpen&&D.active?(N.current={tool:D.active,scope:k},O(Uq)):h()},getContainer:()=>M.current,isPresent:()=>M.current?.contains(document.activeElement)??!1}),(0,K.jsx)(Ck.Provider,{value:E,children:(0,K.jsx)(Ti,{children:(0,K.jsxs)(`aside`,{ref:M,className:`workbar-panel`,hidden:!e,"aria-label":C(me??`openTools`),children:[(0,K.jsxs)(`header`,{className:`workbar-tabbar`,children:[(0,K.jsxs)(`div`,{className:`workbar-tabs`,role:`toolbar`,"aria-label":C(`openTools`),children:[D.tabs.length===0&&(0,K.jsxs)(`span`,{className:`workbar-tab-placeholder`,children:[(0,K.jsx)(lt,{"aria-hidden":`true`}),` `,C(`openTools`)]}),D.tabs.map(e=>{let t=Rq(e),n=Wq.find(e=>e.kind===t),r=n.icon,i=!D.launcherOpen&&D.active===e,a=t===`terminal`?U(e):C(n.title),o=()=>{t===`terminal`&&(re(a),te(e))};return(0,K.jsxs)(`div`,{className:`workbar-tab`,"data-active":i||void 0,children:[(0,K.jsxs)(`button`,{type:`button`,ref:t=>{t?A.current.set(e,t):A.current.delete(e)},"aria-pressed":i,title:t===`terminal`?`${a} · ${C(`renameTerminal`)}`:a,onDoubleClick:o,onContextMenu:e=>{t===`terminal`&&(e.preventDefault(),o())},onKeyDown:e=>{t===`terminal`&&e.key===`F2`&&(e.preventDefault(),o())},onClick:()=>O(t=>Vq(t,e)),children:[(0,K.jsx)(r,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:a})]}),(0,K.jsx)(`button`,{type:`button`,className:`workbar-tab-close`,"aria-label":t===`terminal`&&v?C(`workbarEndTerminal`,{name:a}):`${C(`close`)} ${a}`,title:t===`terminal`&&v?C(`workbarEndTerminal`,{name:a}):`${C(`close`)} ${a}`,disabled:t===`terminal`&&v&&(L.includes(e)||F[e]?.pending!==!1),onClick:t=>void fe(e,t.currentTarget),children:(0,K.jsx)(Lt,{"aria-hidden":`true`})})]},e)})]}),(0,K.jsxs)(`div`,{className:`workbar-tabbar-actions`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`workbar-back-to-chat`,onClick:()=>{f?p():h(),requestAnimationFrame(()=>document.querySelector(`.composer textarea`)?.focus({preventScroll:!0}))},children:[(0,K.jsx)(T,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:C(`workbarBackToChat`)})]}),!f&&D.active===`review`&&m&&(0,K.jsx)(`button`,{type:`button`,className:`icon-button review-expand`,"aria-label":C(`gitReviewExpand`),title:C(`gitReviewExpand`),onClick:m,children:(0,K.jsx)(nt,{"aria-hidden":`true`,style:{transform:`rotate(180deg)`}})}),D.active?(0,K.jsx)(jA,{className:`workbar-tool-picker`,button:{ref:j,className:`icon-button workbar-add-tab`,icon:(0,K.jsx)(lt,{"aria-hidden":`true`}),label:C(`openTools`),isIconOnly:!0,variant:`ghost`,"aria-label":C(`openTools`),tooltip:C(`openTools`)},onOpenChange:e=>{e||(N.current??={tool:D.active,scope:k},O(Uq))},items:Wq.map(e=>({id:e.kind,icon:(0,K.jsx)(e.icon,{"aria-hidden":`true`}),label:C(e.kind===`terminal`?`workbarNewTerminal`:e.title),description:C(e.description),onClick:()=>de(e.kind)})),menuWidth:`min(300px, calc(100vw - 24px))`,alignment:`end`,hasChevron:!1}):(0,K.jsx)(`button`,{type:`button`,ref:j,className:`icon-button workbar-add-tab`,"aria-label":C(`openTools`),title:C(`openTools`),"aria-pressed":D.launcherOpen,onClick:()=>O(e=>Bq(e,`launcher`)),children:(0,K.jsx)(lt,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{type:`button`,className:`icon-button`,"aria-label":C(`workbarCollapseTools`),title:C(`workbarCollapseTools`),onClick:h,children:(0,K.jsx)(rt,{"aria-hidden":`true`})})]})]}),B&&(0,K.jsx)(`p`,{className:`error`,role:`alert`,children:B}),(0,K.jsxs)(`div`,{className:`workbar-panels`,children:[(0,K.jsx)(`div`,{className:`workbar-tool-panel`,hidden:!D.launcherOpen,children:(0,K.jsx)(Gq,{onSelect:de})}),D.tabs.map(t=>{let n=Rq(t);return(0,K.jsx)(`div`,{className:`workbar-tool-panel`,"data-tool":n,"data-tab":t,hidden:D.launcherOpen||D.active!==t,inert:D.launcherOpen||D.active!==t||!e,children:n===`terminal`&&e&&v?(0,K.jsx)(qq,{sessionId:r,cwd:a,tabId:t,active:!D.launcherOpen&&D.active===t,onConnectionChange:e=>I(n=>({...n,[t]:e})),activity:s[`background-terminals`]}):n===`browser`&&e&&v&&(oe||se===k)?(0,K.jsx)(Mz,{onReady:S},k):e&&!D.launcherOpen&&D.active===t?!v&&[`side-conversation`,`terminal`,`browser`].includes(n)?(0,K.jsxs)(`div`,{className:`workbar-empty`,children:[(0,K.jsx)(`p`,{children:C(`toolsRequireCurrentSession`)}),y&&(0,K.jsx)(`button`,{type:`button`,className:`secondary`,onClick:y,children:C(`activateViewedSession`)})]}):n===`side-conversation`?(0,K.jsx)(Kq,{sessionId:r,cwd:a,snapshot:o,activity:s.subagents}):n===`review`?(0,K.jsx)(Dz,{review:u?{...le,setSource:e=>{c.setSource?.(e),d?.()}}:c,initialFilePath:u?.filePath??l,readingScope:u?`turn:${u.promptEntryId}:${u.revision}`:`workspace:${c.source??`unstaged`}`,onOpenFiles:()=>de(`files`),onReferenceLine:v?x:void 0,onClose:()=>O(e=>Hq(e,`review`)),embedded:!0},u?`${u.promptEntryId}:${u.revision}`:c.source??`workspace`):(0,K.jsx)(ZR,{sessionId:r,sessionPath:i,cwd:a,active:!0,canWrite:v},JSON.stringify([r,i,a])):null},t)})]}),(0,K.jsx)($j,{isOpen:H!==null,purpose:`form`,"aria-label":C(`renameTerminal`),onOpenChange:e=>{e||te(null)},children:(0,K.jsxs)(`form`,{className:`openpi-dialog`,onSubmit:e=>{e.preventDefault();let t=ne.trim();if(!H||!t)return;ae(e=>({...e,[H]:t}));let n=(E.terminals??={})[H];E.terminals[H]={...n??{viewport:0,atBottom:!0},title:t},te(null)},children:[(0,K.jsx)(`strong`,{children:C(`renameTerminal`)}),(0,K.jsx)(`input`,{"aria-label":C(`terminalName`),value:ne,maxLength:80,onChange:e=>re(e.target.value)}),(0,K.jsxs)(`div`,{className:`dialog-actions`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:()=>te(null),children:C(`cancel`)}),(0,K.jsx)(`button`,{type:`submit`,disabled:!ne.trim(),children:C(`save`)})]})]})})]})})})}var Yq=`openpi:workbar-positions:v1`;function Xq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zq(e,t=4096){return typeof e==`string`&&e.length<=t?e:``}function Qq(e,t=0,n=0,r=5e7){return typeof e==`number`&&Number.isFinite(e)&&e>=n&&e<=r?e:t}function $q(e,t=100){return Array.isArray(e)?e.slice(0,t).filter(e=>typeof e==`string`&&e.length<=4096):[]}function eJ(e){return WR(Zq(e),window.location.origin)}function tJ(e){return typeof e==`string`&&([`files`,`review`,`browser`,`terminal`,`side-conversation`].includes(e)||/^terminal:[a-zA-Z0-9-]{1,128}$/u.test(e))}function nJ(e){return typeof e==`string`&&[`launcher`,`files`,`review`,`browser`,`terminal`,`side-conversation`].includes(e)}function rJ(e){let t={};if(!Xq(e))return t;if(Xq(e.tabs)){let n=Array.isArray(e.tabs.tabs)?[...new Set(e.tabs.tabs.filter(tJ))].slice(0,16):[],r=tJ(e.tabs.active)&&n.includes(e.tabs.active)?e.tabs.active:null;t.tabs={tabs:n,active:r,launcherOpen:e.tabs.launcherOpen===!0||r===null,activationHistory:Array.isArray(e.tabs.activationHistory)?[...new Set(e.tabs.activationHistory.filter(tJ).filter(e=>n.includes(e)))].slice(-16):[]},t.requestRevision=Qq(e.requestRevision)}if(Xq(e.files)&&(t.files={selected:Zq(e.files.selected),treeVisible:e.files.treeVisible!==!1,query:Zq(e.files.query,200),expanded:$q(e.files.expanded),treeScroll:Qq(e.files.treeScroll)}),Xq(e.artifact)){t.artifact={reference:Zq(e.artifact.reference),source:e.artifact.source===!0,editing:!1,scroll:Qq(e.artifact.scroll)};let n=e.artifact.document;Xq(n)&&typeof n.revision==`string`&&/^[a-f0-9]{64}$/u.test(n.revision)&&(t.artifact.document={path:Zq(n.path),revision:n.revision,page:Math.floor(Qq(n.page,1,1,1e5)),...typeof n.scale==`number`?{scale:Qq(n.scale,1,.1,8)}:{}})}let n=e.review;Xq(n)&&(n.source===`unstaged`||n.source===`staged`||n.source===`branch`||n.source===`session`)&&(t.review={scope:Zq(n.scope),source:n.source,...typeof n.baseRef==`string`?{baseRef:Zq(n.baseRef,1024)}:{},selected:typeof n.selected==`string`?Zq(n.selected):null,query:Zq(n.query,200),collapsedDirectories:$q(n.collapsedDirectories),visibleFiles:Qq(n.visibleFiles,50,0,200),listScroll:Qq(n.listScroll),previewScroll:Qq(n.previewScroll)},Xq(n.viewed)&&typeof n.viewed.revision==`string`&&(t.review.viewed={revision:Zq(n.viewed.revision,128),paths:$q(n.viewed.paths,200)}));let r=e.browser;if(Xq(r)&&Array.isArray(r.tabs)){let e=new Set,n=r.tabs.flatMap(t=>{if(!Xq(t)||!Number.isSafeInteger(t.id)||typeof t.id!=`number`||t.id<0||t.id>5e7||e.has(t.id))return[];e.add(t.id);let n=eJ(t.initialUrl);return[{id:t.id,title:Zq(t.title,200),...n?{initialUrl:n}:{}}]}).slice(0,8),i={};for(let e of n){let t=Xq(r.pages)?r.pages[e.id]:void 0;if(!Xq(t))continue;let n=$q(t.history,32).flatMap(e=>eJ(e)??[]);i[e.id]={draft:eJ(t.draft)??``,history:n,index:n.length?Math.min(Math.floor(Qq(t.index)),n.length-1):-1}}t.browser={tabs:n,selected:n.some(e=>e.id===r.selected)?Number(r.selected):n[0]?.id??0,pages:i}}if(Xq(e.terminals)){t.terminals={};for(let[n,r]of Object.entries(e.terminals).slice(0,16))!tJ(n)||n!==`terminal`&&!n.startsWith(`terminal:`)||!t.tabs?.tabs.includes(n)||!Xq(r)||(t.terminals[n]={...typeof r.id==`string`?{id:Zq(r.id,128)}:{},...typeof r.title==`string`?{title:Zq(r.title,80)}:{},viewport:Qq(r.viewport),atBottom:r.atBottom!==!1})}return Xq(e.terminal)&&typeof e.terminal.id==`string`&&(t.terminal={id:Zq(e.terminal.id,128),viewport:Qq(e.terminal.viewport),atBottom:e.terminal.atBottom!==!1}),Xq(e.sideConversation)&&(t.sideConversation={selectedId:typeof e.sideConversation.selectedId==`string`?Zq(e.sideConversation.selectedId,128):null,drafts:{}}),t}function iJ(e){if(!Xq(e)||!Zq(e.sessionId,128)||!Zq(e.sessionPath)||!nJ(e.tool))return null;let t={sessionId:Zq(e.sessionId,128),sessionPath:Zq(e.sessionPath),tool:e.tool,open:e.open===!0,requestRevision:Qq(e.requestRevision),reading:rJ(e.reading)};return Xq(e.reviewTurn)&&Zq(e.reviewTurn.promptEntryId,512)&&(t.reviewTurn={promptEntryId:Zq(e.reviewTurn.promptEntryId,512),revision:Qq(e.reviewTurn.revision),...typeof e.reviewTurn.filePath==`string`?{filePath:Zq(e.reviewTurn.filePath)}:{}}),t}function aJ(){try{let e=localStorage.getItem(Yq);if(!e||e.length>256e3)return[];let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=new Map;for(let e of t.slice(-32)){let t=iJ(e);t&&n.set(JSON.stringify([t.sessionId,t.sessionPath]),t)}return[...n.values()]}catch{return[]}}function oJ(e){try{let t=e.slice(-32).flatMap(e=>iJ(e)??[]),n=JSON.stringify(t);for(;n.length>256e3&&t.length;)t.shift(),n=JSON.stringify(t);localStorage.setItem(Yq,n)}catch{}}function sJ(e,t,n){if([`session_start`,`session_switched`,`session_created`].includes(t))return e.length===0?e:[];if([`agent_settled`,`turn_settled`].includes(t))return e.some(e=>e.state===`running`)?e.map(e=>e.state===`running`?{...e,state:`unknown`}:e):e;if(!t.startsWith(`tool_execution_`))return e;let r=n.toolCallId;if(typeof r!=`string`||r.length>500)return e;let i=e.find(e=>e.call.id===r);if(i&&i.state!==`running`&&(i.state!==`unknown`||t!==`tool_execution_end`))return e;let a=Pd(n.call),o=a.type===`toolCall`&&typeof a.name==`string`&&typeof a.arguments==`string`?a:i?.call;if(!o||o.evidenceTruncated&&o.id?.includes(`[truncated]`))return e;let s=Pd(n.result),c=typeof s.content==`string`?s:i?.result,l=typeof n.parentToolCallId==`string`&&n.parentToolCallId.length<=500?n.parentToolCallId:i?.parentToolCallId,u={call:o,result:c,...l?{parentToolCallId:l}:{},state:t===`tool_execution_end`?n.isError===!0?`failed`:`returned`:`running`},d=(i?e.map(e=>e.call.id===r?u:e):[...e,u]).slice(-32);for(;d.length>0&&new TextEncoder().encode(JSON.stringify(d)).byteLength>524288;)d.shift();return d}var cJ={en:{translation:{promptPending:`Processing your request…`,commandFeedbackTruncated:`This is a limited command preview. Narrow the query or run it in the TUI for the full output.`,planMode_inactive:`Normal mode`,planMode_planning:`Planning · writes blocked`,planMode_ready:`Plan ready · awaiting review`,planMode_invalid:`Plan state invalid · writes blocked`,planModeEnter:`Plan`,promptPlanMessage:`This conversation uses Plan mode · discuss the plan; no implementation yet`,planModeUnconfirmed:`Could not confirm Plan mode. Refresh before continuing.`,planModeExit:`Exit planning`,planModeImplement:`Prepare implementation prompt`,planImplementationReplaceDraft:`Preparing this plan will replace the current draft and turn off Plan mode. The prompt will not be sent. Continue?`,commandSupport_plan:`Planning and same-session implementation prompts are available. Starting a fresh implementation session still requires the TUI.`,commandSupport_setup:`Configuration uses the active model; questions are answered in Web.`,handoffWaiting:`Manual action`,handoffDone:`Done`,handoffUnable:`Unable to complete`,handoffDoneHelp:`I performed the action. The agent still needs to verify it.`,handoffUnableHelp:`I could not finish. I can add a note about the blocker.`,handoffReview:`Review status`,handoffSubmit:`Submit status`,handoffSignal:`Expected result:`,handoffVerify:`Reporting Done lets the agent continue and verify; it is not proof of success.`,planCardLabel:`Development plan`,planCardReady:`Plan ready`,planCardResult:`Plan result`,planCardNotApproval:`This step produced a plan. It did not approve or start implementation.`,planCardCollapse:`Collapse`,planCardExpand:`Expand`,planCardCopy:`Copy plan`,planCardCopyPreview:`Copy visible preview`,planCardTruncated:`Only a bounded preview is displayed.`,planCardLoadFull:`Load full plan`,planCardLoadingFull:`Loading plan...`,planCardLoadFailed:`Could not load the full plan. Retry`,planCardEvidence:`Tool result · plan_ready`,questionWaiting:`Question`,questionPreview:`View preview`,questionSkip:`Skip`,questionProgress:`{{current}} of {{total}}`,questionReview:`Review answers`,questionReviewTitle:`Ready to send?`,questionReviewHelp:`Review your choices. Nothing is sent until you submit.`,questionEdit:`Edit answer: {{question}}`,questionDismiss:`Dismiss questions without answering`,questionCustom:`Or write your own reply`,questionCustomHelp:`Or leave it blank to ask for a clearer question.`,questionYourAnswer:`Your answer`,questionCustomPlaceholder:`Describe what you have in mind…`,questionNotes:`Additional context (optional)`,questionNotesPlaceholder:`Add a constraint or clarify your choice…`,questionRephrase:`Ask for a clearer or smaller question`,questionBack:`Back`,questionNext:`Next question`,questionSubmit:`Submit answers`,questionSubmitting:`Sending…`,questionRetry:`Check submission`,questionUncertain:`We could not confirm delivery. Your submitted answers are kept here. Check submission to recover the result without sending them twice.`,questionDisconnected:`Reconnecting… Your choices stay here; submitting is paused.`,questionLimit:`Keep each answer or note within {{count}} UTF-8 bytes.`,questionLoadFailed:`Could not check for questions awaiting your answer.`,questionDraftLimit:`Question drafts are full. Shorten or clear an existing answer before adding more text.`,questionRetryLoad:`Try again`,questionCloseReceipt:`Close question status`,questionState_dismissed:`Questions dismissed. No answers were submitted.`,questionState_cancelled:`Questions cancelled. No answers were submitted.`,questionState_expired:`Questions expired. No answers were submitted.`,questionState_stale:`This request is no longer active. Check the conversation for its result.`,conversationView:`Conversation view`,jumpToLatest:`Jump to latest`,historyLoading:`Loading history…`,historyOmitted:`{{count}} earlier entries · Scroll up to load automatically`,historyChanged:`The Session branch changed. History has been reset to the current branch.`,historyUnavailable:`Could not load history. Please retry.`,historyValidationUnavailable:`Could not verify the conversation history. Please retry.`,historyVerifying:`Checking conversation history…`,messageLoadFull:`Load full message`,messageLoadMore:`Load more`,messageLoadingFull:`Loading message…`,messageLoadFailed:`Could not load this message. Retry`,filePreview:`File preview`,changeEvidence:`Changes`,changeEvidenceScope:`Read-only Git snapshot of changes since this session started.`,turnLabel:`Turn {{number}}`,turnState_running:`Running`,turnState_complete:`Completed`,turnState_failed:`Failed`,turnState_interrupted:`Interrupted`,turnState_waiting:`Waiting for response`,turnState_forked:`Forked · Ready to continue`,turnChanges_one:`{{count}} file changed during this turn`,turnChanges_other:`{{count}} files changed during this turn`,turnChangesPartial:`At least {{count}} files changed during this turn`,turnChangesIncomplete:`This turn's change record is incomplete.`,turnChangesMore:`Show {{count}} more files`,turnChangesLess:`Show fewer files`,turnChangesReview:`Review turn changes`,turnChangesReviewButton:`Review`,turnChangesBack:`Back to turn changes`,turnChangesLoading:`Loading this turn's changes…`,turnChangesUnavailable:`This turn's saved diff is unavailable.`,messageCopyRequiresFull:`Load the full message before copying.`,filesChanged_one:`{{count}} file changed`,filesChanged_other:`{{count}} files changed`,reviewChanges:`Review changes`,workspaceChanges:`Workspace changes`,overviewChanges:`Changes`,overviewLineTotals:`Text lines added and removed across the current Git comparison`,overviewPartialTotals:`Known line counts only; some files could not be counted. Open Changes for details.`,overviewCounting:`Counting…`,overviewCountsUnknown:`Counts unavailable`,overviewReviewUnavailable:`Unavailable`,sessionSources:`Sources`,sourcesAdd:`Add source`,sourcesEmpty:`No sources yet`,sourcesFailed:`Could not load sources.`,sourcesViewAll:`View all`,sourcesLoadMore:`Load more sources`,sourcesBack:`Back to sources`,sourcesPartial:`This list has reached its display limit. Earlier sources remain in the conversation.`,turnChangesScope:`Saved workspace changes during this turn`,turnEdits_one:`Edited {{count}} file`,turnEdits_other:`Edited {{count}} files`,turnEditsPartial:`Recorded edits to {{count}} files`,turnEditsScope:`This turn's recorded file-tool writes · saved; shell and external edits are not included`,turnEditStatsUnknown:`Line counts unavailable`,turnEditReason_before_unavailable:`The write completed, but previous contents were not authorized for reading. A before/after diff is unavailable.`,turnEditReason_content_limit:`The write completed. Content exceeds the saved comparison limit, so exact line counts are unavailable.`,turnEditReason_concurrent_change:`The file changed between recorded operations. A reliable net diff for this turn is unavailable.`,gitReviewLoadedCount:`{{count}} files loaded`,gitReviewPartialLabel:`Partial`,gitReviewSearch:`Search file paths`,gitReviewExpand:`Expand review`,gitReviewSearchLoaded:`Search loaded files`,gitReviewMarkViewed:`Mark {{path}} as viewed`,gitReviewMarkCurrentViewed:`Mark current file {{path}} as viewed`,gitReviewViewedLabel:`Viewed`,gitReviewViewedProgress:`Viewed {{viewed}} / {{loaded}} loaded files`,gitReviewViewedLimit:`Up to {{count}} viewed marks are remembered for this comparison.`,gitReviewNoMatch:`No matching files.`,gitReviewNoLoadedMatch:`No matches in the loaded files.`,gitReviewLoadNext:`Load the next files`,gitReviewChanged:`The workspace changed. Refresh the list before loading more.`,gitReviewNewVersion:`New changes are available. You are reading the previous version.`,gitReviewShowLatest:`Show latest diff`,gitReviewBinary:`No text diff is available for this binary file.`,gitReviewBinaryShort:`Binary`,gitReviewPendingStats:`Not loaded`,gitReviewComparison:`{{current}} compared with {{base}}`,gitReviewWorkingTree:`Working tree compared with HEAD`,gitReviewSessionSnapshot:`Changes since this session started`,gitReviewDetached:`Detached HEAD`,gitReviewLoading:`Reading Git changes…`,gitReviewRetry:`Retry`,gitReviewRefresh:`Refresh changes`,gitReviewOlderResult:`Showing the previous result.`,gitReviewNotRepository:`This workspace is not a Git repository.`,gitReviewUnborn:`This repository has no readable HEAD yet.`,gitReviewFailed:`Git changes could not be read.`,gitReviewTruncated:`The change snapshot reached its file or diff size limit.`,gitReviewEmpty:`No changes in this comparison.`,gitReviewHiddenLines:`{{count}} more diff lines hidden.`,gitReviewDiffTruncated:`This file's diff was not loaded because the snapshot reached its size limit.`,gitReviewShowMore:`Show {{count}} more files`,gitReviewBackToFiles:`Back to changed files`,gitReviewFilePreview:`Diff for {{file}}`,gitReviewNoDiff:`No text diff is available for this file.`,changeDiff:`Change diff`,diffView:`Diff`,gitFileStatus_added:`Added`,gitFileStatus_modified:`Modified`,gitFileStatus_deleted:`Deleted`,gitFileStatus_renamed:`Renamed`,gitFileStatus_copied:`Copied`,gitFileStatus_untracked:`Untracked`,gitFileStatus_unknown:`Changed`,closePreview:`Close preview`,artifactReadOnly:`Read-only`,artifactReferenceUnavailable:`File preview is unavailable in this view: {{path}}`,artifactSession:`Session {{sessionId}}`,copyFilePath:`Copy file path`,filePathCopied:`File path copied`,refreshFile:`Refresh file`,downloadFile:`Download file`,downloadingFile:`Downloading…`,artifactOlderPreview:`Showing an older preview. `,readingFile:`Reading file…`,artifactVersion:`Version`,artifactBytes:`{{count}} bytes`,artifactPreviewTruncated:`Preview truncated. Download the file for the complete content.`,artifactUnsupported:`This file type cannot be previewed. Use Download.`,chatView:`Chat`,trajectory:`Trajectory`,trajectoryScope:`Recorded Session messages in order, not execution durations or the complete model request.`,trajectoryRunning:`Work is active. This view updates as saved records arrive; in-flight text is available in Chat.`,trajectoryTruncated:`Loaded history is partial: {{entries}} entries omitted, {{parts}} parts omitted, {{messages}} messages truncated.`,trajectoryEmpty:`No saved records yet.`,trajectoryOrder:`Record order`,trajectoryRecordCount:`{{count}} records`,trajectoryMatches:`{{count}} matches`,trajectorySearch:`Search loaded records`,trajectoryNoMatches:`No matching records.`,trajectoryEarlierGroup:`Earlier context`,trajectoryEventCount:`{{count}} Session changes`,trajectorySummary:`Overview`,trajectoryInputTab:`Input`,trajectoryResultTab:`Result`,trajectoryConversationGroup:`Conversation`,trajectoryReasoningTitle:`Thinking`,trajectoryRecordNumber:`Record {{number}}`,trajectoryRecordInfo:`Record information`,trajectoryRecordId:`Record ID`,trajectoryCallId:`Tool call ID`,trajectoryEventType:`Event type`,trajectoryEvent_model_change:`Model changed`,trajectoryEvent_thinking_level_change:`Thinking level changed`,trajectoryEvent_compaction:`Context compacted`,trajectoryEvent_session_info:`Session information updated`,trajectoryEvent_custom:`Session record`,trajectoryEarlier:`Show earlier records ({{count}} remaining in loaded history)`,trajectoryDetails:`Record details`,trajectoryRecordedAt:`Record timestamp`,trajectoryEvidenceTruncated:`This evidence was truncated in the Session projection.`,trajectoryArguments:`Tool arguments`,trajectoryRecordedContent:`Recorded content`,trajectoryThinking:`Recorded model reasoning`,trajectoryOutput:`Tool result`,trajectoryMissingResult:`No unambiguous result is included in the loaded records. This does not imply the tool is still running.`,trajectoryStructured:`Structured result`,trajectoryEventOnly:`Only this event’s type and timestamp are available.`,trajectory_user:`User message`,trajectory_assistant:`Assistant`,trajectory_call:`Tool call`,trajectory_result:`Unpaired result`,trajectory_event:`Session event`,trajectory_returned:`Tool returned a result.`,trajectory_error:`Tool returned an error`,trajectory_unknown:`Outcome not established`,runtimeStatus:`Runtime status`,refreshStatus:`Refresh status`,terminalDetails:`Terminal details`,openTools:`Open tools`,sideConversation:`Side conversation`,sideConversationDescription:`Ask a focused question in a separate Pi session without interrupting the main task.`,workbarChangesDescription:`Inspect the current Git branch and working tree.`,terminal:`Terminal`,renameTerminal:`Rename terminal`,terminalName:`Terminal name`,workbarTerminalDescription:`Open an interactive shell for the current workspace.`,backgroundTerminalActivity:`Agent command activity`,restartTerminal:`Restart terminal`,reconnectTerminal:`Reconnect terminal`,restartTerminalTitle:`Restart this terminal?`,restartTerminalDetail:`The current terminal will be closed. Running processes may be interrupted.`,terminalReconnecting:`Reconnecting terminal...`,terminalScrollToBottom:`Scroll to bottom`,terminalOutputResynced:`Terminal output resynchronized.`,terminalRestarting:`Restarting terminal...`,terminalConnecting:`Starting terminal…`,terminalExited:`Terminal exited.`,terminalExitCode:`Terminal exited with code {{code}}.`,terminalDisconnected:`Terminal connection ended unexpectedly.`,terminalError:`Terminal unavailable.`,browser:`Browser`,sessionFileRecords:`Session file records`,gitReviewSource:`Changes`,gitReviewBaseBranch:`Compare against branch`,gitReviewChooseBase:`Choose comparison branch`,gitReviewSearchBranches:`Search branches`,gitReviewLocalBranch:`Local branch`,gitReviewRemoteBranch:`Remote branch`,gitReviewBranchesTruncated:`Showing a bounded list of branches. Some branches are omitted.`,gitReviewNoMatchingBranches:`No matching branches.`,gitReviewBaseUnavailable:`No default comparison branch is available. Choose a branch to review committed changes.`,gitReviewBaseInvalid:`The selected comparison branch is unavailable. Choose another branch.`,gitReviewUnstaged:`Unstaged changes`,gitReviewStaged:`Staged changes`,gitReviewBranch:`Branch changes`,gitReviewFileMissing:`This file no longer has changes in this view. Refresh the file list.`,artifactExternalAccess:`This file is in another working directory. You can authorize read-only access to this file for this session; other files remain inaccessible.`,artifactAuthorizeFile:`Open this file read-only`,sideConversationPending:`Preparing side conversation…`,resizeSidebar:`Resize sidebar`,resizePanes:`Resize panes`,resizeWorkbar:`Resize workbar`,browserPasteTooLarge:`Paste at most {{count}} characters at a time.`,browserInputTooLarge:`Enter at most {{count}} characters at a time.`,browserInputTargetChanged:`The input target changed or could not be confirmed. An input operation was not executed.`,workbarBrowserDescription:`Open and interact with a page inside the OpenPI workbar.`,browserReady:`Enter an address to start browsing`,browserStarting:`Starting the embedded browser…`,browserOpened:`Opened in the embedded browser`,browserOpenAgain:`Open again`,browserOpenFailed:`The embedded browser is unavailable.`,browserBack:`Back`,browserForward:`Forward`,browserReload:`Reload`,browserTabs:`Browser tabs`,browserNewTab:`New tab`,browserAddTab:`New browser tab`,browserCloseTab:`Close {{title}}`,browserTabLimit:`Up to {{count}} browser tabs`,browserPageTitle:`Web page: {{address}}`,browserEnteredAddress:`Last address opened from this toolbar`,browserAddressNotAllowed:`Enter an HTTP(S) address without embedded credentials, outside this application's origin.`,browserLocationUnknown:`This page navigated. Its new address is unavailable. Reload returns to the address you entered.`,browserDirectDescription:`Browse pages directly. Sites that refuse embedding can be opened in your external browser.`,browserDirectHint:`The address records toolbar navigation only. Page popups open in your external browser. Blank page? Use Open in external browser.`,browserEnhancedHint:`Browser enhancement is on: addresses sync and ordinary popup links open in these tabs. Some site policies, login popups and cross-site history still require an external browser.`,files:`Files`,filesExplorer:`Workspace files`,filesSearch:`Filter files…`,refreshFiles:`Refresh files`,filesWorkspaceActions:`Workspace file actions`,filesCreateMenu:`New`,filesImportMenu:`Import`,filesMoreMenu:`More`,filesNewFile:`New file`,filesNewDirectory:`New folder`,filesImport:`Import files`,filesImportFolder:`Import folder`,filesImportFolderChoose:`Choose a folder to import`,filesImportFolderLimit:`Import up to 2,000 files and folders at a time, with at most 64 nested levels.`,filesSelectMultiple:`Select multiple files`,filesSelectItem:`Select {{name}}`,filesSelectedCount:`{{count}} selected`,filesRename:`Rename`,filesNewName:`New name`,filesMove:`Move`,filesMoveDestination:`Destination folder (workspace relative path)`,filesTrashAction:`Move to trash`,filesTrash:`Workspace trash`,filesTrashDetail:`Removed files stay in this workspace and can be restored. Existing names are preserved.`,filesTrashEmpty:`No removed files`,filesTrashUnavailable:`{{count}} entries could not be verified. Their contents remain in .openpi-trash; automatic restore is unavailable.`,filesRestore:`Restore`,filesRestoreItem:`Restore {{name}}`,filesUndoTrash:`Undo removal`,filesOrganizationResults:`File operation results`,filesOperationDone:`Done`,filesRefreshBeforeOrganizing:`Refresh the file tree before organizing this item.`,filesImportChoose:`Choose files to import`,filesTargetDirectory:`Destination`,filesWorkspaceRoot:`Workspace root`,filesFileName:`File name`,filesDirectoryName:`Folder name`,filesCreate:`Create`,filesCreating:`Creating…`,filesCreated:`Created: {{path}}`,filesNameInvalid:`Enter one file or folder name without path separators.`,filesNameExists:`This name already exists. Choose a different name; the existing file was preserved.`,filesMutationFailed:`Could not write this file. Your input is preserved.`,filesWriteUnavailable:`Switch to this session to write workspace files.`,filesImportLimit:`Each file can be up to 50 MiB. Existing names are never overwritten.`,filesImportTooLarge:`This file exceeds the 50 MiB import limit.`,filesImportDirectoryUnsupported:`Folders cannot be imported. Choose the files inside the folder.`,filesImportResults:`File import results`,filesImportPending:`Waiting to import`,filesImporting:`Importing…`,filesImported:`Saved to the workspace`,filesImportedNoPreview:`Saved. Preview supports up to 20 MiB; copy the path to use this file in chat.`,filesClearImported:`Clear completed imports`,filesRetryImport:`Retry import`,filesPathActions:`Path actions for {{name}}`,filesCopyRelativePath:`Copy relative path`,filesCopyAbsolutePath:`Copy absolute path`,filesPathCopied:`Copied path: {{path}}`,filesReadFailed:`Unable to read files.`,filesSymlink:`Symbolic link — not followed by the file browser`,filesTruncated:`The result is incomplete. Refine your search.`,filesNoMatches:`No matching files`,filesEmpty:`This folder is empty`,filesChoose:`Choose a file to preview`,filesChooseDetail:`Browse your workspace on the right. Files open here, keeping the explorer in place.`,filesHideTree:`Hide file tree`,filesShowTree:`Show file tree`,filesPreview:`Preview`,filesSource:`View source`,filesEdit:`Edit`,filesMode:`File view`,filesEditor:`File editor`,filesSave:`Save file`,filesSaving:`Saving…`,filesSaved:`Saved`,filesUnsaved:`Unsaved changes · draft kept in this window`,filesDiscard:`Discard draft`,filesDiscardConfirm:`Discard your unsaved changes to this file?`,filesSaveConflict:`The file changed on disk. Your draft is preserved. Refresh to inspect the current version, then reconcile your changes before saving.`,filesSaveFailed:`Could not save. Your draft is preserved; check the file and retry.`,filesEditLoadFirst:`Continue reading the complete file before editing.`,filesEditUnavailable:`Editing supports workspace UTF-8 text files up to 1 MiB. At most 16 unsaved drafts can be kept.`,filesOutline:`Document outline`,filesDiskVersion:`Inspect current disk version`,filesReconcile:`Reviewed · continue editing my draft against this version`,filesTable:`Table preview`,filesRow:`Row`,filesSheets:`Worksheets`,filesTableTruncated:`Showing a bounded table preview. Download the file for all rows and columns.`,filesOfficeLayout:`Document content preview; pagination and typography may differ from Office.`,filesSlidesLayout:`Slide text and images; themes, charts and animations may differ from PowerPoint.`,filesPreviousPage:`Previous page`,filesNextPage:`Next page`,filesZoomOut:`Zoom out`,filesZoomIn:`Zoom in`,filesZoomReset:`Reset zoom`,filesPdfPage:`Page {{page}}`,filesDocumentLimit:`This document exceeds the preview limit. Download it to open locally.`,filesPreviewFailed:`Unable to preview this file. You can still download it.`,filesDiagram:`Mermaid diagram`,filesExpandDiagram:`Expand diagram`,filesFitImage:`Fit`,filesOriginalImage:`Original size`,filesLoadMore:`Load more`,filesLoaded:`{{count}} items loaded`,filesReadMore:`Continue reading`,filesContentChanged:`The file changed. Refresh when ready; your current reading position is preserved.`,workbarFilesDescription:`Browse workspace files with an inline preview and file tree.`,backToSideConversations:`Back to side conversations`,continueSideConversation:`Send a follow-up…`,startSideConversation:`Ask a side question…`,sideConversationModelInherited:`New side conversations use the main conversation’s model and thinking level.`,sideConversationModelFixed:`This is the model used by this side conversation.`,stop:`Stop`,start:`Start`,browserAddress:`Browser address`,browserGo:`Open address`,openExternalBrowser:`Open in external browser`,invalidBrowserAddress:`Enter a valid HTTP or HTTPS address.`,addImages:`Add images`,addFiles:`Add files`,fileAttachments:`File attachments`,previewFileAttachment:`Preview file`,fileAttachmentDescription:`Documents, spreadsheets, PDFs, text, code, and other files`,fileAttachmentCount:`Attach up to {{count}} items.`,fileAttachmentTooLarge:`Files must total 50 MB or less.`,fileAttachmentReadFailed:`Could not read this file. Check the format or whether it is password protected.`,fileAttachmentTextReady:`Text ready`,fileAttachmentTextTruncated:`Partial text · original retained`,fileAttachmentOriginalReady:`Original file ready`,fileAttachmentExtractionFailed:`Text unavailable · original retained`,fileAttachmentEncodingUnavailable:`The text encoding could not be read. The original bytes are preserved.`,fileAttachmentDocumentUnavailable:`Text could not be extracted. The document may be password protected or have an unsupported format. The original bytes are preserved.`,fileAttachmentNoText:`The original file will be attached for the agent to read with its tools. No text was extracted.`,fileAttachmentPreviewTruncated:`Preview shows the first 20,000 characters. The complete extracted text will be attached.`,fileAttachmentExtractedContent:`Extracted text`,fileAttachmentPromptLabel:`User-provided files:`,fileAttachmentPromptTooLong:`The message and file references exceed the input limit. Shorten the message or attach fewer files.`,imageAttachmentDescription:`PNG, JPEG, GIF, or WebP`,imageAttachments:`Image attachments`,imageAttachmentsLoading:`Preparing attachments…`,commandOpensPanel:`Open panel`,commandPanelArguments:`This command opens a panel and cannot include arguments or images. Remove them, or use the panel directly.`,commandPanelUnavailable:`The panel could not be opened. Your command is preserved.`,commandUnavailable_terminal_only:`Requires Pi's terminal interface.`,commandUnavailable_not_integrated:`This extension command is not connected to Web yet. Use it in Pi's terminal.`,artifactImagePreviewFailed:`Unable to preview this image. Refresh the file to retry, or download it.`,artifactFileDetails:`File details`,turnElapsedRunning:`Working for {{duration}}`,compactionElapsed:`Waiting {{duration}}`,compactionRunning:`Compacting context`,compactionCompleted:`Context automatically compacted`,compactionFailed:`Context compaction failed`,compactionInterrupted:`Compaction interrupted`,compactionUnchanged:`Compaction finished without a new summary`,compactionUnavailable:`Context compaction status unavailable`,compactionReconnectHelp:`Connection interrupted. The current status will be checked after reconnecting.`,compactionDraftHelp:`Compacting history. Messages you send will be queued.`,turnElapsedFinished:`Worked for {{duration}}`,composerAdd:`Add`,composerCommands:`Commands`,composerFile:`File`,composerGoal:`Goal`,composerPlan:`Plan`,composerCompact:`Compact`,composerModel:`Model`,composerBack:`Back`,composerGoalDescription:`Set or view a long-running goal`,composerPlanDescription:`Enter or leave Plan mode`,composerCompactDescription:`Summarize earlier conversation history`,composerModelDescription:`Select this Session's model`,compactionQueueWaiting:`Waiting for compaction to finish`,compactionQueueBlocked:`Messages retained. Retry when ready or clear the queue.`,clearPromptQueue:`Clear queue`,turnElapsedOutcome_cancelled:`Stopped`,turnElapsedOutcome_failed:`Failed`,turnElapsedOutcome_uncertain:`Outcome unconfirmed`,settingsSetupBusyHint:`Agent configuration is available after this turn. Display settings can be changed now.`,resetChatContentWidth:`Reset chat content width`,resetChatFontSize:`Reset chat font size`,setupResolveAdmission:`Return to the conversation to resolve the pending message before applying settings.`,removeAttachment:`Remove attachment`,dropImagesHere:`Drop files or images here`,imageAttachmentCount:`Attach up to {{count}} images.`,imageAttachmentTooLarge:`Each image must be 10 MB or smaller.`,imageAttachmentTotalTooLarge:`The attached images must total 32 MB or less.`,imageAttachmentUnsupported:`Only valid PNG, JPEG, GIF, and WebP images are supported.`,imageAttachmentReadFailed:`Could not read this image. Add it again to retry; your message is preserved.`,attachedImage:`Attached image`,previewAttachment:`Preview image`,closeImagePreview:`Close image preview`,imagePreviewFailed:`Unable to display this image.`,fitImage:`Fit image`,originalImageSize:`Original size`,imageViewMode:`Image view`,sessionUsage:`Session token usage`,sessionInputTokens:`Input tokens`,sessionOutputTokens:`Output tokens`,sessionCacheTokens:`Cached tokens`,sessionContextUsage:`Context usage and context window`,usageContextLabel:`Context`,usageUnknown:`Unknown`,usageOpenDetails:`Input {{input}} · Output {{output}} · Context {{percent}} / {{capacity}} · View token usage`,usageContextHelp:`Estimated tokens in the current branch / model context limit.`,usageSessionTotals:`Session totals`,usageInputLabel:`Input`,usageOutputLabel:`Output`,usageTotalLabel:`Total`,usageWorkspaceLabel:`Workspace`,usageSessionId:`Session ID`,usageTotalsHelp:`Session token totals include cache usage.`,subagentDetails:`Subagents`,sessionOverview:`Session overview`,sessionOverviewChanges:`Changes in the current review scope`,subagentSummaryRunning:`{{count}} running`,subagentSummaryDone:`{{count}} completed`,subagentSummaryOther:`{{count}} other`,subagentNoneYet:`No subagents yet`,subagentOtherGroup:`Failed / interrupted`,subagentShowMore:`Show {{count}} more`,backToSubagents:`Back to subagents`,subagentActiveGroup:`Active`,subagentFinishedGroup:`Completed`,subagentNoneRunning:`No subagents running.`,subagentNoneFinished:`Completed tasks will appear here.`,subagentProgress:`Subagents: {{running}} running · {{completed}} completed`,subagentSummaryUnknown:`{{count}} without confirmed status`,subagentTasks:`Subagent tasks`,inspectSubagent:`Open subagent: {{name}}`,subagentState_running:`Running`,subagentState_done:`Completed`,subagentState_error:`Failed`,subagentState_interrupted:`Interrupted`,subagentStarting:`Starting…`,subagentSpawnFailed:`Failed to start`,subagentStateUnavailable:`Started · state unavailable`,subagentSpawnReceipt:`Start receipt`,subagentSpawnReceiptHint:`This confirms the start request, not the subagent's final result.`,subagentTask:`Assigned task`,subagentTranscript:`Subagent conversation`,subagentResult:`Result`,subagentSaved:`Saved record`,subagentRecordedState:`Last recorded state`,subagentSavedHint:`From this parent session's saved receipts. A result may include other tasks from the same batch; this is not the child's full live conversation.`,subagentLive:`Working · updates automatically`,subagentReadOnly:`Read-only view · closing this panel does not stop the task`,subagentUnavailable:`Live details are no longer available for this subagent in the current session. The start receipt is not evidence of completion.`,subagentStale:`Could not refresh. The details below are the last received snapshot.`,subagentNoMessages:`No messages received yet.`,subagentTranscriptUnavailable:`This view retains a task summary and cannot show the full child conversation.`,subagentWorkflowsTruncated:`{{count}} workflows are outside the loaded list; their task counts are unknown.`,subagentState_unknown:`Unconfirmed`,subagentUnconfirmedGroup:`Unconfirmed`,subagentTruncated:`Showing a bounded excerpt; {{count}} earlier messages omitted. Some text may be shortened.`,subagentListTruncated:`{{count}} additional tasks are outside the loaded list.`,subagentThinkingRedacted:`Reasoning was redacted by the provider.`,subagentTool_running:`Running`,subagentTool_done:`Returned`,subagentTool_error:`Failed`,subagentTool_unknown:`Result not retained`,inspectionChanged:`The active session changed. Reopen this panel.`,inspectionUnavailable:`Details are unavailable.`,inspectionLoading:`Loading status…`,thinkingUnavailable:`Thinking state is unavailable.`,trustUnavailable:`Project trust status is unavailable.`,executionState:`State`,terminalCommand:`Command`,copyTerminalCommand:`Copy command`,copyVisibleOutput:`Copy visible {{stream}}`,copySetupCommand:`Copy setup command`,savedTrustDecision:`Saved decision`,activeSessionTrust:`Active Session trust`,trustDecision_trusted:`Trusted`,trustDecision_denied:`Denied`,trustDecision_undecided:`Undecided`,trustDecision_unknown:`Unknown`,trustActiveYes:`Trusted in this Session`,trustActiveNo:`Not trusted in this Session`,terminalDirectory:`Directory`,startedAt:`Started`,exitCode:`Exit code`,detailTruncated:`Some details are shortened to keep this view bounded.`,standardOutput:`Standard output`,standardError:`Standard error`,outputTruncated:`{{count}} bytes omitted from this output view.`,outputRecovery:`The runtime reports a retained log. This view shows only a bounded excerpt.`,modelAndThinking:`Model and reasoning`,selectedModel:`Current model`,thinkingLevel:`Thinking level`,availableThinking:`Available levels`,unknownState:`Unknown`,projectTrust:`Project trust`,trust_trusted:`This session trusts the workspace.`,trust_untrusted:`Trust for this workspace has been denied.`,trust_restricted:`Project resources are restricted pending a trust decision.`,trust_unknown:`Trust state is not available.`,trustRefreshNeeded:`The saved decision and active session differ. Refresh the session through Pi to apply it.`,providerAvailability:`Provider credentials`,settings:`Settings`,settingsNavigation:`Settings navigation`,generalSettings:`General`,configurationSettings:`Configuration`,configurationIntro:`Permissions, web access and model responses.`,configurationReadFailure:`Configuration could not be read safely. Fix the settings file, then refresh.`,configurationUserScope:`User configuration`,configurationSetupHint:`Response and search changes use OpenPI setup`,configurationApproval:`Approval policy`,configurationApprovalDetail:`Tool approvals follow the installed Pi extensions.`,configurationPiPermissions:`Pi extensions`,configurationSandbox:`Sandbox`,configurationSandboxDetail:`Tools run with the host process permissions.`,configurationSandboxUnavailable:`No OS sandbox`,configurationSearchDetail:`Let the current Session model search the web when supported.`,configurationSearchOff:`Do not offer native search to the current model.`,configurationSearchOn:`Offer native search when the current connection supports it.`,configurationVerbosity:`Output verbosity`,configurationVerbosityDetail:`Choose how much detail the model includes in its response.`,configurationResponsesUnavailable:`The current connection does not use a supported Responses API.`,configurationVerbosity_default:`Model default`,configurationVerbosity_low:`Low`,configurationVerbosity_medium:`Medium`,configurationVerbosity_high:`High`,configurationVerbosityHelp_low:`Prefer short answers with fewer details.`,configurationVerbosityHelp_medium:`Include useful explanation and a moderate amount of detail.`,configurationVerbosityHelp_high:`Include more complete explanation and detail.`,configurationVerbosityRequest:`Set only response_verbosity to {{value}}; preserve the other OpenPI settings.`,configurationSummary:`Reasoning summary`,configurationSummaryDetail:`Choose the summary requested from a supported reasoning model.`,configurationSummaryUnavailable:`The current connection does not support reasoning summaries.`,configurationSummary_default:`Model default`,configurationSummary_auto:`Auto`,configurationSummary_concise:`Concise`,configurationSummary_detailed:`Detailed`,configurationSummary_none:`Off`,configurationSummaryHelp_auto:`Let the model choose the summary length.`,configurationSummaryHelp_concise:`Request a brief reasoning summary.`,configurationSummaryHelp_detailed:`Request a more detailed reasoning summary.`,configurationSummaryHelp_none:`Do not request a summary. Keep the current reasoning effort.`,configurationSummaryRequest:`Set only response_reasoning_summary to {{value}}; preserve the other OpenPI settings.`,configurationModelFeatures:`Model features`,configurationReasoningLevels:`Available reasoning efforts`,configurationReasoningDetail:`Choose which supported levels appear in model controls. The current level stays visible; its value is unchanged.`,configurationReasoningCount:`{{count}} selected`,configurationDependencies:`Workspace dependencies`,configurationEnvironment:`Local environment`,configurationEnvironmentDetail:`Node.js, Python and other tools come from your environment. OpenPI does not install a bundled workspace runtime.`,configurationRuntimeStatus:`Runtime status`,browserSettings:`Browser`,webSearchSettings:`Web search`,webSearchCurrentModel:`Current Session model`,webSearchNativeDetail:`Use your current model provider's native search with the existing connection and credentials.`,webSearchSupported:`This connection supports native search. When enabled, the model decides when to search.`,webSearchUnsupported:`Native search is unsupported or unconfirmed for this connection. No search tool is provided and no other provider is used.`,webSearchNativeRequest:`Enable native web search using the current Session model and existing Pi credentials. Do not switch model, connection protocol, or search provider. Unsupported or unknown connections must receive no search tool.`,webSearchIntro:`Let your model search current sources and read the original pages.`,webSearchPackageDetail:`Optional search, page reading, and PDF extraction through a Pi package.`,webSearchDefaultOff:`Off by default. This optional extension follows the current Session model; it needs no separate search key or plugin installation.`,webSearchLoaded:`Package loaded in this Session`,webSearchNotLoaded:`Package not loaded in this Session`,webSearchSource:`Review plugin source`,webSearchProfile:`Search setup`,webSearchExa:`Exa — no API key required`,webSearchExisting:`Keep my existing search preferences`,webSearchProfileHint:`Exa uses search queries with direct page reading. Existing preferences stay untouched. Other search services can be configured after installation.`,webSearchEnable:`Enable web search…`,webSearchDisable:`Disable web search…`,webSearchConfigure:`Change search service…`,webSearchExaRequest:`Enable optional web search with Pi Web Access and Exa, which needs no API key. Let me review the installation confirmation, preserve other preferences, and do not reload automatically.`,webSearchExistingRequest:`Enable optional web search with Pi Web Access and keep my existing search preferences unchanged. Let me review the installation confirmation, preserve other preferences, and do not reload automatically.`,webSearchDisableRequest:`Disable native web search. Preserve other settings and Session history.`,webSearchProviderRequest:`Help me change the search service for my installed Pi Web Access plugin. Explain available services and permissions, preserve unrelated preferences, keep credentials with the search plugin, and do not reload automatically.`,browserSettingsIntro:`Let OpenPI read pages, click, type and take screenshots.`,browserControl:`Browser control`,browserControlHint:`Requests a setup change. Access changes after the configuration is saved.`,browserDefault:`Default browser`,browserDefaultHint:`Requests a setup change for the browser used when none is named.`,browserEmbedded:`OpenPI browser`,browserAllowedTitle:`Allowed browsers`,browserOffHint:`Your choices take effect when browser control is on.`,browserConnected:`Connected`,browserNeedsSetup:`Extension setup needed`,browserNotFound:`Browser not detected`,browserUpdateNeeded:`Extension update needed`,browserBlocked:`Not allowed`,browserDefaultBlocked:`Your default browser is not allowed. Allow it or choose another default.`,browserSetUp:`Set up`,browserManage:`Manage`,browserSetupNamed:`Set up {{browser}}`,browserManageNamed:`Manage {{browser}}`,browserAllowNamed:`Allow {{browser}}`,browserMore:`More browsers`,browserSpeakHint:`Say “Use Chrome to…” to choose a different browser for a request.`,browserGuideTitle:`Connect {{browser}}`,browserGuideEyebrow:`One step at a time`,browserConnectionTitle:`Connection`,browserCloseGuide:`Close browser setup`,browserConnectionReady:`Connected. Choose whether OpenPI may use this browser.`,browserEmbeddedDetail:`Pages open inside OpenPI. Some websites require a regular browser to sign in or display correctly.`,browserExternalDetail:`OpenPI can use existing tabs and signed-in pages in your connected {{browser}} profile. Keep an OpenPI tab open in that profile.`,browserManageExtension:`Manage extension`,browserAllowUse:`Allow OpenPI to use it`,browserMakeDefault:`Use as default`,browserInstallIn:`Install in`,browserInstallTitle:`Install OpenPI Browser Bridge`,browserSetupSteps:`Setup steps`,browserGuidePopout:`Keep this guide in a separate window`,browserGuideDetached:`Your guide is open in a separate window. Follow it alongside the browser settings.`,browserShowGuide:`Show guide`,browserGuideInline:`Return guide here`,browserGuideBlocked:`The guide window could not open. Allow pop-ups and try again, or follow the steps here.`,browserSafariSettings:`Safari → Settings`,browserSafariDeveloper:`Developer settings`,browserSafariTemporary:`Add Temporary Extension…`,browserSafariOpenHint:`Open Safari, then choose Safari → Settings. Keep this guide alongside it. Requires Safari 26 or later on macOS.`,browserSafariDeveloperTitle:`Show Safari’s developer settings`,browserSafariDeveloperHint:`In Settings → Advanced, turn on Show features for web developers. Then select the Developer tab.`,browserSafariLoadHint:`In Developer, click Add Temporary Extension and select the folder below. Enable OpenPI Browser Bridge and allow the websites you want to control, including the local OpenPI page. Temporary extensions need reloading after Safari quits.`,browserFirefoxThis:`This Firefox`,browserFirefoxTemporary:`Load Temporary Add-on…`,browserFirefoxDeveloperTitle:`Select This Firefox`,browserFirefoxDeveloperHint:`On about:debugging, choose This Firefox in the left sidebar. Firefox does not need a Developer mode switch.`,browserFirefoxLoadHint:`Click Load Temporary Add-on and select manifest.json in the folder below. This development installation lasts until Firefox restarts; a permanent installation requires a Mozilla-signed package.`,browserFirefoxDone:`Selected. Next`,browserStepCount:`Step {{step}} of {{total}}`,browserStepLabel:`Step {{step}}: {{label}}`,browserStepOpen:`Open page`,browserStepAdd:`Add extension`,browserStepConnect:`Connect`,browserOpenManagerTitle:`Open {{browser}} extensions`,browserOpenManagerHint:`Start here. We’ll open the right page for you.`,browserOpenManager:`Open {{browser}} extensions`,browserReopenManager:`Open extensions page again`,browserAlreadyInstalled:`Already installed? Connect`,browserDeveloperMode:`Developer mode`,browserDeveloperTitle:`Turn on Developer mode`,browserDeveloperHint:`In the extensions page you just opened, turn on the Developer mode switch.`,browserDeveloperDone:`It’s on. Next`,browserIllustration:`Illustration · In {{browser}}`,browserExtensions:`Extensions`,browserLoadUnpacked:`Load unpacked`,browserLoadHint:`Click Load unpacked in your browser, then select the folder below.`,browserFolderBundled:`Included with OpenPI`,browserOpenFolder:`Open folder`,browserFolderOpened:`Extension folder opened.`,browserPathCopied:`Path copied`,browserCopyFailed:`Couldn’t copy. Select the path above and copy it manually.`,browserChooseFolderMac:`In the folder picker, press ⌘ ⇧ G, paste this path and press Return, then click Select.`,browserChooseFolderOther:`In the folder picker, paste this path into the address bar and select the folder.`,browserInstalledConnect:`Added. Connect to OpenPI`,browserPreviousStep:`Back`,browserWaiting:`Waiting for OpenPI Browser Bridge… We’ll detect it automatically.`,browserInstallBrowserFirst:`Install {{browser}} first, or open this OpenPI address in your installed browser.`,browserConnectTitle:`Connect to OpenPI`,browserConnectHint:`Open OpenPI in {{browser}}. Use the profile where you installed the extension.`,browserOpenIn:`Open in {{browser}}`,browserAllowHint:`Once connected, you can allow OpenPI to use this browser. Installing the extension does not change your browser permissions.`,browserCheck:`Check connection`,browserNotConnectedYet:`No connection yet. Finish installation, refresh OpenPI in that browser and check again.`,browserHelp:`Setup help`,browserReloadHint:`Already installed? Reload OpenPI Browser Bridge in the extension manager and refresh OpenPI. Accept the browser’s permission prompt if shown.`,browserSupportedHint:`Chrome, Edge, Brave and Chromium 145+ support embedded and native pages. Safari 26+ on macOS and Firefox 128+ use the portable extension for native tabs; nested frames must be opened separately. Temporary Safari/Firefox installations need reloading after browser restart.`,browserCopyPath:`Copy extension folder path`,browserLoading:`Checking browser connections…`,browserSaved:`Saved. Browser permissions take effect immediately.`,browserSaving:`Saving…`,modelSettings:`Models`,skillsSettings:`Skills`,subagentsSettings:`Sub-agents`,pluginsSettings:`Plugins`,configureOpenPi:`Configure OpenPI`,setupRequestReviewAll:`review every OpenPI configuration area with me`,setupRequestSetTheme:`set only the OpenPI Web theme to {{value}} and preserve every other setting`,setupRequestSetChatWidth:`set only the OpenPI Web chat content width to {{value}}px and preserve every other setting`,setupRequestSetChatFontSize:`set only the OpenPI Web chat font size to {{value}}px and preserve every other setting`,setupRequestEnableExpandedThinking:`expand thinking blocks by default in OpenPI Web and preserve every other setting`,setupRequestDisableExpandedThinking:`collapse thinking blocks by default in OpenPI Web and preserve every other setting`,setupRequestSubagents:`review and configure Agent role models and workflow limits`,setupRequestFailed:`The OpenPI setup request was not accepted.`,setupRequestRunning:`Applying OpenPI settings…`,setupRequestAccepted:`Configuration request accepted.`,setupPlanBlocked:`Exit Plan mode before changing agent configuration. Display settings can be changed directly; exiting does not start implementation.`,setupPlanBusy:`Agent configuration requires an idle turn and leaving Plan mode. Display settings can be changed now.`,setupOutcome_pending:`Configuration request is awaiting a save receipt.`,toolCallArguments:`Tool arguments`,toolCallOutput:`Tool result`,setupOutcome_saved:`OpenPI configuration was saved and applied.`,setupOutcome_unchanged:`Configuration was saved; effective settings are unchanged.`,setupOutcome_failed:`The setup request failed. Review the error and current settings before retrying.`,setupOutcome_cancelled:`Setup was cancelled without a confirmed save.`,setupOutcome_unconfirmed:`No successful save was confirmed. Review current settings before retrying /openpi-setup.`,settingsUpdateFailed:`The Web preference could not be saved.`,settingsPreferencesSaved:`Display settings saved.`,settingsPreferencesSaveFailed:`Could not save display settings. Check configuration diagnostics and retry.`,settingsCatalogLoading:`Loading Pi resources…`,settingsCatalogFailed:`Could not load Pi settings resources.`,appearance:`Appearance`,settingsPersonal:`Personal`,settingsAgent:`Agent`,settingsIntegrations:`Integrations`,settingsArchivedChats:`Archived chats`,settingsSearch:`Search settings`,settingsClearSearch:`Clear search`,settingsNoResults:`No matching settings`,appearanceVisualStyle:`Visual style`,appearanceMode:`Mode`,appearanceTheme:`Theme`,appearanceAccent:`Accent color`,appearanceBackground:`Background`,appearanceForeground:`Foreground`,appearanceFont:`Font`,appearanceFont_codex:`Codex default`,appearanceFont_sans:`Sans serif`,appearanceFont_serif:`Serif`,appearanceFont_mono:`Monospace`,appearanceAccent0:`Default`,appearanceAccent1:`Blue`,appearanceAccent2:`Purple`,appearanceAccent3:`Pink`,appearanceAccent4:`Orange`,appearanceAccent5:`Green`,appearanceCustomAccent:`Custom accent color`,appearanceAdvanced:`Advanced`,appearanceReset:`Restore defaults`,appearanceResetAction:`Reset appearance`,appearanceImport:`Import theme`,appearanceCopy:`Copy theme`,appearanceCopied:`Theme copied`,appearanceCopyFailed:`Could not copy theme. Try again.`,appearanceThemeValue:`Theme data`,appearanceImportPlaceholder:`Paste an OpenPI theme…`,appearanceImportInvalid:`Enter valid OpenPI theme data.`,appearanceImportAction:`Import`,searchArchivedChats:`Search archived chats`,archiveProjectFilter:`Filter by project`,archiveAllProjects:`All projects`,archiveProjectGroup:`{{project}} · {{count}} archived chats`,archiveSort:`Sort archived chats`,archiveSortUpdated:`Last updated`,archiveSortCreated:`Date created`,restoreArchivedChat:`Restore {{title}}`,themeLight:`Light`,themeDark:`Dark`,themeMist:`Mist`,themeRose:`Rose`,themePine:`Pine`,themeSystem:`System`,conversationSettings:`Conversation`,expandThinkingByDefault:`Expand thinking by default`,chatContentWidth:`Chat content width`,chatFontSize:`Chat font size`,agentBehavior:`Agent behavior`,capabilityDiscovery:`Capability discovery`,capabilityDiscovery_explicit:`Explicit`,capabilityDiscovery_adaptive:`Adaptive`,workflowLimits:`Workflow limits`,workflowConcurrency:`Workflow concurrency`,workflowCalls:`Total calls`,agentSettingsSetupHint:`Agent changes are applied through /openpi-setup in the current session.`,setupRequestDiscovery:`Set capability discovery to {{mode}}. Preserve other settings.`,setupRequestLimits:`Set workflow concurrency to {{concurrency}} and total agent calls to {{calls}}. Preserve other settings.`,setupRequestEnableSuggestions:`Enable next-action suggestions. Help me choose a model if required; preserve other settings.`,setupRequestDisableSuggestions:`Disable next-action suggestions. Preserve other settings.`,setupRequestPostEdit:`Help me configure or disable the post-edit command. Show the current configuration and ask which command to use.`,configurePostEdit:`Configure post-edit command`,workflowLimitsValue:`{{concurrency}} concurrent · {{calls}} total calls`,nextActionSuggestions:`Next-action suggestions`,enabled:`Enabled`,disabled:`Disabled`,configured:`Configured`,postEditCommand:`Post-edit command`,resultDisplay:`Default result display`,subagentResults:`Subagent results`,bashOperations:`Bash operations`,fileMutations:`Write / Edit operations`,footer:`Footer`,terminalFooter:`Pi terminal footer`,terminalFooterStyle:`Terminal footer style`,terminalFooterHint:`Applies to Pi's command-line interface. An already open Pi interface updates when restarted or when setup is applied.`,detailDisplay_full:`Full`,detailDisplay_compact:`Compact`,sessionSettings:`Session`,currentModel:`Current`,useThisModel:`Use model`,model:`Model`,modelConnection:`Model connection`,provider:`Provider`,modelId:`Model ID`,providerStatusUnavailable:`This provider is not present in the bounded authentication snapshot.`,providerSettings:`Provider credentials`,providerSettingsIntro:`Inspect which Pi providers can authenticate the current Web session.`,openRuntimeDetails:`Open runtime details`,currentWorkspace:`Current workspace`,providerAuth_api_key:`API key`,providerAuth_oauth:`OAuth`,providerAuthUnknown:`Authentication method not reported`,authentication:`Authentication`,accessType:`Access`,providerAccessSubscription:`Subscription account`,providerAccessStandard:`Provider credentials`,configurationOwner:`Configuration owner`,providerLoading:`Loading provider status…`,providerLoadFailed:`Could not load provider status.`,providerReadOnly:`Managed by Pi`,selectProvider:`Select a provider`,gitReviewBaselineUnavailable:`No usable session baseline was retained (it may exceed the capture limit). Choose Unstaged, Staged or Branch to inspect Git changes, or open the session file records.`,modelsIntro:`Sign in with an account or add an API key. Your existing Pi connections are available here.`,accountLoginMethod:`Connection method`,accountLoginTab:`Account`,accountLoginChatGPT:`ChatGPT account`,accountLoginClaude:`Claude account`,accountLoginKeyTab:`API key`,accountLoginConfigured:`Account signed in`,accountLoginIntro:`Continue in your browser. No API key needed.`,accountLoginExisting:`Your account credential is saved in Pi.`,accountLoginStart:`Sign in`,accountLoginAgain:`Sign in again`,accountLoginUnsaved:`Save or discard your other changes before signing in.`,accountLoginStarting:`Preparing sign-in…`,accountLoginWaiting:`Waiting for authorization`,accountLoginChoose:`Choose how to sign in`,accountLoginCancelling:`Cancelling sign-in…`,accountLoginBrowser:`Continue in browser`,accountLoginDevice:`Use a device code`,accountLoginBrowserOption:`Sign in on this computer. Returns here automatically.`,accountLoginDeviceOption:`For remote servers or when browser sign-in is unavailable.`,accountLoginBrowserHelp:`Open the sign-in page and approve access. This page updates automatically.`,accountLoginDeviceHelp:`Open the authorization page and enter this code. Keep this page open.`,accountLoginOpen:`Open sign-in page`,accountLoginCopyCode:`Copy device code`,accountLoginPaste:`Authorization code or callback URL`,accountLoginContinue:`Continue`,accountLoginFallback:`Signed in but still waiting?`,accountLoginRemoteHelp:`If automatic return does not work, copy the final callback URL from your browser and paste it here.`,accountLoginCancel:`Cancel sign-in`,accountLogin_failed:`Sign-in failed. Try again or choose another method.`,accountLogin_expired:`Sign-in expired. Start again to get a new authorization link.`,accountLogin_cancelled:`Sign-in cancelled.`,accountLoginRequestFailed:`The request did not complete. Refresh status before retrying.`,accountLoginStatusUnknown:`Cannot check sign-in status. Your authorization may still be in progress.`,accountLoginRefreshRequired:`The credential was saved, but Pi could not update its model list. Reload Pi before using this connection.`,accountLogout:`Sign out`,accountLogoutRefreshRequired:`The saved credential was removed, but Pi could not update its model list. Reload Pi to refresh the status.`,accountLogoutTitle:`Sign out of {{provider}}?`,accountLogoutDetail:`Removes this provider’s saved credential from Pi on this machine. Other Pi sessions using it will also need to sign in again. Environment credentials are unchanged.`,providerInputTypes:`Input types`,providerInputText:`Text`,providerInputImage:`Images`,providerCustomTag:`Custom`,providerEdit:`Edit`,providerRemove:`Delete`,providerSave:`Save`,editProvider:`Edit {{provider}}`,removeProvider:`Delete {{provider}}`,providerAdd:`Add model provider`,providerAddMode:`How to add`,providerAddCatalog:`Third-party providers`,providerAddCustom:`Custom model API`,providerAccountHint:`Use an existing account to connect. Choose a provider and continue in your browser.`,providerCatalogHint:`Choose a provider from the built-in catalog and enter its API key.`,providerCustomHint:`Connect a gateway or self-hosted service using an OpenAI or Anthropic compatible API.`,providerKeyKeep:`Leave blank to keep the existing key`,providerKeyOptional:`Enter an API key, or leave blank to use environment authentication`,providerDisplayName:`Provider name`,providerCustomSettings:`Custom settings`,providerSaved:`Saved {{provider}}.`,modelDefaultTitle:`Default for new chats`,modelDefaultChoose:`Choose model`,modelDefaultBadge:`Default`,modelCurrentBadge:`In use`,modelDefaultNotSet:`Not set · Pi chooses when a new chat starts`,modelDefaultHint:`Choose the model for future chats. Existing chats keep their own model. This also updates Pi's default.`,modelDefaultReadFailed:`Could not read the default model.`,modelDefaultProjectOverride:`This workspace has a Pi override: {{model}}.`,modelDefaultSave:`Save default`,modelMakeDefault:`Also make this the default for new chats`,modelDefaultSaveFailed:`The default was not confirmed. Refresh status and try again.`,modelDefaultPartial:`The chat model changed, but saving the default was not confirmed. Refresh status before retrying.`,modelConnectionNextHint:`Choose a model from this connection to use in the current chat.`,modelConnectionSearch:`Search models…`,modelConnectionChooseProvider:`Choose a model from {{provider}}`,modelConnectionUse:`Use in this chat`,modelConnectionUseFailed:`The model change was not confirmed. Refresh the model list and try again.`,modelConnectionLoadFailed:`Could not load models.`,modelConnectionNoModels:`No selectable models yet. Check the connection or add a model definition.`,modelConnectionNoMatch:`No matching models.`,modelConnectionMore:`{{count}} more models. Search to narrow the list.`,providerModelsEmpty:`No models yet. Fetch available models or add one manually.`,providerModelsInherited:`Uses the provider’s built-in model catalog.`,providerModelsReadOnly:`This provider contains model settings that must be edited in Pi’s configuration file.`,providerModelId:`Model {{number}} ID`,providerModelName:`Model {{number}} name`,providerModelDetails:`Model details: {{model}}`,providerRemoveModel:`Remove model: {{model}}`,providerIdInvalid:`Use a unique provider ID with letters, numbers, hyphens, dots or underscores.`,providerNativeAuth:`This provider uses Pi’s native sign-in.`,providerConfigurationFailed:`Could not save. Check the fields and retry when the session is idle.`,providerProfileSavedKeyFailed:`The provider was saved, but its API key was not. Retry saving the key.`,providerReload:`Discard draft and reload`,providerCurrentRemoval:`Select another model before removing the model currently in use.`,providerRemoveDetail:`Remove this provider’s configuration and custom models? Credentials managed by Pi are kept.`,providerPickerIntro:`Select the models you want to add from this provider.`,providerPickerSelected:`{{count}} selected`,providerApiKey:`API key`,providerKeyPlaceholder:`Paste a key to add or replace it`,saveProviderKey:`Save API key`,savingSettings:`Saving…`,keepEditing:`Keep editing`,discardAndContinue:`Discard and continue`,unsavedSettingsTitle:`Discard unsaved changes?`,unsavedSettingsDetail:`Unsaved model and credential changes will be lost.`,unsavedCredentialTitle:`Discard the unsaved credential?`,unsavedCredentialDetail:`The new key has not been saved and will be cleared.`,modelSelectionBusy:`This session is busy. Model changes are unavailable.`,providerKeySaved:`Saved to Pi credentials. Existing keys are never displayed.`,providerSaveFailed:`Credential save did not complete. Wait until the session is idle, refresh status and retry. Some providers need additional authentication settings.`,providerWriteDetail:`Save API keys here directly to Pi. Keys never enter a model conversation. For OAuth or additional provider fields, use Pi's native login.`,editModelConfiguration:`Add or edit a custom model`,modelConfigurationDetail:`Set up a provider connection, then choose available models or add one manually. Saving does not send a model request.`,configuredModels:`Custom model configuration`,addModel:`Add a model`,modelConfig_provider:`Provider ID`,modelConfig_id:`Model ID`,modelConfig_name:`Display name`,modelConfig_baseUrl:`API base URL`,modelConfig_api:`API format`,modelConfig_contextWindow:`Context window`,modelConfig_maxTokens:`Max output tokens`,providerCapacityLabel:`{{field}} {{number}}`,providerModelOptions:`Model options`,providerModelInvalid:`Model {{number}}: use a unique model ID and positive token counts, such as 128K or 1M. Leave capacities blank to use defaults.`,modelConfig_reasoning:`Supports reasoning`,saveModelConfiguration:`Save model`,reloadModelConfiguration:`Discard draft and load latest`,retryModelConfiguration:`Retry loading`,discardModelDraftTitle:`Discard this model draft?`,discardModelDraftDetail:`The latest configuration will replace this unsaved draft.`,discardAndReload:`Discard and reload`,modelConfigurationUnsaved:`Unsaved changes`,modelConfigurationConflict:`Model configuration changed elsewhere. Your draft is unchanged.`,modelConfigurationLoadFailed:`Could not load model configuration. Your draft is unchanged.`,modelConfigurationSaved:`Saved to Pi models.json. Configure the provider API key to make this model available.`,modelConfigurationFailed:`Model save did not complete. Your draft is unchanged.`,setupConfigurationRequest:`Configuration request`,configureViaSetup:`Apply via OpenPI setup`,setupFormDetail:`Uses /openpi-setup. Follow progress and any required confirmation in the conversation; submission does not mean the configuration is saved.`,setupSkillsPlaceholder:`Describe the skill to add or configure, including its source or local path`,setupPluginsPlaceholder:`Describe the Pi package to configure, including its exact package name or local path`,enableSkillInvocation:`Allow model invocation`,disableSkillInvocation:`Require explicit invocation`,setupSkillInvocationRequest:`Configure this Pi skill: {{path}}. Set its native disable-model-invocation field to {{disabled}}. Preserve other content and explain when the change takes effect.`,setupRoleFormRequest:`Configure the OpenPI {{role}} role to use {{model}} and set workflow concurrency to {{concurrency}}. Inherit parent thinking, validate the selection and preserve unrelated configuration.`,providerReadOnlyDetail:`This page is read-only and never receives credential values. Configure provider authentication through Pi, then refresh this status.`,openProviderSettings:`Open provider settings`,credentialConfigured:`Configured`,credentialMissing:`Not configured`,authNotVerified:`Configured credentials do not guarantee a successful model request.`,configurationViaPi:`Read-only status. Manage model credentials and trust through Pi; manage OpenPI options with /openpi-setup.`,noSkillsFound:`No skills are loaded for this Session.`,addSkill:`Add skill`,addPlugin:`Add plugin`,searchResources:`Search by name or source`,filterResourceScope:`Resource scope`,allResourceScopes:`All scopes`,noMatchingResources:`No matching resources`,resourceBulkTooLarge:`Filter the list further before submitting a bulk request.`,resourceManagement:`Pi resources`,resourceSourceAuto:`Pi automatic discovery`,resourceSourceLocal:`Local resource`,resourcePackageSource:`Package, repository or local path`,resourcePackageSourcePlaceholder:`npm:package@version · git:owner/repo · /path/to/skill`,resourceInstallIntro:`Choose a source and scope. OpenPI setup will review and apply the request in the conversation.`,resourceInstallReview:`Review the exact source and permissions in the conversation. Submitting this request does not mean it is installed or loaded.`,resourceRequestSubmitted:`Request submitted. Follow progress and confirmations in the conversation, then refresh this catalog.`,browseSkills:`Browse skills.sh`,resourceSessionState:`Apply to this Session`,resourcesReloadNote:`Refresh reads the catalog. Reload applies saved resources to this idle Session; changes are never reloaded automatically.`,reloadResources:`Reload resources`,resourceReloadReview:`Apply saved Pi skill and plugin configuration and restart extensions in the current Session? Wait for running work to finish first.`,resourceReloaded:`Resources reloaded. Review the refreshed catalog and diagnostics.`,resourceReloadFailed:`Could not reload resources. Wait for this Session to become idle and refresh before retrying.`,advancedResourceConfiguration:`Advanced configuration`,resourceDiagnostics:`Pi reports {{extensionErrors}} extension diagnostics and {{skillErrors}} skill diagnostics.`,resourceConfigurationDiagnostics:`{{count}} settings files could not be read. Review Pi configuration diagnostics.`,resourceCatalogTruncated:`This catalog is bounded; some resources are omitted.`,resourceTargetTruncated:`This source or path is truncated. Confirm the full target through Advanced configuration before making changes.`,updateResource:`Review update`,removeResource:`Review removal`,skillsEmptyTitle:`Add your first skill`,skillsEmptyIntro:`Skills give Pi reusable instructions. Add a package, repository or local skill; project skills follow Pi project trust.`,pluginsEmptyTitle:`Extend Pi with a plugin`,pluginsEmptyIntro:`Packages can include extensions, skills, prompts and themes. Add a source to review its installation through OpenPI setup.`,pluginCount:`{{count}} plugin sources`,installedVersion:`Installed version`,configuredVersion:`Configured version`,resourceVersionUnpinned:`Not pinned / local source`,pluginState_loaded:`Session resources loaded`,pluginState_installed:`Installed · not loaded`,pluginState_disabled:`Disabled in configuration`,pluginState_missing:`Package missing`,pluginState_error:`Load diagnostics`,pluginState_notLoaded:`Not loaded`,pluginLoadedResources:`{{count}} resources in this Session's catalog. Configuration changes require an explicit reload.`,pluginAction_enable:`Review enable`,pluginAction_disable:`Review disable`,pluginAction_update:`Review update`,pluginAction_remove:`Review removal`,enableVisibleSkills:`Allow model use ({{count}} shown)`,disableVisibleSkills:`Explicit use only ({{count}} shown)`,enableVisiblePlugins:`Enable {{count}} shown packages`,disableVisiblePlugins:`Disable {{count}} shown packages`,setupResourceInstallRequest:`Add these Pi {{kind}} from source {{source}} in scope {{scope}}. Inspect the source and resolve a fixed package identity, review required installation permissions with me using ask_user, then use Pi's native package/skill configuration. For a skill request, preserve unrelated extensions and other resources. Preserve existing preferences and project trust; do not reload this Session automatically. Report saved configuration and any remaining action separately. Do not change unrelated OpenPI settings.`,setupPluginOperationRequest:`Review Pi package action {{action}} for exactly configured source {{source}}, native root {{path}}, scope {{scope}}. Resolve relative sources against the native scope's settings directory. Use Pi's native package management. For updates, inspect available versions and review a fixed target identity and required permissions with me using ask_user before installing. Preserve resource filters and all unrelated preferences; if a toggle would destroy filters, stop and explain. Removal must not delete a local source directory. Do not reload automatically. Report persisted and active states separately; do not change unrelated OpenPI settings.`,setupSkillManageRequest:`Review Pi skill action {{action}} for exactly file {{path}}, source {{source}}, scope {{scope}}. Inspect native ownership first. Review the update/removal and required permissions with me using ask_user. Preserve unrelated skills and package resources; do not remove an entire shared package to remove one skill. Preserve project trust and do not reload automatically. Do not change unrelated OpenPI settings.`,setupSkillsBulkRequest:`For exactly these currently displayed Pi skill files {{paths}}, set native disable-model-invocation to {{disabled}}. Inspect ownership, preserve all other content and preferences, review necessary changes with me, and report any files that cannot be changed safely. Explicit /skill invocation remains available. Do not reload automatically or change unrelated OpenPI settings.`,setupPluginsBulkRequest:`For exactly these currently displayed Pi packages {{packages}}, set disabled to {{disabled}} through native Pi configuration. Preserve all other preferences and resource filters; skip and report entries whose filters cannot be preserved. Respect scope and project trust, review necessary changes with me, and do not reload automatically or change unrelated OpenPI settings.`,resourceRequestFinished:`The setup turn has ended. Refresh and inspect Pi's configuration and Session resources to confirm what changed.`,skillCount_one:`{{count}} skill`,skillCount_other:`{{count}} skills`,skill:`Skill`,copySkillInvocation:`Copy invocation`,source:`Source`,scope:`Scope`,invocation:`Invocation`,modelInvocation:`Model invocation`,resourceScope_user:`Global`,resourceScope_project:`Project`,resourceScope_temporary:`Temporary`,explicitOnly:`Explicit invocation only`,availableToModel:`Available to the model`,skillFile:`Skill file`,selectSkill:`Select a skill`,subagentConfiguration:`Pi-native subagent roles`,subagentConfigurationIntro:`Role models inherit from the parent unless OpenPI setup assigns an available model.`,subagentActiveCount_one:`{{count}} active`,subagentActiveCount_other:`{{count}} active`,subagentCompletedCount_one:`{{count}} recorded`,subagentCompletedCount_other:`{{count}} recorded`,subagentConcurrency:`Limit {{count}}`,builtInRoles:`Built-in roles`,subagentRole_explorer:`Explorer`,subagentRole_implementer:`Implementer`,subagentRole_reviewer:`Reviewer`,subagentRole_advisor:`Advisor`,subagentRoleShort_explorer:`Read-only investigation`,subagentRoleShort_implementer:`Focused implementation`,subagentRoleShort_reviewer:`Correctness review`,subagentRoleShort_advisor:`Technical analysis`,subagentRoleDescription_explorer:`Explores the codebase and reports evidence without modifying files.`,subagentRoleDescription_implementer:`Implements a bounded change and runs the relevant repository checks.`,subagentRoleDescription_reviewer:`Reviews correctness, safety, regressions, and missing validation.`,subagentRoleDescription_advisor:`Analyzes difficult technical questions and recommends a concrete next step.`,configureRoles:`Configure roles`,builtInRole:`Built-in role`,builtIn:`Built-in`,modelAssignment:`Model assignment`,inheritParentModel:`Inherit parent model`,effectiveModel:`Effective model`,workflowConcurrencyLabel:`Concurrent agents`,workflowCallLimit:`Total agent calls`,runtimeBoundaries:`Runtime boundaries`,subagentAuthorityNote:`Child authority is the fail-closed intersection of the parent Session and role capabilities.`,subagentModelNote:`No hardcoded provider is introduced; an unassigned role follows the parent model and thinking level.`,resourceCount_one:`{{count}} resource`,resourceCount_other:`{{count}} resources`,noPluginsFound:`No loaded plugin sources were reported.`,pluginCatalogTotals:`{{extensions}} ext · {{skills}} skills · {{prompts}} prompts · {{themes}} themes`,loaded:`Loaded`,resourceOrigin:`Origin`,resourceOrigin_package:`Package`,resourceOrigin_topLevel:`Top-level resource`,resources:`Resources`,baseDirectory:`Base directory`,notReported:`Not reported`,extensions:`Extensions`,extensionSurfaceCount:`{{tools}} tools · {{commands}} commands`,prompts:`Prompts`,themes:`Themes`,pluginResourceSummary:`{{extensions}} ext · {{skills}} skills · {{prompts}} prompts · {{themes}} themes`,pluginsManagedByPi:`These resources are loaded by Pi. Submit changes using the setup form above. Package changes follow native confirmation and take effect through Pi's reload lifecycle.`,selectPlugin:`Select a plugin source`,statusCaptured:`Snapshot at {{time}} · refresh for the latest state`,conversationViews:`Conversation views`,currentConversations:`Current`,archivedConversations:`Archived`,refreshArchives:`Refresh archived conversations`,loadingArchives:`Loading archived conversations...`,moreArchives:`Load more archived conversations`,retryArchives:`Retry archived conversations`,archiveLoadFailed:`Could not load archived conversations.`,archiveCursorStale:`Archived conversations changed. Refresh to continue.`,archiveScanBounded:`{{count}} older records have not been scanned.`,noArchivedSessions:`No archived conversations.`,noScannedArchives:`No archived conversations in the scanned history.`,noMatchingScannedArchives:`No matching archived conversations in the scanned history.`,draftLimit:`Draft storage is full. Send or clear an existing draft before adding more content.`,restoreConversation:`Restore conversation`,restoringConversation:`Restoring…`,loadedArchives:`Archived conversations in the loaded history`,loadedHistoryBounded:`{{sessions}} more sessions and {{workspaces}} workspace summaries are not loaded. Search covers the loaded list only.`,noLoadedArchives:`No archived conversations in this loaded list.`,restoreFailed:`Could not confirm restoration. Refresh and try again.`,execution_running:`Running`,execution_done:`Completed`,execution_killed:`Stopped`,execution_timed_out:`Timed out`,execution_failed:`Failed`,execution_uncertain:`Uncertain`,activeOnlyHint:`Only the active Web session accepts messages.`,acceptedHint:`Message accepted by OpenPI Web.`,promptAdmissionUnknown:`It is unclear whether the last message was received.`,promptAdmissionUnknownDetail:`Review the refreshed Session history and runtime status before deciding. Sending as a new message may create a duplicate message.`,promptAdmissionCheckingDetail:`Checking the latest Session history and runtime status before resend options are enabled.`,promptAdmissionVerificationFailedDetail:`Could not refresh the latest Session history and runtime status. Check again before sending as a new message.`,abandonAdmission:`Don't resend for now`,retryAdmissionCheck:`Check again`,retryOriginalAdmission:`Retry original message`,promptTooLong:`Message exceeds the send limit ({{count}} / {{limit}}).`,sendAsNew:`Send as new message`,sendingAsNew:`Sending…`,stopTurn:`Stop current turn`,stoppingTurn:`Stopping current turn…`,stoppedTurn:`Current turn stopped.`,pendingFollowUpsHint:`{{count}} messages queued`,sendNextTurn:`Send next turn`,steerCurrentTurn:`Steer current turn`,steeringHint:`Use this instruction after the current tool step finishes.`,pendingSteeringHint:`{{count}} instructions received; waiting for the current tool step`,steeringMessagesTitle:`Pending instructions for this turn`,steerStaleTurn:`That turn has ended or changed. Your draft is kept; choose how to send it again.`,sourceFeedbackNew:`{{path}} · new line {{line}}`,sourceFeedbackOld:`{{path}} · old line {{line}}`,forkMessage:`Fork from here`,forkMessageHint:`Create a new conversation from this message. Keep the original conversation; no message is sent.`,forkSessionPending:`Creating a fork…`,forkSessionCreated:`Fork created. The original conversation remains in the sidebar.`,forkSessionCancelled:`Fork cancelled. The original conversation is kept.`,forkSessionUncertain:`The fork could not be confirmed. Refresh and inspect your conversations before trying again.`,forkSessionUnavailable:`Switch to this conversation and let its current work and queued messages finish before forking.`,reviewQuoteLine:`Reference this line`,reviewSelectOldLine:`Select old line {{line}}`,reviewSelectNewLine:`Select new line {{line}}`,queuedMore:`{{count}} more queued`,queuedImage:`Image attachment`,queuedMessageExpand:`Expand queued message`,queuedMessageCollapse:`Collapse queued message`,backgroundSessionRunning:`This session is running in the background…`,observedSessionTools:`{{count}} active tools`,toolsRequireCurrentSession:`Switch to this session to use interactive tools.`,activateViewedSession:`Switch to this session`,activateViewedSessionHint:`Send a message to continue this conversation.`,addWorkspace:`Add workspace`,addWorkspaceMenu:`Add workspace...`,archiveConversation:`Archive conversation`,pinnedConversations:`Pinned`,sidebarOptions:`Sidebar options`,sidebarProjectOptions:`Project sidebar options`,sidebarRecentOptions:`Chat sidebar options`,sidebarActivityOptions:`Activity view options`,sidebarShow:`Show`,sidebarGroupBy:`Group conversations`,sidebarByProject:`By project`,sidebarFlatList:`All conversations`,sidebarChatSort:`Conversation order`,sidebarRecent:`Recent`,sidebarProjectsInRecents:`Show projects in Recent`,sidebarShowMore:`Show more`,sidebarShowLess:`Show less`,sidebarFilterList:`Filter this list`,sidebarSaveFailed:`Could not save the change. Please try again.`,pinWorkspace:`Pin project`,unpinWorkspace:`Unpin project`,markConversationRead:`Mark as read`,markConversationUnread:`Mark as unread`,sidebarState_unread:`Unread conversation`,sidebarActivity:`Activity`,sidebarViewActivity:`View activity`,sidebarViewChats:`View conversations`,sidebarPriority:`Priority`,sidebarActivityEmpty:`Nothing needs attention`,sidebarActivityEmptyHint:`Completed work and conversations needing your attention appear here.`,sidebarMarkAllRead:`Mark all as read`,sidebarClearRead:`Clear read chats from Priority`,sidebarReadFailed:`Could not update read status. Please try again.`,sidebarToday:`Today`,sidebarYesterday:`Yesterday`,sidebarEarlier:`Earlier`,sidebarActivityCompleted:`Completed`,sidebarActivityFailed:`Failed`,sidebarActivityRead:`Read`,modelAdvanced:`Advanced parameters`,providerConnectionHeading:`Provider connection`,providerFetchModels:`Get available models`,providerFetchHint:`Enter the provider and endpoint, then choose models in one step.`,providerPickerTitle:`Choose models to add`,providerPickerAccess:`Connection credentials`,providerPickerKey:`Access key (optional)`,providerPickerKeyHint:`Leave blank to use saved credentials for this endpoint. A key entered here is used for discovery only and is not saved.`,providerPickerSearch:`Search models`,providerPickerSelectAll:`Select all`,providerPickerClear:`Clear selection`,providerPickerLoading:`Reading available models…`,providerPickerAdded:`Added`,providerPickerNoMatch:`No matching models`,providerPickerEmpty:`No models returned. You can still add one manually.`,providerPickerBounded:`Showing the first 500 models. Add other IDs manually.`,providerPickerError_load:`Could not read the model list. Check the endpoint and credentials, then retry or add a model manually.`,providerPickerError_save:`Could not confirm the save. Your selection is kept; check the connection before retrying.`,providerPickerError_conflict:`Configuration changed elsewhere. Close this dialog and reload configuration before saving again.`,providerPickerDefaults:`New models use {{context}} context / {{output}} output tokens. You can adjust these per model after adding.`,providerPickerRetry:`Refresh list`,providerPickerCount:`{{count}} selected · up to 100`,providerPickerSave:`Add selected`,sidebarState_running:`Running`,sidebarState_compacting:`Organizing context`,sidebarState_waiting:`Waiting for your response`,sidebarState_completed:`Completed · unread result`,sidebarState_failed:`Failed · open conversation for details`,pinnedOptions:`Pinned options`,pinConversation:`Pin conversation`,unpinConversation:`Unpin conversation`,pinnedRecentlyUpdated:`Recently updated`,pinnedManualOrder:`Manual order`,movePinUp:`Move up`,movePinDown:`Move down`,pinSaveFailed:`Could not save pinned conversations. Please try again.`,cancel:`Cancel`,chooseWorkspaceHint:`Choose a workspace and describe the work`,close:`Close`,closeSearch:`Close search`,collapseSidebar:`Collapse sidebar`,confirmEdit:`Save and rerun`,editMessageHint:`Rerun from here in a new branch. Keep the original conversation, images and file references. Existing workspace changes are kept.`,regenerateMessage:`Regenerate response`,regenerateMessageHint:`Rerun this question in a new branch, keeping its original attachments and conversation.`,messageRerunStarted:`Rerun admitted in a new branch. The original conversation is kept.`,openOriginalConversation:`View original conversation`,messageRerunWorkspaceHint:`Existing workspace changes are kept.`,modelRequestRecovered:`Request recovered`,modelReconnecting:`Reconnecting`,modelReconnectUnknown:`Reconnection status unconfirmed`,modelEarlierAttempts:`Earlier request errors`,modelFailedAttempts:`Failed attempts ({{count}})`,draftStorageUnavailable:`Draft could not be saved on this device. Keep this page open or copy your message.`,draftStorageInvalid:`Some saved draft content could not be restored. Check your message and attachments.`,draftStorageRetry:`Retry saving draft`,workbarBackToChat:`Back to chat`,workbarCollapseTools:`Collapse tools`,workbarEndTerminal:`Close {{name}} and end its process`,workbarNewTerminal:`New terminal`,workbarContinueInChat:`Continue in chat`,transcriptSearch:`Search message contents`,transcriptSearchPlaceholder:`Search titles, projects, or messages…`,transcriptSearchRecent:`Recent conversations`,transcriptSearchSessions:`Conversations`,transcriptSearchMessages:`Message contents`,transcriptSearchSessionResult:`Open conversation {{session}}`,transcriptSearchSessionOpenFailed:`Could not open this conversation. Try again.`,transcriptSearchIncludeArchived:`Include archived conversations`,transcriptSearching:`Searching messages…`,transcriptSearchEmpty:`No matching messages found.`,transcriptSearchFailed:`Could not search messages. Try again.`,transcriptSearchRetry:`Retry search`,transcriptSearchPartial:`Some history could not be searched. Results may be incomplete.`,transcriptSearchOpenFailed:`This message could not be opened. It may have moved or belong to another branch.`,transcriptSearchResult:`Open message from {{source}} in {{session}}`,transcriptSearchSource_user:`you`,transcriptSearchSource_assistant:`assistant`,transcriptSearchSource_tool_call:`tool call`,transcriptSearchSource_tool_result:`tool output`,connected:`Connected`,connecting:`Connecting`,conversationName:`Conversation name`,conversationOptions:`Conversation options`,sidebarRename:`Rename`,sidebarPin:`Pin`,sidebarUnpin:`Unpin`,sidebarFork:`Fork`,sidebarForkLocal:`Fork chat`,sidebarForkSameWorktree:`Fork in same worktree`,archiveNoticeTitle:`Chat archived`,archiveNoticeView:`View`,archiveNoticeUndo:`Undo`,archiveNoticeFailed:`Could not complete this action. Try again.`,sidebarForkWorktree:`Fork chat in new worktree`,sidebarForkCancelling:`Requesting cancellation…`,sidebarForkFinishing:`Cancellation is no longer available. Confirming the result…`,sidebarForkCancelUnconfirmed:`Cancellation could not be confirmed. Waiting for the fork result.`,sidebarForkWorktreePreserved:`The worktree was kept at {{path}}. Inspect it before retrying.`,sidebarForkWorktreePending:`Creating a worktree and conversation…`,sidebarForkOptionsLoading:`Checking worktree availability…`,sidebarForkOptionsFailed:`Unable to check worktrees. Reopen menu to retry.`,sidebarForkUnavailable:`Send a message before forking this conversation.`,sidebarForkArchived:`Restore this conversation before forking.`,sidebarForkFailed:`Could not create the fork. The original conversation is unchanged.`,sidebarCopy:`Copy`,sidebarCopyLink:`Copy conversation link`,sidebarCopyMarkdown:`Copy as Markdown`,sidebarCopyCwd:`Copy working directory`,sidebarCopied:`Copied`,sidebarCopyFailed:`Could not copy. Try again.`,sidebarNewWindow:`Open in new window`,sidebarOpenIn:`Open in`,sidebarAppsLoading:`Loading available apps…`,sidebarAppsFailed:`Unable to load apps. Reopen menu to retry.`,sidebarOpenFailed:`Unable to open this project in the selected app.`,sidebarArchive:`Archive`,sidebarRestore:`Restore`,sidebarDelete:`Permanently delete`,managedWorktreeRecoveryFull:`Check earlier unfinished removal requests before starting another.`,managedWorktreesChanged:`The worktree list changed. Refresh it before reviewing a target.`,managedWorktreesRefresh:`Refresh worktrees`,managedWorktreesBack:`Back to worktrees`,managedWorktreesRetry:`Retry request`,managedWorktrees:`Retained worktrees`,managedWorktreesDescription:`Worktrees created by OpenPI are kept when a conversation is deleted. Review an exact path before requesting removal. Active, shared, changed or unverified worktrees stay in place.`,managedWorktreeConfirm:`Remove this managed worktree? The server rechecks ownership, active conversations and local changes before removal.`,managedWorktreeRemoved:`Worktree removed.`,managedWorktreePreserved:`Worktree kept:`,managedWorktreeUncertainTerminal:`Removal outcome is uncertain. Automatic removal cannot be repeated. Inspect the retained path before taking further action.`,managedWorktreeUncertain:`Removal outcome is unknown. Retry to check the original request.`,managedWorktreeRemoving:`Checking and removing…`,managedWorktreeRemove:`Remove worktree`,managedWorktreeReview:`Review removal`,managedWorktreesEmpty:`No managed worktrees were found on this page.`,managedWorktreesUnavailable:`{{count}} ownership records could not be verified.`,managedWorktreesLoadFailed:`Could not load retained worktrees. Retry without changing the target.`,managedWorktreesMore:`Load more worktrees`,managedWorktreeRetainedAfterDelete:`Conversation deleted. Worktree kept at {{path}}. Review retained worktrees in the project menu.`,sidebarDeleteTitle:`Delete conversation?`,sidebarDeleteDescription:`Permanently delete “{{name}}”? This cannot be undone.`,sidebarDeleteConfirm:`Delete`,sidebarDeleting:`Deleting…`,sidebarDeleteFailed:`Could not delete this conversation. Retry or cancel.`,sidebarActionRunning:`Let current work and queued messages finish first.`,sidebarActionDisconnected:`Reconnect before changing this conversation.`,sessionDeleteCancelled:`Deletion cancelled`,sessionDeleteUncertain:`Could not confirm whether the conversation was deleted. Refresh and try again.`,sessionDeleted:`Conversation permanently deleted`,sessionDeleteMetadataPending:`The conversation was deleted, but its sidebar records could not be fully cleared.`,sessionLinkUnavailable:`The linked conversation no longer exists or its identity has changed.`,sidebarDropPin:`Drop here to pin`,sidebarDropProjectLast:`Move project to the end`,conversationTurns:`Conversation turns`,conversationTurnPosition:`Go to turn {{position}}`,turnPreviewLoading:`Loading preview…`,turnPreviewUnavailable:`Preview unavailable. Try again.`,commands:`Slash commands`,addContext:`Add context`,fileReference:`Reference workspace file`,fileReferenceTitle:`Reference workspace file`,fileReferenceDetail:`Add a path reference to the prompt without uploading file contents.`,fileReferenceLabel:`Workspace file path`,fileReferencePlaceholder:`src/app.tsx`,fileReferenceValidatedHint:`The current Session verifies that this is a readable workspace file.`,fileReferenceDraftHint:`This path will be resolved by Pi after the new Session starts.`,fileReferenceChecking:`Checking…`,fileReferenceFailed:`Could not verify this file.`,fileReferenceDenied:`Choose a file inside the current Session workspace.`,fileReferenceMissing:`This workspace file no longer exists.`,fileReferenceUnsupported:`Only regular workspace files can be referenced.`,fileReferenceExpired:`The active Session changed. Reopen the file reference and try again.`,fileReferenceBusy:`File validation is busy. Try again shortly.`,insertReference:`Insert reference`,commandsSessionRequired:`Slash commands are available after the Session starts.`,commandsEmptyDraftOnly:`Slash commands can be inserted only into an empty draft.`,commandsLoading:`Loading commands...`,commandsUnavailable:`Commands are temporarily unavailable.`,commandsNoMatch:`No matching commands.`,commandsNoAvailable:`No discovered commands can run in Web. Type a command name to inspect its availability.`,commandsBounded:`{{count}} more commands are not shown.`,commandSessionRequired:`Commands require an active Web session.`,commandUnsupported:`Not adapted · manual commands still reach Pi`,commandAcceptsArguments:`Accepts arguments`,commandSource_extension:`Extension`,commandSource_prompt:`Prompt template`,commandSource_skill:`Skill`,copiedMessage:`Copied`,copyMessage:`Copy message`,copyFailed:`Copy failed. Please select and copy the message manually.`,copiedCode:`Code copied`,copyCode:`Copy code`,copyCodeFailed:`Could not copy this code. Select and copy it manually.`,codeBlock:`Code block`,deleteWorkspace:`Delete workspace`,describeTask:`Describe a task`,editMessage:`Edit and rerun from here`,enterHint:`Enter to send, Shift+Enter for a new line.`,expandSidebar:`Expand sidebar`,importWorkspace:`Import workspace`,loadingModels:`Loading models...`,modelsTruncated:`Showing {{shown}} models. {{omitted}} more are available; search to find them.`,searchModels:`Search available models`,searchModelsPlaceholder:`Search provider, model name, or ID...`,searchingModels:`Searching models...`,noMatchingModels:`No matching models`,modelSearchFailed:`Could not search models. Try again.`,retryModelSearch:`Retry model search`,fileReferenceDraftChanged:`The draft changed. Reopen the file reference.`,modelSearchTruncated:`{{omitted}} matching models are not shown.`,modelPreparing:`Preparing task...`,modelRetrying:`Retrying model request...`,modelRunning:`Working...`,modelRequestFailed:`Model request failed`,modelRequestStopped:`Model request stopped`,modelFailureUnknown:`The provider did not return an error reason.`,retryPrompt:`Retry prompt`,retryingPrompt:`Retrying...`,newSession:`New session`,noConversations:`No conversations yet`,noMatching:`No matching conversations`,noMatchingLoaded:`No matching conversations in the loaded history`,noModels:`No models available`,noOutput:`no output`,noSessions:`No sessions`,openSidebar:`Open sidebar`,promptMessage:`Send a message or start a task, / for commands`,promptReadonly:`A non-active session cannot receive prompts`,promptStart:`Choose a workspace to begin.`,promptTask:`Describe what you want to build.`,landingTagline:`Small harness. Clean context. Deep extensions.`,queuedHint:`The message will be queued after the current turn.`,reconnecting:`Reconnecting`,removeWorkspace:`Remove from sidebar`,workspaceOptions:`Workspace options`,renameFailed:`Could not save the name. Your changes were kept.`,savingName:`Saving...`,workspaceRemoveFailed:`Could not remove the workspace. Try again.`,removingWorkspace:`Removing...`,renameConversation:`Rename conversation`,renameWorkspace:`Rename workspace`,save:`Save`,searchConversations:`Search conversations`,searchPlaceholder:`Filter titles and workspaces…`,selectModel:`Select model`,configureModels:`Configure models`,openModelSettings:`Model settings`,selectThinking:`Select thinking level`,resetThinking:`Restore the opening level ({{level}})`,modelThinkingNotEnabled:`Thinking is not enabled for this model. Enable reasoning support in model settings if your provider supports it.`,providerReasoningHint:`Enable only if the provider supports reasoning. Available levels come from Pi; adjust the level in the composer.`,providerImageHint:`When Image is unchecked, the model will not receive image attachments.`,selectWorkspace:`Select workspace`,send:`Send`,processDetails:`Execution details`,processRunning:`Working`,processThinkingCount_one:`{{count}} reasoning note`,processThinkingCount_other:`{{count}} reasoning notes`,processToolCount_one:`{{count}} tool call`,processToolCount_other:`{{count}} tool calls`,processActivityCount_one:`{{count}} agent activity`,processActivityCount_other:`{{count}} agent activities`,switchingSession:`Switching session...`,thinkingActive:`Thinking...`,thinkingActiveLevel:`Thinking ({{level}})...`,thinkingDone:`Thinking`,thinkingLoadFull:`Load full thinking`,thinkingLoadingFull:`Loading thinking…`,thinkingLoadFailed:`Unable to load thinking. Retry`,thinkingPartialText:`Showing part of the saved thinking. More text can be loaded below.`,thinkingPreviewOnly:`Thinking preview reached its limit. The full saved text will be available when this message finishes.`,toolState_running:`Running`,toolState_returned:`Returned`,toolState_failed:`Failed`,toolState_cancelled:`Stopped`,toolState_timed_out:`Timed out`,toolState_unknown:`Unconfirmed`,toolSnapshotMissingResult:`No result at fork`,toolActivity_running:`{{action}}…`,toolActivity_failed:`{{action}} failed`,toolActivity_cancelled:`{{action}} stopped`,toolActivity_timed_out:`{{action}} timed out`,toolActivity_unknown:`{{action}}`,toolAction_read:`Read`,toolAction_write:`Write file`,toolAction_edit:`Edit file`,toolAction_command:`Run command`,toolAction_search:`Search`,toolAction_list:`List files`,toolAction_web:`Browse web`,toolAction_agent:`Agent activity`,toolAction_workflow:`Workflow`,toolAction_plan:`Prepare plan`,toolAction_task:`Update tasks`,toolAction_goal:`Update goal`,toolAction_git:`Review changes`,toolAction_call:`Use tool`,toolActionDone_read:`Read`,toolActionDone_write:`Wrote file`,toolActionDone_edit:`Edited`,toolActionDone_command:`Ran command`,toolActionDone_search:`Searched`,toolActionDone_list:`Listed files`,toolActionDone_web:`Browsed web`,toolActionDone_agent:`Agent activity returned`,toolActionDone_workflow:`Workflow tool returned`,toolActionDone_plan:`Plan tool returned`,toolActionDone_task:`Task tool returned`,toolActionDone_goal:`Goal tool returned`,toolActionDone_git:`Reviewed changes`,toolActionDone_call:`Used tool`,toolActionGroup_read:`read files`,toolActionGroup_write:`write files`,toolActionGroup_edit:`edit files`,toolActionGroup_command:`run commands`,toolActionGroup_search:`search`,toolActionGroup_list:`list files`,toolActionGroup_web:`browse web`,toolActionGroup_agent:`agent activity`,toolActionGroup_workflow:`workflow activity`,toolActionGroup_plan:`planning`,toolActionGroup_task:`tasks`,toolActionGroup_goal:`goal`,toolActionGroup_git:`review changes`,toolActionGroup_call:`use tools`,toolGroup_done:`Activity · {{actions}}`,toolGroup_running:`Working · {{actions}}`,toolGroup_unknown:`Activity · {{actions}}`,toolGroupSeparator:`, `,toolSearchTarget:`“{{pattern}}” · {{path}}`,toolDiffStatsHelp:`Added and removed lines in the displayed diff`,toolRequestedFile:`File:`,toolWorkspace:`Workspace`,toolRawEvidence:`Arguments and original result`,toolCodemodeDetails:`Script and original result`,toolNestedOutputMissing:`This session records the call and its status, but not the nested tool output.`,toolNestedArgumentsMissing:`This session omits the full arguments and nested tool output.`,toolNestedIncomplete:`The nested-call record is incomplete; some calls, arguments or final states are unavailable.`,toolPartialEvidence:`Partial output: a byte, line or item limit was reached. The original result may also be truncated.`,toolFileChange_created:`File created`,toolFileChange_unchanged:`No content changes`,toolFileChange_overwritten:`File overwritten`,toolChangeUnavailable:`This result does not include a change comparison.`,toolTestResults:`Reported test results · {{format}}`,toolTestCounts:`{{tests}} tests · {{passed}} passed · {{failed}} failed · {{cancelled}} cancelled`,toolTestCountsHelp:`Counts come from command output. The execution status is shown separately.`,toolReadMore:`Read another range using the path and offset. The original result contains continuation details.`,toolFullOutputReference:`Full output:`,subagentBackgroundResult_one:`Background subagent result · {{count}}`,subagentBackgroundResult_other:`Background subagent results · {{count}}`,thinkingDraftHint:`Choose a workspace and create a session first.`,thinkingInactiveHint:`Only the active session can change its thinking level.`,thinkingLevelMismatch:`The confirmed thinking level is not offered by the current model. Choosing another level will correct it.`,thinkingLockedRunning:`Stop the current turn before changing the thinking level.`,thinkingModelPendingHint:`Wait for the model change to finish.`,thinkingNotConfirmed:`Thinking level was not confirmed. Please try again.`,thinkingPendingHint:`Applying the thinking level...`,thinkingUnsupported:`Thinking is unavailable`,thinkingUnsupportedHint:`No model is selected, or the current model does not support thinking.`,unavailable:`Unavailable`,ungrouped:`Ungrouped`,untitledSession:`New session`,workspaceDeleteConfirm:`The folder and conversation records will be kept. Its conversations will move to Ungrouped.`,workspaceName:`Workspace name`,workspaces:`Workspaces`,sidebarProjects:`Projects`}},zh:{translation:{promptPending:`正在处理请求…`,commandFeedbackTruncated:`这里只显示部分命令结果。请缩小查询范围,或在 TUI 查看完整输出。`,planMode_inactive:`普通模式`,planMode_planning:`规划中 · 禁止写入`,planMode_ready:`计划就绪 · 等待审阅`,planMode_invalid:`计划状态异常 · 禁止写入`,planModeEnter:`进入规划`,promptPlanMessage:`本次对话使用 Plan 模式 · 继续讨论计划,暂不实施`,planModeUnconfirmed:`暂时无法确认 Plan 状态,请刷新后再继续。`,planModeExit:`退出规划`,planModeImplement:`准备实施提示`,planImplementationReplaceDraft:`准备实施会替换当前草稿并关闭规划模式,但不会发送提示词。是否继续?`,commandSupport_plan:`支持规划和准备当前会话的实施提示;新建实施会话仍需使用 TUI。`,commandSupport_setup:`通过当前模型配置,在 Web 回答问题。`,handoffWaiting:`需要你操作`,handoffDone:`已完成`,handoffUnable:`无法完成`,handoffDoneHelp:`已执行操作,接下来由模型验证结果。`,handoffUnableHelp:`未能完成,可以补充遇到的障碍。`,handoffReview:`复核状态`,handoffSubmit:`提交状态`,handoffSignal:`预期结果:`,handoffVerify:`提交完成后,模型仍需验证结果;你的反馈本身不代表验证成功。`,planCardLabel:`开发计划`,planCardReady:`计划已就绪`,planCardResult:`计划结果`,planCardNotApproval:`此步骤仅生成计划,不代表已批准或开始实施。`,planCardCollapse:`收起`,planCardExpand:`展开`,planCardCopy:`复制计划`,planCardCopyPreview:`复制可见预览`,planCardTruncated:`当前仅显示截断预览。`,planCardLoadFull:`加载完整计划`,planCardLoadingFull:`正在加载计划...`,planCardLoadFailed:`无法加载完整计划,重试`,planCardEvidence:`工具结果 · plan_ready`,questionWaiting:`问题`,questionPreview:`查看预览`,questionSkip:`跳过`,questionProgress:`{{current}} / {{total}}`,questionReview:`复核答案`,questionReviewTitle:`确认这些选择?`,questionReviewHelp:`可以返回修改,点击提交后才会发送给助手。`,questionEdit:`修改答案:{{question}}`,questionDismiss:`关闭提问,不提交答案`,questionCustom:`或自行撰写回复`,questionCustomHelp:`留空提交,表示希望助手把问题说清楚或拆小。`,questionYourAnswer:`你的答案`,questionCustomPlaceholder:`说说你的想法…`,questionNotes:`补充说明(选填)`,questionNotesPlaceholder:`补充限制条件,或解释你的选择…`,questionRephrase:`请助手把问题说清楚或拆小`,questionBack:`上一步`,questionNext:`下一题`,questionSubmit:`提交答案`,questionSubmitting:`正在提交…`,questionRetry:`核对提交结果`,questionUncertain:`暂时无法确认是否送达,已保留本次提交的答案。点击核对可恢复结果,不会重复提交。`,questionDisconnected:`正在重新连接… 已保留你的选择,暂时无法提交。`,questionLimit:`每项答案或补充说明不能超过 {{count}} 个 UTF-8 字节。`,questionLoadFailed:`暂时无法读取等待回答的问题。`,questionDraftLimit:`提问草稿已达上限,请缩短或清空已有答案后再添加内容。`,questionRetryLoad:`重试`,questionCloseReceipt:`关闭问答状态提示`,questionState_dismissed:`已关闭提问,没有提交答案。`,questionState_cancelled:`提问已取消,没有提交答案。`,questionState_expired:`提问已过期,没有提交答案。`,questionState_stale:`该提问已失效,请查看对话中的处理结果。`,conversationView:`会话视图`,jumpToLatest:`跳至最新`,historyLoading:`正在加载历史…`,historyOmitted:`还有 {{count}} 条较早记录 · 向上滚动自动加载`,historyChanged:`会话分支已更改,已切换到当前分支的历史。`,historyUnavailable:`历史记录加载失败,请重试。`,historyValidationUnavailable:`无法校验会话历史,请重试。`,historyVerifying:`正在校验会话历史…`,messageLoadFull:`加载完整消息`,messageLoadMore:`加载更多`,messageLoadingFull:`正在加载消息…`,messageLoadFailed:`无法加载这条消息,重试`,filePreview:`文件预览`,changeEvidence:`变更`,changeEvidenceScope:`按所选范围查看当前工作目录的只读 Git 变更。`,turnLabel:`第 {{number}} 轮`,turnState_running:`运行中`,turnState_complete:`已完成`,turnState_failed:`失败`,turnState_interrupted:`已中断`,turnState_waiting:`等待回复`,turnState_forked:`已分叉,可继续对话`,turnChanges:`本轮更改 {{count}} 个文件`,turnChangesPartial:`本轮已记录 {{count}} 个文件`,turnChangesIncomplete:`这一轮的变更记录不完整。`,turnChangesMore:`再显示 {{count}} 个文件`,turnChangesLess:`收起文件`,turnChangesReview:`审阅本轮变更`,turnChangesReviewButton:`审阅`,turnChangesBack:`返回本轮变更`,turnChangesLoading:`正在加载本轮变更…`,turnChangesUnavailable:`无法读取本轮保存的差异。`,messageCopyRequiresFull:`加载完整消息后才能复制。`,filesChanged:`{{count}} 个文件已更改`,reviewChanges:`查看变更`,workspaceChanges:`工作区更改`,overviewChanges:`变更`,overviewLineTotals:`当前 Git 比较范围内的文本新增与删除行数`,overviewPartialTotals:`仅展示已核实的行数,部分文件尚无法统计。点击变更查看详情。`,overviewCounting:`统计中…`,overviewCountsUnknown:`行数未知`,overviewReviewUnavailable:`暂不可用`,sessionSources:`来源`,sourcesAdd:`添加来源`,sourcesEmpty:`暂无来源`,sourcesFailed:`来源加载失败。`,sourcesViewAll:`查看全部`,sourcesLoadMore:`加载更多来源`,sourcesBack:`返回来源列表`,sourcesPartial:`已达到列表展示上限,更早的来源仍可在对话中查看。`,turnChangesScope:`该轮开始至结束的工作区差异 · 已保存`,turnEdits:`已编辑 {{count}} 个文件`,turnEditsPartial:`已记录 {{count}} 个文件的编辑`,turnEditsScope:`本轮文件工具写入记录 · 已保存;不含命令行与外部修改`,turnEditStatsUnknown:`行数未知`,turnEditReason_before_unavailable:`文件已写入,但该操作未授权读取旧内容,无法提供可靠的前后差异。`,turnEditReason_content_limit:`文件已写入,内容超过已保存对比的大小限制,无法提供准确行数。`,turnEditReason_concurrent_change:`文件在已记录的操作之间发生了变化,无法确认本轮净增删行数。`,gitReviewLoadedCount:`已载入 {{count}} 个文件`,gitReviewPartialLabel:`部分`,gitReviewSearch:`搜索文件路径`,gitReviewExpand:`展开审阅`,gitReviewSearchLoaded:`搜索已载入文件`,gitReviewMarkViewed:`标记 {{path}} 为已查看`,gitReviewMarkCurrentViewed:`标记当前文件 {{path}} 为已查看`,gitReviewViewedLabel:`已查看`,gitReviewViewedProgress:`已查看 {{viewed}} / 已加载 {{loaded}} 个文件`,gitReviewViewedLimit:`本次对比最多保留 {{count}} 个已查看标记。`,gitReviewNoMatch:`没有匹配的文件。`,gitReviewNoLoadedMatch:`已载入文件中没有匹配项。`,gitReviewLoadNext:`载入下一批文件`,gitReviewChanged:`工作区已有变化,请刷新清单后继续载入。`,gitReviewNewVersion:`有新的更改,当前仍显示你正在阅读的版本。`,gitReviewShowLatest:`查看最新差异`,gitReviewBinary:`此二进制文件无法显示文本差异。`,gitReviewBinaryShort:`二进制`,gitReviewPendingStats:`待读取`,gitReviewComparison:`{{current}} 对比 {{base}}`,gitReviewWorkingTree:`工作区对比 HEAD`,gitReviewSessionSnapshot:`自本会话开始后的变更`,gitReviewDetached:`游离 HEAD`,gitReviewLoading:`正在读取 Git 变更…`,gitReviewRetry:`重试`,gitReviewRefresh:`刷新变更`,gitReviewOlderResult:`当前显示上一次读取结果。`,gitReviewNotRepository:`此工作区不是 Git 仓库。`,gitReviewUnborn:`此仓库还没有可读取的 HEAD。`,gitReviewFailed:`无法读取 Git 变更。`,gitReviewTruncated:`结果不完整,部分文件或差异未载入。`,gitReviewEmpty:`当前范围内没有文件变更。`,gitReviewHiddenLines:`另有 {{count}} 行 diff 未显示。`,gitReviewDiffTruncated:`快照已达到大小上限,未加载此文件的 diff。`,gitReviewShowMore:`再显示 {{count}} 个文件`,gitReviewBackToFiles:`返回变更文件`,gitReviewFilePreview:`{{file}} 的差异`,gitReviewNoDiff:`此文件没有可显示的文本差异。`,changeDiff:`变更差异`,diffView:`差异`,gitFileStatus_added:`已新增`,gitFileStatus_modified:`已修改`,gitFileStatus_deleted:`已删除`,gitFileStatus_renamed:`已重命名`,gitFileStatus_copied:`已复制`,gitFileStatus_untracked:`未跟踪`,gitFileStatus_unknown:`已变更`,closePreview:`关闭预览`,artifactReadOnly:`只读`,artifactReferenceUnavailable:`此视图无法打开文件预览:{{path}}`,artifactSession:`所属会话 {{sessionId}}`,copyFilePath:`复制文件路径`,filePathCopied:`已复制文件路径`,refreshFile:`刷新文件`,downloadFile:`下载文件`,downloadingFile:`正在下载…`,artifactOlderPreview:`当前显示旧版预览。`,readingFile:`正在读取文件…`,artifactVersion:`版本`,artifactBytes:`{{count}} 字节`,artifactPreviewTruncated:`预览已截断;下载文件可获取完整内容。`,artifactUnsupported:`此类型无法预览,请下载文件。`,chatView:`对话`,trajectory:`执行轨迹`,trajectoryScope:`按记录顺序展示会话消息,不表示执行耗时,也不是完整模型请求。`,trajectoryRunning:`任务仍在进行。已保存记录到达后自动更新;实时生成内容可在“对话”中查看。`,trajectoryTruncated:`当前历史不完整:省略 {{entries}} 条记录、{{parts}} 个内容片段,{{messages}} 条消息被截断。`,trajectoryEmpty:`尚无已保存记录。`,trajectoryOrder:`记录顺序`,trajectoryRecordCount:`{{count}} 条记录`,trajectoryMatches:`{{count}} 条匹配`,trajectorySearch:`搜索已加载记录`,trajectoryNoMatches:`没有匹配的记录。`,trajectoryEarlierGroup:`较早上下文`,trajectoryEventCount:`{{count}} 条会话变更`,trajectorySummary:`概览`,trajectoryInputTab:`输入`,trajectoryResultTab:`结果`,trajectoryConversationGroup:`本轮对话`,trajectoryReasoningTitle:`思考`,trajectoryRecordNumber:`记录 {{number}}`,trajectoryRecordInfo:`记录信息`,trajectoryRecordId:`记录 ID`,trajectoryCallId:`工具调用 ID`,trajectoryEventType:`事件类型`,trajectoryEvent_model_change:`切换模型`,trajectoryEvent_thinking_level_change:`调整思考级别`,trajectoryEvent_compaction:`压缩上下文`,trajectoryEvent_session_info:`更新会话信息`,trajectoryEvent_custom:`会话记录`,trajectoryEarlier:`显示更早记录(已加载历史中还有 {{count}} 条)`,trajectoryDetails:`记录详情`,trajectoryRecordedAt:`记录时间`,trajectoryEvidenceTruncated:`此证据在会话投影中已被截断。`,trajectoryArguments:`工具参数`,trajectoryRecordedContent:`已记录内容`,trajectoryThinking:`模型返回的推理内容`,trajectoryOutput:`工具结果`,trajectoryMissingResult:`当前记录中没有可明确配对的结果。这不表示工具仍在运行。`,trajectoryStructured:`结构化结果`,trajectoryEventOnly:`当前仅提供此事件的类型和记录时间。`,trajectory_user:`用户消息`,trajectory_assistant:`助手回复`,trajectory_call:`工具调用`,trajectory_result:`未配对结果`,trajectory_event:`会话事件`,trajectory_returned:`工具已返回结果。`,trajectory_error:`工具返回错误`,trajectory_unknown:`尚无法确定结果`,runtimeStatus:`运行状态`,refreshStatus:`刷新状态`,terminalDetails:`终端详情`,openTools:`打开工具`,sideConversation:`侧边对话`,sideConversationDescription:`在独立 Pi 会话中追问具体问题,不打断当前主任务。`,workbarChangesDescription:`查看当前目录的未暂存、已暂存、分支或会话变更。`,terminal:`终端`,renameTerminal:`重命名终端`,terminalName:`终端名称`,workbarTerminalDescription:`打开当前工作区的交互式终端。`,backgroundTerminalActivity:`Agent 命令活动`,restartTerminal:`重新启动终端`,reconnectTerminal:`重新连接终端`,restartTerminalTitle:`重新启动此终端?`,restartTerminalDetail:`当前终端会被关闭,其中运行的进程可能被中断。`,terminalReconnecting:`正在重新连接终端...`,terminalScrollToBottom:`回到底部`,terminalOutputResynced:`终端输出已重新同步`,terminalRestarting:`正在重新启动终端...`,terminalConnecting:`正在启动终端…`,terminalExited:`终端已退出。`,terminalExitCode:`终端已退出,状态码 {{code}}。`,terminalDisconnected:`终端连接意外中断。`,terminalError:`终端不可用。`,browser:`浏览器`,sessionFileRecords:`本会话文件记录`,gitReviewSource:`变更范围`,gitReviewBaseBranch:`对比分支`,gitReviewChooseBase:`选择对比分支`,gitReviewSearchBranches:`搜索分支`,gitReviewLocalBranch:`本地分支`,gitReviewRemoteBranch:`远程分支`,gitReviewBranchesTruncated:`显示有数量限制的分支列表,部分分支已省略。`,gitReviewNoMatchingBranches:`没有匹配的分支。`,gitReviewBaseUnavailable:`没有可用的默认对比分支。请选择分支以审阅已提交的变更。`,gitReviewBaseInvalid:`所选对比分支已不可用,请选择其他分支。`,gitReviewUnstaged:`未暂存(含未跟踪)`,gitReviewStaged:`已暂存变更`,gitReviewBranch:`分支变更`,gitReviewFileMissing:`此文件在当前范围内已无变更,请刷新文件列表。`,artifactExternalAccess:`此文件位于其他工作目录。可为当前会话授权只读打开这一个文件,不会开放其他文件的访问。`,artifactAuthorizeFile:`只读打开此文件`,sideConversationPending:`正在准备侧边会话…`,resizeSidebar:`调整侧边栏宽度`,resizePanes:`调整面板宽度`,resizeWorkbar:`调整工具栏宽度`,browserPasteTooLarge:`每次最多粘贴 {{count}} 个字符。`,browserInputTooLarge:`每次最多输入 {{count}} 个字符。`,browserInputTargetChanged:`输入目标已变化或无法确认,有输入操作未执行。`,workbarBrowserDescription:`在 OpenPI 工作栏内打开并操作网页。`,browserReady:`输入地址开始浏览`,browserStarting:`正在启动内嵌浏览器…`,browserOpened:`已在内嵌浏览器中打开`,browserOpenAgain:`再次打开`,browserOpenFailed:`内嵌浏览器暂不可用。`,browserBack:`后退`,browserForward:`前进`,browserReload:`重新加载`,browserTabs:`网页标签页`,browserNewTab:`新标签页`,browserAddTab:`新建网页标签页`,browserCloseTab:`关闭 {{title}}`,browserTabLimit:`最多打开 {{count}} 个网页标签页`,browserPageTitle:`网页:{{address}}`,browserEnteredAddress:`最近从此地址栏打开的地址`,browserAddressNotAllowed:`请输入不含用户名或密码、且不属于 OpenPI 自身地址的 HTTP(S) 网址。`,browserLocationUnknown:`网页已跳转,新地址无法读取。重新加载会返回你输入的地址。`,browserDirectDescription:`直接浏览网页。不允许嵌入的网站可在外部浏览器打开。`,browserDirectHint:`地址栏仅记录手动打开的地址。网页弹窗在外部浏览器打开;遇到空白页,可点击外部打开。`,browserEnhancedHint:`浏览增强已开启:地址自动同步,普通弹窗链接在内部标签页打开。部分站点限制、登录弹窗和跨站历史仍需外部浏览器。`,files:`文件`,filesExplorer:`工作区文件`,filesSearch:`筛选文件…`,refreshFiles:`刷新文件`,filesWorkspaceActions:`工作区文件操作`,filesCreateMenu:`新建`,filesImportMenu:`导入`,filesMoreMenu:`更多`,filesNewFile:`新建文件`,filesNewDirectory:`新建文件夹`,filesImport:`导入文件`,filesImportFolder:`导入文件夹`,filesImportFolderChoose:`选择要导入的文件夹`,filesImportFolderLimit:`每次最多导入 2,000 个文件和文件夹,目录层级最多 64 层。`,filesSelectMultiple:`多选文件`,filesSelectItem:`选择 {{name}}`,filesSelectedCount:`已选 {{count}} 项`,filesRename:`重命名`,filesNewName:`新名称`,filesMove:`移动`,filesMoveDestination:`目标文件夹(工作区内相对路径)`,filesTrashAction:`移入回收站`,filesTrash:`工作区回收站`,filesTrashDetail:`移除的文件保留在当前工作区,可恢复;不会覆盖同名文件。`,filesTrashEmpty:`暂无已移除文件`,filesTrashUnavailable:`{{count}} 项记录无法核验,内容仍保留在 .openpi-trash 中,暂不能自动恢复。`,filesRestore:`恢复`,filesRestoreItem:`恢复 {{name}}`,filesUndoTrash:`撤销移除`,filesOrganizationResults:`文件操作结果`,filesOperationDone:`完成`,filesRefreshBeforeOrganizing:`请先刷新文件树,再整理这项文件。`,filesImportChoose:`选择要导入的文件`,filesTargetDirectory:`目标目录`,filesWorkspaceRoot:`工作区根目录`,filesFileName:`文件名称`,filesDirectoryName:`文件夹名称`,filesCreate:`创建`,filesCreating:`创建中…`,filesCreated:`已创建:{{path}}`,filesNameInvalid:`请输入单个文件或文件夹名称,不要包含路径分隔符。`,filesNameExists:`此名称已存在,请更换名称;原有文件已保留。`,filesMutationFailed:`写入失败,输入已保留。`,filesWriteUnavailable:`请先切换到此会话,再修改工作区文件。`,filesImportLimit:`每个文件最多 50 MiB,同名文件不会覆盖。`,filesImportTooLarge:`此文件超过 50 MiB 导入上限。`,filesImportDirectoryUnsupported:`不支持导入整个文件夹,请选择其中的文件。`,filesImportResults:`文件导入结果`,filesImportPending:`等待导入`,filesImporting:`导入中…`,filesImported:`已保存到工作区`,filesImportedNoPreview:`已保存。预览上限为 20 MiB;可复制路径,在对话中引用此文件。`,filesClearImported:`清除已完成的导入`,filesRetryImport:`重试导入`,filesPathActions:`{{name}} 的路径操作`,filesCopyRelativePath:`复制相对路径`,filesCopyAbsolutePath:`复制绝对路径`,filesPathCopied:`已复制路径:{{path}}`,filesReadFailed:`无法读取文件。`,filesSymlink:`符号链接,文件浏览器不会自动跟随`,filesTruncated:`结果不完整,请缩小搜索范围。`,filesNoMatches:`没有匹配的文件`,filesEmpty:`此文件夹为空`,filesChoose:`选择文件进行预览`,filesChooseDetail:`从右侧浏览工作区文件,在这里直接预览。`,filesHideTree:`收起文件树`,filesShowTree:`显示文件树`,filesPreview:`预览`,filesSource:`查看源代码`,filesEdit:`编辑`,filesMode:`文件视图`,filesEditor:`文件编辑器`,filesSave:`保存文件`,filesSaving:`保存中…`,filesSaved:`已保存`,filesUnsaved:`未保存的修改 · 草稿保留在当前窗口`,filesDiscard:`放弃草稿`,filesDiscardConfirm:`放弃此文件尚未保存的修改?`,filesSaveConflict:`磁盘上的文件已改变,编辑草稿已保留。请刷新查看最新内容,核对修改后再保存。`,filesSaveFailed:`保存失败,编辑草稿已保留。请检查文件后重试。`,filesEditLoadFirst:`请先继续读取完整文件,再编辑。`,filesEditUnavailable:`支持编辑工作区内不超过 1 MiB 的 UTF-8 文本,最多保留 16 份未保存草稿。`,filesOutline:`章节目录`,filesDiskVersion:`查看当前磁盘版本`,filesReconcile:`已核对,保留草稿并基于此版本继续编辑`,filesTable:`表格预览`,filesRow:`行`,filesSheets:`工作表`,filesTableTruncated:`当前显示部分表格;下载文件可查看全部行列。`,filesOfficeLayout:`文档内容预览;分页和排版可能与 Office 不同。`,filesSlidesLayout:`幻灯片文字与图片预览;主题、图表和动画可能与 PowerPoint 不同。`,filesPreviousPage:`上一页`,filesNextPage:`下一页`,filesZoomOut:`缩小`,filesZoomIn:`放大`,filesZoomReset:`重置缩放`,filesPdfPage:`第 {{page}} 页`,filesDocumentLimit:`此文档超出预览处理范围,请下载后在本地打开。`,filesPreviewFailed:`无法预览此文件,仍可下载后打开。`,filesDiagram:`Mermaid 图表`,filesExpandDiagram:`放大图表`,filesFitImage:`适应宽度`,filesOriginalImage:`原始尺寸`,filesLoadMore:`加载更多`,filesLoaded:`已加载 {{count}} 项`,filesReadMore:`继续读取`,filesContentChanged:`文件已更新。当前阅读内容已保留,可在准备好后刷新。`,workbarFilesDescription:`浏览工作区文件,在文件树旁直接预览。`,backToSideConversations:`返回侧边对话`,continueSideConversation:`继续追问…`,startSideConversation:`提出一个侧边问题…`,sideConversationModelInherited:`新侧边对话使用主会话的模型与思考等级。`,sideConversationModelFixed:`这是当前侧边对话使用的模型。`,stop:`停止`,start:`开始`,browserAddress:`浏览器地址`,browserGo:`打开地址`,openExternalBrowser:`在外部浏览器打开`,invalidBrowserAddress:`请输入有效的 HTTP 或 HTTPS 地址。`,addImages:`添加图片`,addFiles:`添加文件`,fileAttachments:`文件附件`,previewFileAttachment:`预览文件`,fileAttachmentDescription:`文档、表格、PDF、文本、代码及其他文件`,fileAttachmentCount:`最多可添加 {{count}} 个附件。`,fileAttachmentTooLarge:`文件总大小不能超过 50 MB。`,fileAttachmentReadFailed:`无法读取此文件,请检查格式或是否有密码保护。`,fileAttachmentTextReady:`文本已就绪`,fileAttachmentTextTruncated:`部分文本 · 保留原文件`,fileAttachmentOriginalReady:`原文件已就绪`,fileAttachmentExtractionFailed:`未提取文本 · 原文件保留`,fileAttachmentEncodingUnavailable:`无法读取文本编码,原文件字节已保留。`,fileAttachmentDocumentUnavailable:`无法提取文本。文件可能受密码保护或格式暂不支持,原文件字节已保留。`,fileAttachmentNoText:`发送后,代理可通过工具读取原文件;此文件未提取出文本。`,fileAttachmentPreviewTruncated:`预览显示前 20,000 个字符,发送时会附上全部已提取文本。`,fileAttachmentExtractedContent:`已提取文本`,fileAttachmentPromptLabel:`用户提供的文件:`,fileAttachmentPromptTooLong:`消息和文件引用超过输入限制,请缩短消息或减少附件。`,imageAttachmentDescription:`支持 PNG、JPEG、GIF 或 WebP`,imageAttachments:`图片附件`,imageAttachmentsLoading:`正在准备附件…`,commandOpensPanel:`打开面板`,commandPanelArguments:`此命令用于打开面板,不能携带参数或图片。请移除后重试,或直接使用对应面板。`,commandPanelUnavailable:`未能打开面板,已保留命令。`,commandUnavailable_terminal_only:`需要在 Pi 终端界面中使用。`,commandUnavailable_not_integrated:`此扩展命令尚未接入 Web,请在 Pi 终端中使用。`,artifactImagePreviewFailed:`图片预览失败。请刷新文件重试,或下载后查看。`,artifactFileDetails:`文件信息`,turnElapsedRunning:`已处理 {{duration}}`,compactionElapsed:`已等待 {{duration}}`,compactionRunning:`正在压缩上下文`,compactionCompleted:`上下文已自动压缩`,compactionFailed:`上下文压缩失败`,compactionInterrupted:`压缩已中断`,compactionUnchanged:`压缩已结束,未生成新的摘要`,compactionUnavailable:`上下文压缩状态暂不可用`,compactionReconnectHelp:`连接已中断,恢复连接后将核实当前状态。`,compactionDraftHelp:`正在压缩上下文,发送的消息会排队等待。`,turnElapsedFinished:`用时 {{duration}}`,composerAdd:`添加`,composerCommands:`指令`,composerFile:`文件`,composerGoal:`目标`,composerPlan:`计划`,composerCompact:`压缩`,composerModel:`模型`,composerBack:`返回`,composerGoalDescription:`设置或查看长期任务目标`,composerPlanDescription:`进入或退出计划模式`,composerCompactDescription:`整理之前的对话,释放上下文空间`,composerModelDescription:`选择本会话使用的模型`,compactionQueueWaiting:`等待压缩完成`,compactionQueueBlocked:`消息已保留,可重试或清空队列。`,clearPromptQueue:`清空队列`,turnElapsedOutcome_cancelled:`已停止`,turnElapsedOutcome_failed:`失败`,turnElapsedOutcome_uncertain:`结果待确认`,settingsSetupBusyHint:`Agent 配置需等待当前轮次结束;显示设置可直接调整。`,resetChatContentWidth:`恢复默认聊天宽度`,resetChatFontSize:`恢复默认字体大小`,setupResolveAdmission:`请先返回对话,处理尚未确认的消息,再应用设置。`,removeAttachment:`移除附件`,dropImagesHere:`将文件或图片拖到这里`,imageAttachmentCount:`最多可添加 {{count}} 张图片。`,imageAttachmentTooLarge:`单张图片不能超过 10 MB。`,imageAttachmentTotalTooLarge:`图片总大小不能超过 32 MB。`,imageAttachmentUnsupported:`仅支持有效的 PNG、JPEG、GIF 和 WebP 图片。`,imageAttachmentReadFailed:`无法读取此图片,请重新添加重试;消息内容已保留。`,attachedImage:`已附加图片`,previewAttachment:`预览图片`,closeImagePreview:`关闭图片预览`,imagePreviewFailed:`无法显示这张图片。`,fitImage:`适应窗口`,originalImageSize:`原始尺寸`,imageViewMode:`图片查看`,sessionUsage:`会话 Token 用量`,sessionInputTokens:`输入 Token`,sessionOutputTokens:`输出 Token`,sessionCacheTokens:`缓存 Token`,sessionContextUsage:`上下文占用与窗口大小`,usageContextLabel:`上下文`,usageUnknown:`未知`,usageOpenDetails:`输入 {{input}} · 输出 {{output}} · 上下文 {{percent}} / {{capacity}} · 查看会话用量`,usageContextHelp:`当前分支的估算占用 / 模型上下文容量上限。`,usageSessionTotals:`累计用量`,usageInputLabel:`输入`,usageOutputLabel:`输出`,usageTotalLabel:`总计`,usageWorkspaceLabel:`工作区`,usageSessionId:`会话 ID`,usageTotalsHelp:`本会话累计 Token 用量,包含缓存。`,subagentDetails:`子代理`,sessionOverview:`会话概览`,sessionOverviewChanges:`当前审阅范围的更改`,subagentSummaryRunning:`{{count}} 运行中`,subagentSummaryDone:`{{count}} 完成`,subagentSummaryOther:`{{count}} 其他记录`,subagentNoneYet:`暂无子代理`,subagentOtherGroup:`失败 / 已中断`,subagentShowMore:`再显示 {{count}} 个`,backToSubagents:`返回子代理列表`,subagentActiveGroup:`运行中`,subagentFinishedGroup:`完成`,subagentNoneRunning:`暂无正在运行的子代理。`,subagentNoneFinished:`任务结束后会显示在这里。`,subagentProgress:`子代理:{{running}} 运行中 · {{completed}} 已完成`,subagentSummaryUnknown:`{{count}} 个状态未确认`,subagentTasks:`子代理任务列表`,inspectSubagent:`打开子代理:{{name}}`,subagentState_running:`运行中`,subagentState_done:`已完成`,subagentState_error:`失败`,subagentState_interrupted:`已中断`,subagentStarting:`正在启动…`,subagentSpawnFailed:`启动失败`,subagentStateUnavailable:`已启动 · 状态未保留`,subagentSpawnReceipt:`启动回执`,subagentSpawnReceiptHint:`此回执仅确认启动请求,不表示子代理任务已完成。`,subagentTask:`分配的任务`,subagentTranscript:`子代理对话`,subagentResult:`执行结果`,subagentSaved:`已保存记录`,subagentRecordedState:`最后记录的状态`,subagentSavedHint:`来自当前父会话已保存的回执;结果可能包含同批其他任务,并非子代理的完整实时对话。`,subagentLive:`正在执行 · 自动更新`,subagentReadOnly:`只读查看 · 关闭此面板不会停止任务`,subagentUnavailable:`当前会话已无法提供此子代理的实时详情。启动回执不代表任务已完成。`,subagentStale:`刷新失败,下方保留的是上次收到的状态。`,subagentNoMessages:`暂未收到消息。`,subagentTranscriptUnavailable:`此视图仅保留任务摘要,无法显示完整子代理对话。`,subagentWorkflowsTruncated:`另有 {{count}} 个 workflow 未包含在当前列表中,其任务数量未知。`,subagentState_unknown:`未确认`,subagentUnconfirmedGroup:`未确认`,subagentTruncated:`当前显示有界摘录,已省略 {{count}} 条较早消息,部分文本可能已截短。`,subagentListTruncated:`另有 {{count}} 个任务未包含在当前列表中。`,subagentThinkingRedacted:`服务商已隐藏此段思考内容。`,subagentTool_running:`执行中`,subagentTool_done:`已返回`,subagentTool_error:`失败`,subagentTool_unknown:`结果未保留`,inspectionChanged:`当前会话已切换,请重新打开详情。`,inspectionUnavailable:`暂时无法读取详情。`,inspectionLoading:`正在读取状态…`,thinkingUnavailable:`暂时无法读取思考等级。`,trustUnavailable:`暂时无法读取项目信任状态。`,executionState:`状态`,terminalCommand:`命令`,copyTerminalCommand:`复制命令`,copyVisibleOutput:`复制当前可见{{stream}}`,copySetupCommand:`复制配置命令`,savedTrustDecision:`已保存决定`,activeSessionTrust:`当前会话信任`,trustDecision_trusted:`已信任`,trustDecision_denied:`已拒绝`,trustDecision_undecided:`未决定`,trustDecision_unknown:`未知`,trustActiveYes:`当前会话已信任`,trustActiveNo:`当前会话未信任`,terminalDirectory:`目录`,startedAt:`启动时间`,exitCode:`退出码`,detailTruncated:`部分详情已截断,以限制页面加载量。`,standardOutput:`标准输出`,standardError:`错误输出`,outputTruncated:`此输出视图省略了 {{count}} 字节。`,outputRecovery:`运行时报告已保留日志;此处仅显示有大小限制的片段。`,modelAndThinking:`模型与思考`,selectedModel:`当前模型`,thinkingLevel:`思考等级`,availableThinking:`支持的等级`,unknownState:`未知`,projectTrust:`项目信任`,trust_trusted:`当前会话信任此工作区。`,trust_untrusted:`此工作区的信任已被拒绝。`,trust_restricted:`项目资源受到限制,等待信任决定。`,trust_unknown:`尚无法确定信任状态。`,trustRefreshNeeded:`保存的信任决定与当前会话不同,请通过 Pi 刷新会话后生效。`,providerAvailability:`服务商凭据`,settings:`设置`,settingsNavigation:`设置导航`,generalSettings:`常规`,configurationSettings:`配置`,configurationIntro:`配置工具权限、网络访问与模型响应。`,configurationReadFailure:`无法安全读取配置。请修复设置文件后刷新。`,configurationUserScope:`用户配置`,configurationSetupHint:`响应与搜索选项通过 OpenPI setup 应用`,configurationApproval:`批准策略`,configurationApprovalDetail:`工具审批沿用已安装 Pi 扩展的权限机制。`,configurationPiPermissions:`由 Pi 扩展管理`,configurationSandbox:`沙箱设置`,configurationSandboxDetail:`工具使用宿主进程的权限运行。`,configurationSandboxUnavailable:`未提供 OS 沙箱`,configurationSearchDetail:`允许当前会话模型在支持时访问网络。`,configurationSearchOff:`不向当前模型提供原生搜索。`,configurationSearchOn:`在当前连接支持时允许原生搜索。`,configurationVerbosity:`输出详细程度`,configurationVerbosityDetail:`选择模型回复包含细节的详细程度。`,configurationResponsesUnavailable:`当前连接未使用支持的 Responses 接口。`,configurationVerbosity_default:`模型默认`,configurationVerbosity_low:`简短`,configurationVerbosity_medium:`适中`,configurationVerbosity_high:`详细`,configurationVerbosityHelp_low:`简短直接地回答,减少额外细节。`,configurationVerbosityHelp_medium:`给出必要解释与适量细节。`,configurationVerbosityHelp_high:`提供更完整的解释与细节。`,configurationVerbosityRequest:`只把 response_verbosity 设为 {{value}},保留其他 OpenPI 配置。`,configurationSummary:`推理摘要`,configurationSummaryDetail:`选择向支持的推理模型请求哪种摘要。`,configurationSummaryUnavailable:`当前连接不支持推理摘要。`,configurationSummary_default:`模型默认`,configurationSummary_auto:`自动`,configurationSummary_concise:`简洁`,configurationSummary_detailed:`详细`,configurationSummary_none:`关闭`,configurationSummaryHelp_auto:`由模型自动选择摘要长度。`,configurationSummaryHelp_concise:`请求简洁的推理摘要。`,configurationSummaryHelp_detailed:`请求较详细的推理摘要。`,configurationSummaryHelp_none:`不请求推理摘要;保留当前推理强度。`,configurationSummaryRequest:`只把 response_reasoning_summary 设为 {{value}},保留其他 OpenPI 配置。`,configurationModelFeatures:`模型功能`,configurationReasoningLevels:`可用推理强度`,configurationReasoningDetail:`选择在模型控件中显示哪些受支持的级别。当前级别仍会显示,推理强度不变。`,configurationReasoningCount:`已选择 {{count}} 个`,configurationDependencies:`工作空间依赖项`,configurationEnvironment:`本地运行环境`,configurationEnvironmentDetail:`Node.js、Python 等工具由当前环境提供。OpenPI 不安装捆绑的工作空间运行时。`,configurationRuntimeStatus:`运行状态`,browserSettings:`浏览器`,webSearchSettings:`联网搜索`,webSearchCurrentModel:`当前会话模型`,webSearchNativeDetail:`调用当前模型供应商的原生搜索,复用现有连接和凭据。`,webSearchSupported:`当前连接支持原生搜索。开启后,由模型决定何时联网。`,webSearchUnsupported:`当前连接不支持或尚未确认支持原生搜索,不提供搜索工具,也不会切换到其他供应商。`,webSearchNativeRequest:`开启联网搜索,使用当前会话模型的原生搜索和已有 Pi 凭据。不要切换模型、连接协议或搜索供应商;当前连接不支持或支持情况未知时,不提供搜索工具。`,webSearchIntro:`让模型搜索最新资料,并打开原始网页核实。`,webSearchPackageDetail:`通过可选 Pi 插件提供搜索、网页读取和 PDF 提取。`,webSearchDefaultOff:`默认关闭。可选扩展跟随当前会话模型,无需另填搜索密钥或安装插件。`,webSearchLoaded:`本会话已加载插件`,webSearchNotLoaded:`本会话尚未加载插件`,webSearchSource:`查看插件源码`,webSearchProfile:`搜索设置`,webSearchExa:`Exa — 无需 API 密钥`,webSearchExisting:`保留我已有的搜索偏好`,webSearchProfileHint:`Exa 提供搜索,网页由本机直接读取。已有偏好会原样保留;安装后也可更换搜索服务。`,webSearchEnable:`启用联网搜索…`,webSearchDisable:`关闭联网搜索…`,webSearchConfigure:`更换搜索服务…`,webSearchExaRequest:`启用可选联网搜索,使用 Pi Web Access 和无需 API 密钥的 Exa。让我审阅插件安装确认,保留其他偏好,不要自动重新加载。`,webSearchExistingRequest:`启用可选联网搜索,使用 Pi Web Access,原样保留我已有的搜索偏好。让我审阅插件安装确认,保留其他偏好,不要自动重新加载。`,webSearchDisableRequest:`关闭原生联网搜索。保留其他设置和会话记录。`,webSearchProviderRequest:`帮我更换已安装 Pi Web Access 插件的搜索服务。介绍可用服务与权限,保留无关偏好,密钥留在搜索插件中,不要自动重新加载。`,browserSettingsIntro:`让 OpenPI 阅读网页、点击、输入和截图。`,browserControl:`浏览器控制`,browserControlHint:`提交设置变更请求,保存配置后生效。`,browserDefault:`默认浏览器`,browserDefaultHint:`提交设置变更请求,选择未指定浏览器时使用的默认项。`,browserEmbedded:`OpenPI 内置浏览器`,browserAllowedTitle:`允许使用的浏览器`,browserOffHint:`下方选择将在开启浏览器控制后生效。`,browserConnected:`已连接`,browserNeedsSetup:`需要连接浏览器扩展`,browserNotFound:`未检测到此浏览器`,browserUpdateNeeded:`需要更新扩展`,browserBlocked:`未授权`,browserDefaultBlocked:`当前默认浏览器未获授权,请允许使用或更换默认值。`,browserSetUp:`设置`,browserManage:`管理`,browserSetupNamed:`设置 {{browser}}`,browserManageNamed:`管理 {{browser}}`,browserAllowNamed:`允许使用 {{browser}}`,browserMore:`更多浏览器`,browserSpeakHint:`对话中说“使用 Chrome …”,即可指定这次使用的浏览器。`,browserGuideTitle:`连接 {{browser}}`,browserGuideEyebrow:`跟着做,一次一步`,browserConnectionTitle:`连接状态`,browserCloseGuide:`收起浏览器设置引导`,browserConnectionReady:`连接正常,可选择是否允许 OpenPI 使用。`,browserEmbeddedDetail:`网页在 OpenPI 内打开。部分网站需要使用普通浏览器才能登录或正常显示。`,browserExternalDetail:`OpenPI 可以使用已连接的 {{browser}} 配置中的现有标签和登录状态。请在该配置中保留一个 OpenPI 标签页。`,browserManageExtension:`管理扩展`,browserAllowUse:`允许 OpenPI 使用`,browserMakeDefault:`设为默认`,browserInstallIn:`安装到`,browserInstallTitle:`安装 OpenPI Browser Bridge`,browserSetupSteps:`设置步骤`,browserGuidePopout:`在独立窗口中跟随操作`,browserGuideDetached:`引导已在独立窗口打开,可以对照浏览器设置逐步完成。`,browserShowGuide:`显示引导窗口`,browserGuideInline:`把引导放回这里`,browserGuideBlocked:`未能打开引导窗口。可允许弹出式窗口后重试,也可继续查看这里的步骤。`,browserSafariSettings:`Safari → 设置`,browserSafariDeveloper:`开发者设置`,browserSafariTemporary:`添加临时扩展…`,browserSafariOpenHint:`打开 Safari 后,在菜单栏选择「Safari → 设置」,对照此引导操作。需要 macOS 上的 Safari 26 或更新版本。`,browserSafariDeveloperTitle:`显示 Safari 开发者设置`,browserSafariDeveloperHint:`在「设置 → 高级」中开启「显示网页开发者功能」,再进入「开发者」标签。`,browserSafariLoadHint:`在「开发者」中点击「添加临时扩展」,选择下方文件夹。启用 OpenPI Browser Bridge,允许访问要控制的网站及本地 OpenPI 页面。退出 Safari 后需重新加载临时扩展。`,browserFirefoxThis:`此 Firefox`,browserFirefoxTemporary:`临时载入附加组件…`,browserFirefoxDeveloperTitle:`选择「此 Firefox」`,browserFirefoxDeveloperHint:`在 about:debugging 左侧选择「此 Firefox」。Firefox 不需要开启「开发者模式」开关。`,browserFirefoxLoadHint:`点击「临时载入附加组件」,选择下方文件夹中的 manifest.json。此安装在 Firefox 重启后失效;永久安装需要经过 Mozilla 签名的扩展包。`,browserFirefoxDone:`已选中,下一步`,browserStepCount:`第 {{step}} 步,共 {{total}} 步`,browserStepLabel:`第 {{step}} 步:{{label}}`,browserStepOpen:`打开扩展页`,browserStepAdd:`添加扩展`,browserStepConnect:`连接`,browserOpenManagerTitle:`打开 {{browser}} 扩展页`,browserOpenManagerHint:`从这里开始,我们会帮你打开对应的页面。`,browserOpenManager:`打开 {{browser}} 扩展页`,browserReopenManager:`重新打开扩展页`,browserAlreadyInstalled:`已经安装?直接连接`,browserDeveloperMode:`开发者模式`,browserDeveloperTitle:`开启「开发者模式」`,browserDeveloperHint:`在刚打开的扩展页,找到并开启「开发者模式」开关。`,browserDeveloperDone:`已开启,下一步`,browserIllustration:`操作示意 · 在 {{browser}} 中完成`,browserExtensions:`扩展程序`,browserLoadUnpacked:`加载已解压的扩展程序`,browserLoadHint:`在浏览器中点击「加载已解压的扩展程序」,选择下面的文件夹。`,browserFolderBundled:`已随 OpenPI 准备好`,browserOpenFolder:`打开文件夹`,browserFolderOpened:`扩展文件夹已打开。`,browserPathCopied:`已复制路径`,browserCopyFailed:`未能复制,请选中上方路径手动复制。`,browserChooseFolderMac:`在文件选择窗口按 ⌘ ⇧ G,粘贴路径并回车,再点击「选择」。`,browserChooseFolderOther:`在文件选择窗口的地址栏粘贴路径,再选择该文件夹。`,browserInstalledConnect:`已添加,连接 OpenPI`,browserPreviousStep:`上一步`,browserWaiting:`等待 OpenPI Browser Bridge 连接,连接后会自动进入下一步。`,browserInstallBrowserFirst:`请先安装 {{browser}},或在已安装的浏览器中打开当前 OpenPI 地址。`,browserConnectTitle:`连接 OpenPI`,browserConnectHint:`在 {{browser}} 中打开 OpenPI,使用刚安装扩展的浏览器配置。`,browserOpenIn:`在 {{browser}} 中打开`,browserAllowHint:`连接成功后,可以允许 OpenPI 使用此浏览器。安装扩展不会自动开启浏览器控制。`,browserCheck:`检查连接`,browserNotConnectedYet:`还未连接。请完成安装,在该浏览器中刷新 OpenPI 后再次检查。`,browserHelp:`设置帮助`,browserReloadHint:`已安装旧版?在扩展页重新加载 OpenPI Browser Bridge,再刷新 OpenPI。如浏览器提示权限,请完成其原生确认。`,browserSupportedHint:`Chrome、Edge、Brave、Chromium 145+ 可控制内置页面及普通标签。macOS Safari 26+、Firefox 128+ 通过兼容扩展控制普通标签,嵌套框架需单独打开。Safari、Firefox 的临时安装需在浏览器重启后重新加载。`,browserCopyPath:`复制扩展文件夹路径`,browserLoading:`正在检查浏览器连接…`,browserSaved:`已保存,浏览器权限立即生效。`,browserSaving:`正在保存…`,modelSettings:`模型`,skillsSettings:`技能`,subagentsSettings:`子代理`,pluginsSettings:`插件`,configureOpenPi:`配置 OpenPI`,setupRequestReviewAll:`和我一起检查全部 OpenPI 配置项`,setupRequestSetTheme:`仅将 OpenPI Web 主题设置为 {{value}},其他配置保持不变`,setupRequestSetChatWidth:`仅将 OpenPI Web 聊天内容宽度设置为 {{value}}px,其他配置保持不变`,setupRequestSetChatFontSize:`仅将 OpenPI Web 聊天字体大小设置为 {{value}}px,其他配置保持不变`,setupRequestEnableExpandedThinking:`仅将 OpenPI Web 的思考块改为默认展开,其他配置保持不变`,setupRequestDisableExpandedThinking:`仅将 OpenPI Web 的思考块改为默认折叠,其他配置保持不变`,setupRequestSubagents:`检查并配置 Agent 角色模型和工作流上限`,setupRequestFailed:`OpenPI 配置请求未被接收。`,setupRequestRunning:`正在应用 OpenPI 设置…`,setupRequestAccepted:`配置请求已接收。`,setupPlanBlocked:`Agent 配置需先退出 Plan 模式;显示设置可直接调整。退出不会开始实施计划。`,setupPlanBusy:`Agent 配置需等待当前回合结束并退出 Plan 模式;显示设置可直接调整。`,setupOutcome_pending:`配置请求正在处理,尚未收到保存回执。`,toolCallArguments:`工具参数`,toolCallOutput:`工具结果`,setupOutcome_saved:`OpenPI 配置已保存并应用。`,setupOutcome_unchanged:`配置已保存,实际设置没有变化。`,setupOutcome_failed:`配置请求失败,请查看错误和当前设置后再重试。`,setupOutcome_cancelled:`配置过程已取消,未确认成功保存。`,setupOutcome_unconfirmed:`本次未确认成功保存,请核对当前设置后再运行 /openpi-setup。`,settingsUpdateFailed:`无法保存 Web 显示设置。`,settingsPreferencesSaved:`显示设置已保存。`,settingsPreferencesSaveFailed:`无法保存显示设置,请检查配置诊断后重试。`,settingsCatalogLoading:`正在加载 Pi 资源…`,settingsCatalogFailed:`无法加载 Pi 设置资源。`,appearance:`外观`,settingsPersonal:`个人`,settingsAgent:`Agent`,settingsIntegrations:`集成`,settingsArchivedChats:`已归档聊天`,settingsSearch:`搜索设置`,settingsClearSearch:`清除搜索`,settingsNoResults:`没有匹配的设置`,appearanceVisualStyle:`视觉风格`,appearanceMode:`模式`,appearanceTheme:`主题`,appearanceAccent:`强调色`,appearanceBackground:`背景`,appearanceForeground:`前景`,appearanceFont:`字体`,appearanceFont_codex:`Codex 默认`,appearanceFont_sans:`无衬线`,appearanceFont_serif:`衬线`,appearanceFont_mono:`等宽`,appearanceAccent0:`默认`,appearanceAccent1:`蓝色`,appearanceAccent2:`紫色`,appearanceAccent3:`粉色`,appearanceAccent4:`橙色`,appearanceAccent5:`绿色`,appearanceCustomAccent:`自定义强调色`,appearanceAdvanced:`高级`,appearanceReset:`恢复默认设置`,appearanceResetAction:`重置外观`,appearanceImport:`导入主题`,appearanceCopy:`复制主题`,appearanceCopied:`主题已复制`,appearanceCopyFailed:`无法复制主题,请重试。`,appearanceThemeValue:`主题数据`,appearanceImportPlaceholder:`粘贴 OpenPI 主题…`,appearanceImportInvalid:`请输入有效的 OpenPI 主题数据。`,appearanceImportAction:`导入`,searchArchivedChats:`搜索已归档聊天`,archiveProjectFilter:`按项目筛选`,archiveAllProjects:`所有项目`,archiveProjectGroup:`{{project}} · {{count}} 条归档聊天`,archiveSort:`归档聊天排序`,archiveSortUpdated:`最近更新`,archiveSortCreated:`创建时间`,restoreArchivedChat:`恢复 {{title}}`,themeLight:`浅色`,themeDark:`深色`,themeMist:`雾青`,themeRose:`蔷薇`,themePine:`松夜`,themeSystem:`跟随系统`,conversationSettings:`对话`,expandThinkingByDefault:`默认展开思考块`,chatContentWidth:`聊天内容宽度`,chatFontSize:`聊天字体大小`,agentBehavior:`Agent 行为`,capabilityDiscovery:`能力发现`,capabilityDiscovery_explicit:`明确请求`,capabilityDiscovery_adaptive:`自适应`,workflowLimits:`工作流上限`,workflowConcurrency:`工作流并行上限`,workflowCalls:`总调用次数`,agentSettingsSetupHint:`Agent 设置通过当前会话中的 /openpi-setup 生效。`,setupRequestDiscovery:`将能力发现设置为 {{mode}},保留其他配置。`,setupRequestLimits:`将工作流并行上限设置为 {{concurrency}},总子代理调用上限设置为 {{calls}},保留其他配置。`,setupRequestEnableSuggestions:`启用下一步建议。如需模型配置,请帮助我选择模型,保留其他配置。`,setupRequestDisableSuggestions:`关闭下一步建议,保留其他配置。`,setupRequestPostEdit:`帮我配置或关闭编辑后命令。先展示当前配置,再询问要使用的命令。`,configurePostEdit:`配置编辑后命令`,workflowLimitsValue:`并行 {{concurrency}} · 总调用 {{calls}}`,nextActionSuggestions:`下一步建议`,enabled:`已启用`,disabled:`已关闭`,configured:`已配置`,postEditCommand:`编辑后命令`,resultDisplay:`默认结果显示`,subagentResults:`子代理结果`,bashOperations:`Bash 操作`,fileMutations:`Write / Edit 操作`,footer:`页脚`,terminalFooter:`Pi 终端页脚`,terminalFooterStyle:`终端页脚样式`,terminalFooterHint:`影响 Pi 命令行界面的页脚;已打开的 Pi 界面在下次启动或配置应用后更新。`,detailDisplay_full:`完整`,detailDisplay_compact:`紧凑`,sessionSettings:`会话`,currentModel:`当前`,useThisModel:`使用此模型`,model:`模型`,modelConnection:`模型连接`,provider:`服务商`,modelId:`模型 ID`,providerStatusUnavailable:`此服务商不在当前有界认证快照中。`,providerSettings:`服务商凭据`,providerSettingsIntro:`查看当前 Web 会话可通过哪些 Pi 服务商完成认证。`,openRuntimeDetails:`打开运行详情`,currentWorkspace:`当前工作区`,providerAuth_api_key:`API 密钥`,providerAuth_oauth:`OAuth`,providerAuthUnknown:`未报告认证方式`,authentication:`认证方式`,accessType:`访问方式`,providerAccessSubscription:`订阅账户`,providerAccessStandard:`服务商凭据`,configurationOwner:`配置归属`,providerLoading:`正在加载服务商状态…`,providerLoadFailed:`无法加载服务商状态。`,providerReadOnly:`由 Pi 管理`,selectProvider:`选择服务商`,gitReviewBaselineUnavailable:`未保留可用的会话基线,可能超出了捕获限额。请切换到未暂存、已暂存或分支查看 Git 变更,也可打开本会话文件记录。`,modelsIntro:`登录账户或添加 API 密钥。已有的 Pi 连接也会显示在这里。`,accountLoginMethod:`连接方式`,accountLoginTab:`账户登录`,accountLoginChatGPT:`ChatGPT 账户`,accountLoginClaude:`Claude 账户`,accountLoginKeyTab:`API 密钥`,accountLoginConfigured:`账户已登录`,accountLoginIntro:`在浏览器中完成授权,无需填写 API 密钥。`,accountLoginExisting:`账户凭据已保存在 Pi 中。`,accountLoginStart:`登录`,accountLoginAgain:`重新登录`,accountLoginUnsaved:`请先保存或放弃其他修改,再登录账户。`,accountLoginStarting:`正在准备登录…`,accountLoginWaiting:`等待账户授权`,accountLoginChoose:`选择登录方式`,accountLoginCancelling:`正在取消登录…`,accountLoginBrowser:`在浏览器中继续`,accountLoginDevice:`使用设备码登录`,accountLoginBrowserOption:`在当前电脑上登录,完成后自动返回。`,accountLoginDeviceOption:`适合远程服务器,或无法自动返回的情况。`,accountLoginBrowserHelp:`打开登录页并完成授权,这里会自动更新。`,accountLoginDeviceHelp:`打开授权页并输入下方代码,请保持此页面打开。`,accountLoginOpen:`打开登录页`,accountLoginCopyCode:`复制设备码`,accountLoginPaste:`授权码或回调地址`,accountLoginContinue:`继续`,accountLoginFallback:`已登录,但这里没有更新?`,accountLoginRemoteHelp:`如果无法自动返回,请复制浏览器最后的回调地址,并粘贴到下方。`,accountLoginCancel:`取消登录`,accountLogin_failed:`登录未完成,请重试或选择其他登录方式。`,accountLogin_expired:`登录已过期,请重新开始获取新的授权链接。`,accountLogin_cancelled:`已取消登录。`,accountLoginRequestFailed:`请求未完成,请先刷新状态再重试。`,accountLoginStatusUnknown:`暂时无法查询登录状态,账户授权可能仍在进行。`,accountLoginRefreshRequired:`凭据已保存,但 Pi 未能更新模型列表。请重载 Pi 后使用此连接。`,accountLogout:`退出登录`,accountLogoutRefreshRequired:`已移除保存的凭据,但 Pi 未能更新模型列表。请重载 Pi 刷新状态。`,accountLogoutTitle:`退出 {{provider}}?`,accountLogoutDetail:`将移除此电脑上 Pi 保存的该服务凭据,其他使用它的 Pi 会话也需要重新登录。环境凭据不受影响。`,providerInputTypes:`输入类型`,providerInputText:`文本`,providerInputImage:`图片`,providerCustomTag:`自定义`,providerEdit:`编辑`,providerRemove:`删除`,providerSave:`保存`,editProvider:`编辑 {{provider}}`,removeProvider:`删除 {{provider}}`,providerAdd:`添加模型提供商`,providerAddMode:`添加方式`,providerAddCatalog:`第三方模型提供商`,providerAddCustom:`自定义模型 API`,providerAccountHint:`使用已有账户连接模型,选择服务商后前往浏览器授权。`,providerCatalogHint:`从内置目录中选择提供商,填入其 API 密钥即可使用。`,providerCustomHint:`连接中转站、自部署服务或其他兼容 OpenAI / Anthropic 协议的接口,需填写 API 地址、协议和模型。`,providerKeyKeep:`已配置密钥,留空保持不变`,providerKeyOptional:`输入 API 密钥,或留空使用环境认证`,providerDisplayName:`提供商名称`,providerCustomSettings:`自定义设置`,providerSaved:`已保存 {{provider}}。`,modelDefaultTitle:`新会话默认模型`,modelDefaultChoose:`选择模型`,modelDefaultBadge:`默认`,modelCurrentBadge:`当前使用`,modelDefaultNotSet:`未设置 · 新会话启动时由 Pi 选择`,modelDefaultHint:`选择以后新会话使用的模型,已有会话保留自己的选择。此设置也会更新 Pi 的默认模型。`,modelDefaultReadFailed:`暂时无法读取默认模型。`,modelDefaultProjectOverride:`此工作区有 Pi 独立设置:{{model}}。`,modelDefaultSave:`保存默认模型`,modelMakeDefault:`同时设为新会话默认模型`,modelDefaultSaveFailed:`默认模型保存尚未确认,请刷新状态后重试。`,modelDefaultPartial:`当前模型已切换,但默认模型保存尚未确认,请刷新状态后再试。`,modelConnectionNextHint:`从此连接选择一个模型,用于当前会话。`,modelConnectionSearch:`搜索模型…`,modelConnectionChooseProvider:`选择 {{provider}} 的模型`,modelConnectionUse:`用于当前会话`,modelConnectionUseFailed:`模型切换尚未确认,请刷新模型列表后重试。`,modelConnectionLoadFailed:`暂时无法读取模型列表。`,modelConnectionNoModels:`暂无可选模型,请检查连接或添加模型定义。`,modelConnectionNoMatch:`没有匹配的模型。`,modelConnectionMore:`还有 {{count}} 个模型,可搜索缩小范围。`,providerModelsEmpty:`还没有模型,获取可用模型或手动添加。`,providerModelsInherited:`使用提供商的内置模型目录。`,providerModelsReadOnly:`此提供商包含当前页面未支持的模型设置,请在 Pi 配置文件中编辑。`,providerModelId:`模型 {{number}} ID`,providerModelName:`模型 {{number}} 名称`,providerModelDetails:`模型参数:{{model}}`,providerRemoveModel:`删除模型:{{model}}`,providerIdInvalid:`请使用未被占用的提供商 ID,仅包含字母、数字、连字符、点或下划线。`,providerNativeAuth:`此提供商使用 Pi 原生登录。`,providerConfigurationFailed:`保存失败,请检查填写内容,并在会话空闲时重试。`,providerProfileSavedKeyFailed:`提供商配置已保存,但密钥保存失败。重试将只保存密钥。`,providerReload:`放弃草稿并重新加载`,providerCurrentRemoval:`请先切换当前使用的模型,再删除。`,providerRemoveDetail:`删除此提供商的配置和自定义模型?由 Pi 管理的凭据将保留。`,providerPickerIntro:`以下是模型提供商的可用模型,勾选要添加的模型。`,providerPickerSelected:`已选 {{count}} 个`,providerApiKey:`API 密钥`,providerKeyPlaceholder:`粘贴密钥以添加或替换`,saveProviderKey:`保存密钥`,savingSettings:`正在保存…`,keepEditing:`继续编辑`,discardAndContinue:`放弃更改并继续`,unsavedSettingsTitle:`放弃未保存的更改?`,unsavedSettingsDetail:`未保存的模型和凭据修改将被丢弃。`,unsavedCredentialTitle:`放弃未保存的凭据?`,unsavedCredentialDetail:`新密钥尚未保存,继续后将清空。`,modelSelectionBusy:`当前会话忙碌,暂不能切换模型。`,providerKeySaved:`已保存到 Pi 凭据存储。已有密钥不会回显。`,providerSaveFailed:`密钥保存未完成。请等待会话空闲,刷新状态后重试;部分服务商需要额外认证信息。`,providerWriteDetail:`在这里直接保存到 Pi 凭据存储,密钥不会进入模型对话。OAuth 或需要额外字段的认证请使用 Pi 原生登录。`,editModelConfiguration:`添加或编辑自定义模型`,modelConfigurationDetail:`先设置提供商连接,再获取模型列表或手动添加。保存配置不会调用模型。`,configuredModels:`自定义模型配置`,addModel:`添加模型`,modelConfig_provider:`服务商 ID`,modelConfig_id:`模型 ID`,modelConfig_name:`显示名称`,modelConfig_baseUrl:`API 地址`,modelConfig_api:`API 格式`,modelConfig_contextWindow:`上下文窗口`,modelConfig_maxTokens:`最大输出 token 数`,providerCapacityLabel:`{{field}} {{number}}`,providerModelOptions:`模型选项`,providerModelInvalid:`模型 {{number}}:模型 ID 不能为空或重复;容量需为正数,例如 128K 或 1M,留空使用默认值。`,modelConfig_reasoning:`支持推理`,saveModelConfiguration:`保存模型`,reloadModelConfiguration:`放弃草稿并载入最新配置`,retryModelConfiguration:`重试读取`,discardModelDraftTitle:`放弃这份模型草稿?`,discardModelDraftDetail:`最新配置将替换这份未保存的草稿。`,discardAndReload:`放弃并重新载入`,modelConfigurationUnsaved:`未保存的更改`,modelConfigurationConflict:`模型配置已在别处更改,当前草稿已保留。`,modelConfigurationLoadFailed:`无法读取模型配置,草稿已保留。`,modelConfigurationSaved:`已保存到 Pi models.json。配置服务商密钥后即可选择此模型。`,modelConfigurationFailed:`模型保存未完成,草稿已保留。`,setupConfigurationRequest:`配置需求`,configureViaSetup:`通过 OpenPI setup 应用`,setupFormDetail:`统一走 /openpi-setup。请在对话中查看进度及必要的确认;提交成功不等于配置已保存。`,setupSkillsPlaceholder:`填写要添加或调整的技能,以及来源或本地路径`,setupPluginsPlaceholder:`填写要配置的 Pi 插件,以及准确的包名或本地路径`,enableSkillInvocation:`允许模型调用`,disableSkillInvocation:`改为仅显式调用`,setupSkillInvocationRequest:`配置这个 Pi 技能:{{path}}。将原生 disable-model-invocation 字段设为 {{disabled}},保留其余内容,并说明何时生效。`,setupRoleFormRequest:`将 OpenPI 的 {{role}} 角色配置为使用 {{model}},工作流并发设为 {{concurrency}}。推理级别继承父会话,校验选择有效性,并保留其他配置。`,providerReadOnlyDetail:`此页面只读且不会接收凭据内容。请通过 Pi 配置服务商认证,然后刷新此状态。`,openProviderSettings:`打开服务商设置`,credentialConfigured:`已配置`,credentialMissing:`未配置`,authNotVerified:`凭据已配置不代表模型请求一定成功。`,configurationViaPi:`此处为只读状态。模型凭据与信任由 Pi 管理,OpenPI 选项通过 /openpi-setup 配置。`,noSkillsFound:`当前会话没有加载技能。`,addSkill:`添加技能`,addPlugin:`添加插件`,searchResources:`搜索名称或来源`,filterResourceScope:`资源范围`,allResourceScopes:`全部范围`,noMatchingResources:`没有匹配的资源`,resourceBulkTooLarge:`请进一步筛选列表后,再提交批量配置请求。`,resourceManagement:`Pi 资源`,resourceSourceAuto:`Pi 自动发现`,resourceSourceLocal:`本地资源`,resourcePackageSource:`软件包、仓库或本地路径`,resourcePackageSourcePlaceholder:`npm:包名@版本 · git:owner/repo · /path/to/skill`,resourceInstallIntro:`选择来源和范围,在对话中通过 OpenPI setup 审查并应用。`,resourceInstallReview:`请在对话中确认准确来源和权限。提交请求不代表已安装或已加载。`,resourceRequestSubmitted:`请求已提交。请在对话中查看进度和确认,完成后刷新此目录。`,browseSkills:`浏览 skills.sh 技能`,resourceSessionState:`应用到当前会话`,resourcesReloadNote:`刷新只读取目录;重新加载才会将已保存的资源应用到空闲会话。配置变更不会自动重新加载。`,reloadResources:`重新加载资源`,resourceReloadReview:`将已保存的 Pi 技能与插件配置应用到当前会话,并重新启动扩展?请先等待运行中的工作结束。`,resourceReloaded:`资源已重新加载,请查看更新后的目录和诊断。`,resourceReloadFailed:`无法重新加载资源。请等待当前会话空闲,刷新后重试。`,advancedResourceConfiguration:`高级配置`,resourceDiagnostics:`Pi 报告了 {{extensionErrors}} 项扩展诊断与 {{skillErrors}} 项技能诊断。`,resourceConfigurationDiagnostics:`{{count}} 项设置读取失败,请检查 Pi 配置诊断。`,resourceCatalogTruncated:`此目录有数量上限,部分资源未展示。`,resourceTargetTruncated:`此来源或路径已截断,请通过高级配置确认完整目标后再进行管理。`,updateResource:`检查更新`,removeResource:`审查移除`,skillsEmptyTitle:`添加你的第一个技能`,skillsEmptyIntro:`技能为 Pi 提供可复用的指引。可以添加软件包、仓库或本地技能;项目技能遵循 Pi 的项目信任。`,pluginsEmptyTitle:`用插件扩展 Pi`,pluginsEmptyIntro:`软件包可以包含扩展、技能、提示词和主题。添加来源后,通过 OpenPI setup 审查安装。`,pluginCount:`{{count}} 个插件来源`,installedVersion:`已安装版本`,configuredVersion:`配置版本`,resourceVersionUnpinned:`未固定版本 / 本地来源`,pluginState_loaded:`本会话资源已加载`,pluginState_installed:`已安装 · 未加载`,pluginState_disabled:`配置已禁用`,pluginState_missing:`软件包缺失`,pluginState_error:`加载诊断`,pluginState_notLoaded:`未加载`,pluginLoadedResources:`当前会话目录包含 {{count}} 项资源。配置变更需要明确重新加载后才会应用。`,pluginAction_enable:`审查启用`,pluginAction_disable:`审查禁用`,pluginAction_update:`检查更新`,pluginAction_remove:`审查移除`,enableVisibleSkills:`允许模型使用(当前 {{count}} 项)`,disableVisibleSkills:`仅显式调用(当前 {{count}} 项)`,enableVisiblePlugins:`启用当前 {{count}} 个软件包`,disableVisiblePlugins:`禁用当前 {{count}} 个软件包`,setupResourceInstallRequest:`添加 Pi {{kind}},来源为 {{source}},范围为 {{scope}}。先检查来源并确定固定的软件包身份,通过 ask_user 与我确认安装权限,再使用 Pi 原生的软件包或技能配置。添加技能时保留其他扩展和资源。保留现有偏好与项目信任,不要自动重新加载当前会话。分别报告已保存的配置与仍需执行的操作,不要改动无关的 OpenPI 设置。`,setupPluginOperationRequest:`审查 Pi 软件包操作 {{action}},只针对配置来源 {{source}}、原生安装目录 {{path}}、范围 {{scope}}。相对来源应以该范围的原生设置目录解析。使用 Pi 原生包管理;更新时检查可用版本,通过 ask_user 与我确认固定的目标身份和安装权限。保留资源过滤器及所有无关偏好;如果切换会破坏过滤器,停止并说明。移除时不得删除本地来源目录。不要自动重新加载,分别报告已持久化与当前会话状态,不要改动无关的 OpenPI 设置。`,setupSkillManageRequest:`审查 Pi 技能操作 {{action}},只针对文件 {{path}}、来源 {{source}}、范围 {{scope}}。先检查原生资源归属,通过 ask_user 与我确认更新或移除及所需权限。保留无关技能与软件包资源,不要为了移除一个技能删除整个共享软件包。保留项目信任,不要自动重新加载,也不要改动无关的 OpenPI 设置。`,setupSkillsBulkRequest:`只针对当前展示的 Pi 技能文件 {{paths}},将原生 disable-model-invocation 设为 {{disabled}}。检查资源归属,保留其余内容和偏好,与我审查必要变更,报告无法安全修改的文件。显式 /skill 调用仍应可用。不要自动重新加载,也不要改动无关的 OpenPI 设置。`,setupPluginsBulkRequest:`只针对当前展示的 Pi 软件包 {{packages}},通过 Pi 原生配置将 disabled 设为 {{disabled}}。保留其他偏好与资源过滤器;无法保留过滤器的条目应跳过并报告。遵循范围与项目信任,与我审查必要变更,不要自动重新加载,也不要改动无关的 OpenPI 设置。`,resourceRequestFinished:`配置回合已结束。请刷新并查看 Pi 原生配置与会话资源,确认实际变更。`,skillCount_one:`{{count}} 个技能`,skillCount_other:`{{count}} 个技能`,skill:`技能`,copySkillInvocation:`复制调用命令`,source:`来源`,scope:`范围`,invocation:`调用方式`,modelInvocation:`模型调用`,resourceScope_user:`全局`,resourceScope_project:`项目`,resourceScope_temporary:`临时`,explicitOnly:`仅允许明确调用`,availableToModel:`模型可按需使用`,skillFile:`技能文件`,selectSkill:`选择一个技能`,subagentConfiguration:`Pi 原生子代理角色`,subagentConfigurationIntro:`未在 OpenPI 配置中指定模型时,角色继承父会话模型。`,subagentActiveCount_one:`{{count}} 个运行中`,subagentActiveCount_other:`{{count}} 个运行中`,subagentCompletedCount_one:`{{count}} 条记录`,subagentCompletedCount_other:`{{count}} 条记录`,subagentConcurrency:`上限 {{count}}`,builtInRoles:`内置角色`,subagentRole_explorer:`探索者`,subagentRole_implementer:`实现者`,subagentRole_reviewer:`审查者`,subagentRole_advisor:`顾问`,subagentRoleShort_explorer:`只读调查`,subagentRoleShort_implementer:`聚焦实现`,subagentRoleShort_reviewer:`正确性审查`,subagentRoleShort_advisor:`技术分析`,subagentRoleDescription_explorer:`调查代码库并报告证据,不修改文件。`,subagentRoleDescription_implementer:`实现边界明确的改动并运行相关仓库检查。`,subagentRoleDescription_reviewer:`审查正确性、安全性、回归风险和缺失验证。`,subagentRoleDescription_advisor:`分析困难技术问题并提出具体下一步建议。`,configureRoles:`配置角色`,builtInRole:`内置角色`,builtIn:`内置`,modelAssignment:`模型分配`,inheritParentModel:`继承父会话模型`,effectiveModel:`实际模型`,workflowConcurrencyLabel:`并行 Agent`,workflowCallLimit:`Agent 总调用数`,runtimeBoundaries:`运行时边界`,subagentAuthorityNote:`子会话权限是父会话与角色能力的故障关闭交集,不会静默扩大权限。`,subagentModelNote:`不会硬编码服务商;未分配的角色继承父会话模型和思考等级。`,resourceCount_one:`{{count}} 项资源`,resourceCount_other:`{{count}} 项资源`,noPluginsFound:`Pi 未报告已加载的插件来源。`,pluginCatalogTotals:`{{extensions}} 扩展 · {{skills}} 技能 · {{prompts}} 提示词 · {{themes}} 主题`,loaded:`已加载`,resourceOrigin:`来源类型`,resourceOrigin_package:`软件包`,resourceOrigin_topLevel:`顶层资源`,resources:`资源`,baseDirectory:`基础目录`,notReported:`未报告`,extensions:`扩展`,extensionSurfaceCount:`{{tools}} 个工具 · {{commands}} 个命令`,prompts:`提示词`,themes:`主题`,pluginResourceSummary:`{{extensions}} 扩展 · {{skills}} 技能 · {{prompts}} 提示词 · {{themes}} 主题`,pluginsManagedByPi:`这些资源由 Pi 加载。可通过上方 setup 表单提交变更;软件包操作沿用原生确认,并通过 Pi 的重新加载流程生效。`,selectPlugin:`选择一个插件来源`,statusCaptured:`采集于 {{time}} · 刷新查看最新状态`,conversationViews:`会话视图`,currentConversations:`当前`,archivedConversations:`已归档`,refreshArchives:`刷新归档会话`,loadingArchives:`正在加载归档会话...`,moreArchives:`加载更多归档会话`,retryArchives:`重试读取归档会话`,archiveLoadFailed:`无法加载归档会话。`,archiveCursorStale:`归档会话已变化,请刷新后继续。`,archiveScanBounded:`还有 {{count}} 条更早记录未扫描。`,noArchivedSessions:`没有归档会话。`,noScannedArchives:`已扫描历史中没有归档会话。`,noMatchingScannedArchives:`已扫描历史中没有匹配的归档会话。`,draftLimit:`草稿暂存已满,请先发送或清空已有草稿。`,restoreConversation:`恢复会话`,restoringConversation:`正在恢复…`,loadedArchives:`已加载历史中的归档会话`,loadedHistoryBounded:`另有 {{sessions}} 个会话和 {{workspaces}} 个工作区摘要未加载。搜索仅覆盖已加载列表。`,noLoadedArchives:`已加载列表中没有归档会话。`,restoreFailed:`暂时无法确认恢复结果,请刷新后重试。`,execution_running:`运行中`,execution_done:`已完成`,execution_killed:`已停止`,execution_timed_out:`已超时`,execution_failed:`失败`,execution_uncertain:`状态不确定`,activeOnlyHint:`只有当前 Web 会话可以接收消息。`,stopTurn:`停止当前轮次`,stoppingTurn:`正在停止当前轮次…`,stoppedTurn:`当前轮次已停止。`,pendingFollowUpsHint:`{{count}} 条消息正在排队`,sendNextTurn:`下一轮发送`,steerCurrentTurn:`当前执行纠偏`,steeringHint:`在当前工具步骤结束后加入这条指示。`,pendingSteeringHint:`已接收 {{count}} 条纠偏指示,等待当前工具步骤结束`,steeringMessagesTitle:`当前轮次待处理的纠偏指示`,steerStaleTurn:`目标轮次已结束或变化。草稿已保留,请重新选择发送方式。`,sourceFeedbackNew:`{{path}} · 新版本第 {{line}} 行`,sourceFeedbackOld:`{{path}} · 旧版本第 {{line}} 行`,forkMessage:`从此处分叉`,forkMessageHint:`从此消息创建新聊天,保留原聊天;不会自动发送消息。`,forkSessionPending:`正在创建分叉会话…`,forkSessionCreated:`已创建分叉会话,原会话保留在侧栏。`,forkSessionCancelled:`分叉已取消,原会话已保留。`,forkSessionUncertain:`无法确认分叉结果。请先刷新并检查会话列表,再决定是否重试。`,forkSessionUnavailable:`切换到此会话并等待当前执行和排队消息结束后,可以从这里创建新会话。`,reviewQuoteLine:`引用此行`,reviewSelectOldLine:`选择旧版本第 {{line}} 行`,reviewSelectNewLine:`选择新版本第 {{line}} 行`,queuedMore:`还有 {{count}} 条排队消息`,queuedImage:`图片附件`,queuedMessageExpand:`展开排队消息`,queuedMessageCollapse:`收起排队消息`,backgroundSessionRunning:`此会话正在后台运行…`,observedSessionTools:`{{count}} 个正在执行的工具`,toolsRequireCurrentSession:`切换到此会话后可使用交互工具。`,activateViewedSession:`切换到此会话`,activateViewedSessionHint:`发送消息即可继续此会话。`,acceptedHint:`OpenPI Web 已接收消息。`,promptAdmissionUnknown:`无法确认上次发送的消息是否已被接收。`,promptAdmissionUnknownDetail:`请先核对已刷新的会话历史和运行状态,再决定下一步。作为新消息发送可能产生重复消息。`,promptAdmissionCheckingDetail:`正在核对最新的会话历史和运行状态,核对完成前不能作为新消息发送。`,promptAdmissionVerificationFailedDetail:`暂时无法刷新最新的会话历史和运行状态。请重新核对后再决定是否作为新消息发送。`,abandonAdmission:`暂不重新发送`,retryAdmissionCheck:`重新核对`,retryOriginalAdmission:`重试原消息`,promptTooLong:`文本超出发送上限({{count}} / {{limit}})。`,sendAsNew:`作为新消息发送`,sendingAsNew:`正在发送…`,addWorkspace:`添加工作区`,addWorkspaceMenu:`添加工作区...`,archiveConversation:`归档会话`,pinnedConversations:`置顶`,sidebarOptions:`侧栏选项`,sidebarProjectOptions:`项目侧栏选项`,sidebarRecentOptions:`会话侧栏选项`,sidebarActivityOptions:`动态视图选项`,sidebarShow:`显示`,sidebarGroupBy:`会话分组`,sidebarByProject:`按项目分组`,sidebarFlatList:`所有会话`,sidebarChatSort:`会话排序`,sidebarRecent:`最近`,sidebarProjectsInRecents:`在最近列表显示项目会话`,sidebarShowMore:`展开显示`,sidebarShowLess:`收起显示`,sidebarFilterList:`筛选当前列表`,sidebarSaveFailed:`更改未能保存,请重试。`,pinWorkspace:`置顶项目`,unpinWorkspace:`取消置顶项目`,markConversationRead:`标记为已读`,markConversationUnread:`标记为未读`,sidebarState_unread:`未读会话`,sidebarActivity:`动态`,sidebarViewActivity:`查看动态`,sidebarViewChats:`查看会话`,sidebarPriority:`优先关注`,sidebarActivityEmpty:`没有需要关注的会话`,sidebarActivityEmptyHint:`已完成的工作和需要你处理的会话会显示在这里。`,sidebarMarkAllRead:`全部标记为已读`,sidebarClearRead:`清除优先关注中的已读会话`,sidebarReadFailed:`未能更新已读状态,请重试。`,sidebarToday:`今天`,sidebarYesterday:`昨天`,sidebarEarlier:`更早`,sidebarActivityCompleted:`已完成`,sidebarActivityFailed:`执行失败`,sidebarActivityRead:`已读`,modelAdvanced:`高级参数`,providerConnectionHeading:`提供商连接`,providerFetchModels:`获取可用模型`,providerFetchHint:`填写提供商和端点后,可一次选择多个模型。`,providerPickerTitle:`选择要添加的模型`,providerPickerAccess:`连接凭据`,providerPickerKey:`访问密钥(可选)`,providerPickerKeyHint:`留空使用此端点已保存的凭据。此处输入的密钥仅用于获取列表,不会保存。`,providerPickerSearch:`搜索模型`,providerPickerSelectAll:`全选`,providerPickerClear:`清空选择`,providerPickerLoading:`正在获取可用模型…`,providerPickerAdded:`已添加`,providerPickerNoMatch:`没有匹配的模型`,providerPickerEmpty:`提供商没有返回模型,仍可手动添加。`,providerPickerBounded:`当前显示前 500 个模型,其他模型可手动填写 ID。`,providerPickerError_load:`未能获取模型列表,请检查端点和凭据后重试,也可以手动添加。`,providerPickerError_save:`尚未确认保存成功。已保留你的选择,请检查连接后重试。`,providerPickerError_conflict:`配置已在其他地方更新,请关闭弹窗、重新读取配置后再保存。`,providerPickerDefaults:`新模型使用 {{context}} 上下文 / {{output}} 输出 token,添加后可逐个调整。`,providerPickerRetry:`刷新列表`,providerPickerCount:`已选 {{count}} 个 · 最多 100 个`,providerPickerSave:`添加所选`,sidebarState_running:`执行中`,sidebarState_compacting:`正在整理上下文`,sidebarState_waiting:`等待你的回复`,sidebarState_completed:`已完成 · 结果未读`,sidebarState_failed:`执行失败 · 打开会话查看详情`,pinnedOptions:`置顶选项`,pinConversation:`置顶会话`,unpinConversation:`取消置顶`,pinnedRecentlyUpdated:`最近更新`,pinnedManualOrder:`手动排序`,movePinUp:`上移`,movePinDown:`下移`,pinSaveFailed:`置顶设置未能保存,请重试。`,cancel:`取消`,chooseWorkspaceHint:`选择工作区并描述任务`,close:`关闭`,closeSearch:`关闭搜索`,collapseSidebar:`收起侧边栏`,confirmEdit:`保存并重新运行`,editMessageHint:`从这里创建新分支并重新运行;保留原对话、图片和文件引用。已有工作区改动会保留。`,regenerateMessage:`重新生成回答`,regenerateMessageHint:`在新分支重新运行这条问题,保留原附件和原对话。`,messageRerunStarted:`已在新分支接收重跑消息,原对话已保留。`,openOriginalConversation:`查看原对话`,messageRerunWorkspaceHint:`已有工作区改动会保留。`,modelRequestRecovered:`请求已恢复`,modelReconnecting:`正在重新连接`,modelReconnectUnknown:`重连状态待确认`,modelEarlierAttempts:`先前请求错误`,modelFailedAttempts:`失败尝试({{count}} 次)`,draftStorageUnavailable:`草稿未能保存到此设备,请保持页面打开或复制消息。`,draftStorageInvalid:`部分保存的草稿内容无法恢复,请检查消息和附件。`,draftStorageRetry:`重试保存草稿`,workbarBackToChat:`返回聊天`,workbarCollapseTools:`收起工具栏`,workbarEndTerminal:`关闭 {{name}} 并结束进程`,workbarNewTerminal:`新建终端`,workbarContinueInChat:`继续追问`,transcriptSearch:`搜索消息内容`,transcriptSearchPlaceholder:`搜索标题、项目或消息…`,transcriptSearchRecent:`最近会话`,transcriptSearchSessions:`会话`,transcriptSearchMessages:`消息内容`,transcriptSearchSessionResult:`打开会话 {{session}}`,transcriptSearchSessionOpenFailed:`暂时无法打开此会话,请重试。`,transcriptSearchIncludeArchived:`包含归档会话`,transcriptSearching:`正在搜索消息…`,transcriptSearchEmpty:`没有匹配的消息。`,transcriptSearchFailed:`暂时无法搜索消息,请重试。`,transcriptSearchRetry:`重试搜索`,transcriptSearchPartial:`部分历史未能搜索,结果可能不完整。`,transcriptSearchOpenFailed:`无法打开这条消息,它可能已移动或位于其他分支。`,transcriptSearchResult:`打开 {{session}} 中来自{{source}}的消息`,transcriptSearchSource_user:`你`,transcriptSearchSource_assistant:`助手`,transcriptSearchSource_tool_call:`工具调用`,transcriptSearchSource_tool_result:`工具结果`,connected:`已连接`,connecting:`正在连接`,conversationName:`会话名称`,conversationOptions:`会话选项`,sidebarRename:`重命名`,sidebarPin:`置顶`,sidebarUnpin:`取消置顶`,sidebarFork:`分叉`,sidebarForkLocal:`创建聊天分支`,sidebarForkSameWorktree:`在同一工作树中分叉`,archiveNoticeTitle:`聊天已归档`,archiveNoticeView:`查看`,archiveNoticeUndo:`撤销`,archiveNoticeFailed:`操作未完成,请重试。`,sidebarForkWorktree:`在新工作树中创建聊天分支`,sidebarForkCancelling:`正在请求取消…`,sidebarForkFinishing:`无法再取消,正在确认创建结果…`,sidebarForkCancelUnconfirmed:`无法确认取消,正在等待分叉结果。`,sidebarForkWorktreePreserved:`工作树已保留在 {{path}},请检查后再重试。`,sidebarForkWorktreePending:`正在创建工作树和聊天分支…`,sidebarForkOptionsLoading:`正在检查工作树是否可用…`,sidebarForkOptionsFailed:`无法检查工作树,请重新打开菜单重试。`,sidebarForkUnavailable:`发送消息后才能创建此聊天的分支。`,sidebarForkArchived:`请先恢复此会话,再创建分叉。`,sidebarForkFailed:`未能创建分叉,原会话已保留。`,sidebarCopy:`复制`,sidebarCopyLink:`复制会话链接`,sidebarCopyMarkdown:`复制为 Markdown`,sidebarCopyCwd:`复制工作目录`,sidebarCopied:`已复制`,sidebarCopyFailed:`复制失败,请重试。`,sidebarNewWindow:`在新窗口中打开`,sidebarOpenIn:`打开方式`,sidebarAppsLoading:`正在加载可用应用…`,sidebarAppsFailed:`无法加载应用,请重新打开菜单重试。`,sidebarOpenFailed:`无法在所选应用中打开此项目。`,sidebarArchive:`归档`,sidebarRestore:`恢复`,sidebarDelete:`永久删除`,managedWorktreeRecoveryFull:`请先核对先前未确认的移除请求,再开始新的请求。`,managedWorktreesChanged:`工作树列表已变化,请刷新后重新核对目标。`,managedWorktreesRefresh:`刷新工作树列表`,managedWorktreesBack:`返回工作树列表`,managedWorktreesRetry:`重试请求`,managedWorktrees:`保留的工作树`,managedWorktreesDescription:`删除会话会保留 OpenPI 创建的工作树。请核对准确路径后再请求移除。使用中、共享、有改动或无法确认归属的工作树会保留。`,managedWorktreeConfirm:`移除此工作树?服务端会重新核对归属、使用中的会话及本地改动后再操作。`,managedWorktreeRemoved:`工作树已移除。`,managedWorktreePreserved:`工作树已保留:`,managedWorktreeUncertainTerminal:`移除结果无法确认,不能自动重复移除。请先检查保留路径,再决定后续操作。`,managedWorktreeUncertain:`尚不能确认移除结果。重试会核对原请求。`,managedWorktreeRemoving:`正在核对并移除…`,managedWorktreeRemove:`移除工作树`,managedWorktreeReview:`核对移除`,managedWorktreesEmpty:`这一页没有找到托管工作树。`,managedWorktreesUnavailable:`有 {{count}} 条归属记录无法确认。`,managedWorktreesLoadFailed:`无法加载保留的工作树。请重试,目标不会改变。`,managedWorktreesMore:`加载更多工作树`,managedWorktreeRetainedAfterDelete:`会话已删除,工作树保留在 {{path}}。可从项目菜单核对保留的工作树。`,sidebarDeleteTitle:`删除会话?`,sidebarDeleteDescription:`确定永久删除“{{name}}”?此操作无法撤销。`,sidebarDeleteConfirm:`删除`,sidebarDeleting:`正在删除…`,sidebarDeleteFailed:`未能删除此会话,请重试或取消。`,sidebarActionRunning:`请等待当前工作和排队消息结束。`,sidebarActionDisconnected:`请先恢复连接,再修改此会话。`,sessionDeleteCancelled:`删除已取消`,sessionDeleteUncertain:`无法确认会话是否删除,请刷新后重试`,sessionDeleted:`会话已永久删除`,sessionDeleteMetadataPending:`会话已删除,但侧栏记录未清理完成`,sessionLinkUnavailable:`链接中的会话已不存在或身份已变化`,sidebarDropPin:`拖到此处置顶`,sidebarDropProjectLast:`将项目移到最后`,conversationTurns:`会话轮次`,conversationTurnPosition:`前往第 {{position}} 轮`,turnPreviewLoading:`正在加载预览…`,turnPreviewUnavailable:`暂时无法读取,请重试。`,commands:`斜杠命令`,addContext:`添加上下文`,fileReference:`引用工作区文件`,fileReferenceTitle:`引用工作区文件`,fileReferenceDetail:`将路径引用加入提示词,不上传文件内容。`,fileReferenceLabel:`工作区文件路径`,fileReferencePlaceholder:`src/app.tsx`,fileReferenceValidatedHint:`当前会话会验证该路径是可读取的工作区文件。`,fileReferenceDraftHint:`新会话启动后,Pi 会按其工具权限解析该路径。`,fileReferenceChecking:`正在检查…`,fileReferenceFailed:`无法验证该文件。`,fileReferenceDenied:`请选择当前会话工作区内的文件。`,fileReferenceMissing:`该工作区文件已不存在。`,fileReferenceUnsupported:`只能引用工作区中的普通文件。`,fileReferenceExpired:`活动会话已变化,请重新打开文件引用后再试。`,fileReferenceBusy:`文件校验正忙,请稍后重试。`,insertReference:`插入引用`,commandsSessionRequired:`会话启动后才能插入斜杠命令。`,commandsEmptyDraftOnly:`只能在空白草稿中插入斜杠命令。`,commandsLoading:`正在加载命令…`,commandsUnavailable:`暂时无法读取命令。`,commandsNoMatch:`没有匹配的命令。`,commandsNoAvailable:`已发现的命令均不能在 Web 中运行。输入具体命令名可查看其可用性。`,commandsBounded:`另有 {{count}} 个命令未显示。`,commandSessionRequired:`命令仅在已创建的 Web 会话中可用。`,commandUnsupported:`尚未适配 · 手动命令仍交给 Pi`,commandAcceptsArguments:`可输入参数`,commandSource_extension:`扩展命令`,commandSource_prompt:`提示词模板`,commandSource_skill:`技能`,copiedMessage:`已复制`,copyMessage:`复制消息`,copyFailed:`复制失败,请选中消息后手动复制。`,copiedCode:`代码已复制`,copyCode:`复制代码`,copyCodeFailed:`无法复制代码,请选中后手动复制。`,codeBlock:`代码块`,deleteWorkspace:`删除工作区`,describeTask:`描述任务`,editMessage:`修改并从这里重跑`,enterHint:`按 Enter 发送,Shift+Enter 换行。`,expandSidebar:`展开侧边栏`,importWorkspace:`导入工作区`,loadingModels:`正在加载模型...`,modelsTruncated:`当前显示 {{shown}} 个模型,还有 {{omitted}} 个可用;搜索即可查找。`,searchModels:`搜索可用模型`,searchModelsPlaceholder:`搜索服务商、模型名称或 ID...`,searchingModels:`正在搜索模型...`,noMatchingModels:`没有匹配的模型`,modelSearchFailed:`模型搜索失败,请重试。`,retryModelSearch:`重试模型搜索`,fileReferenceDraftChanged:`草稿已变化,请重新打开文件引用。`,modelSearchTruncated:`还有 {{omitted}} 个匹配模型未显示。`,modelPreparing:`正在准备任务...`,modelRetrying:`模型请求重试中...`,modelRunning:`正在运行...`,modelRequestFailed:`模型请求失败`,modelRequestStopped:`模型请求已停止`,modelFailureUnknown:`服务商没有返回具体失败原因。`,retryPrompt:`重试消息`,retryingPrompt:`正在重试…`,newSession:`新建会话`,noConversations:`暂无对话`,noMatching:`没有匹配的会话`,noMatchingLoaded:`已加载历史中没有匹配的会话`,noModels:`没有可用模型`,noOutput:`无输出`,noSessions:`暂无会话`,openSidebar:`打开侧边栏`,promptMessage:`发消息或创建任务,/ 调用指令`,promptReadonly:`非当前会话不能接收消息`,promptStart:`选择一个工作区开始`,promptTask:`描述你想要构建的任务`,landingTagline:`小骨架 · 净上下文 · 深扩展`,queuedHint:`当前回合结束后将发送消息。`,reconnecting:`正在重连`,removeWorkspace:`从侧边栏移除`,workspaceOptions:`工作区选项`,renameFailed:`无法保存名称,已保留你的修改。`,savingName:`正在保存...`,workspaceRemoveFailed:`无法移出工作区,请重试。`,removingWorkspace:`正在移出...`,renameConversation:`重命名会话`,renameWorkspace:`重命名工作区`,save:`保存`,searchConversations:`搜索会话`,searchPlaceholder:`筛选标题与工作目录…`,selectModel:`选择模型`,configureModels:`配置模型`,openModelSettings:`模型设置`,selectThinking:`选择思考等级`,resetThinking:`恢复打开时的等级({{level}})`,modelThinkingNotEnabled:`此模型未启用思考。如提供商支持,可在模型设置中开启「支持推理」。`,providerReasoningHint:`按提供商能力开启;可用档位由 Pi 提供,在聊天输入框调节强度。`,providerImageHint:`未勾选图片时,模型不会收到图片附件。`,selectWorkspace:`选择工作区`,send:`发送`,processDetails:`执行过程`,processRunning:`正在执行`,processThinkingCount:`{{count}} 段思考`,processToolCount:`{{count}} 次工具调用`,processActivityCount:`{{count}} 项 Agent 活动`,switchingSession:`正在切换会话...`,thinkingActive:`思考中...`,thinkingActiveLevel:`思考中({{level}})...`,thinkingDone:`思考过程`,thinkingLoadFull:`查看完整思考`,thinkingLoadingFull:`正在加载思考…`,thinkingLoadFailed:`思考加载失败,点击重试`,thinkingPartialText:`当前显示部分已保存的思考,可继续加载下方内容。`,thinkingPreviewOnly:`思考预览已达到显示上限,此消息保存后可查看完整内容。`,toolState_running:`执行中`,toolState_returned:`已返回`,toolState_failed:`失败`,toolState_cancelled:`已停止`,toolState_timed_out:`超时`,toolState_unknown:`未确认`,toolSnapshotMissingResult:`分叉时尚无结果`,toolActivity_running:`正在{{action}}`,toolActivity_failed:`{{action}}失败`,toolActivity_cancelled:`{{action}}已停止`,toolActivity_timed_out:`{{action}}超时`,toolActivity_unknown:`{{action}}`,toolAction_read:`读取`,toolAction_write:`写入文件`,toolAction_edit:`编辑文件`,toolAction_command:`运行`,toolAction_search:`搜索`,toolAction_list:`列出文件`,toolAction_web:`浏览网页`,toolAction_agent:`使用子代理`,toolAction_workflow:`调用工作流`,toolAction_plan:`准备计划`,toolAction_task:`处理任务`,toolAction_goal:`处理目标`,toolAction_git:`查看变更`,toolAction_call:`调用工具`,toolActionDone_read:`已读取`,toolActionDone_write:`已写入`,toolActionDone_edit:`已编辑`,toolActionDone_command:`已运行`,toolActionDone_search:`已搜索`,toolActionDone_list:`已列出的文件`,toolActionDone_web:`已浏览网页`,toolActionDone_agent:`子代理工具已返回`,toolActionDone_workflow:`工作流工具已返回`,toolActionDone_plan:`计划工具已返回`,toolActionDone_task:`任务工具已返回`,toolActionDone_goal:`目标工具已返回`,toolActionDone_git:`已查看变更`,toolActionDone_call:`已调用工具`,toolActionGroup_read:`读取文件`,toolActionGroup_write:`写入文件`,toolActionGroup_edit:`编辑文件`,toolActionGroup_command:`运行命令`,toolActionGroup_search:`搜索`,toolActionGroup_list:`列出文件`,toolActionGroup_web:`浏览网页`,toolActionGroup_agent:`子代理活动`,toolActionGroup_workflow:`工作流活动`,toolActionGroup_plan:`准备计划`,toolActionGroup_task:`处理任务`,toolActionGroup_goal:`处理目标`,toolActionGroup_git:`查看变更`,toolActionGroup_call:`调用工具`,toolGroup_done:`已{{actions}}`,toolGroup_running:`正在{{actions}}`,toolGroup_unknown:`{{actions}}`,toolGroupSeparator:`、`,toolSearchTarget:`“{{pattern}}” · {{path}}`,toolDiffStatsHelp:`当前显示差异中的新增和删除行数`,toolRequestedFile:`文件:`,toolWorkspace:`工作区`,toolRawEvidence:`参数与原始结果`,toolCodemodeDetails:`脚本与原始结果`,toolNestedOutputMissing:`会话记录保留了调用和状态,未保存此子工具的输出。`,toolNestedArgumentsMissing:`会话记录未保留完整参数和此子工具的输出。`,toolNestedIncomplete:`子调用记录不完整,部分调用、参数或最终状态不可用。`,toolPartialEvidence:`输出未完整显示:已达到字节、行数或条目上限。原始结果也可能被截断。`,toolFileChange_created:`已创建文件`,toolFileChange_unchanged:`文件内容未改变`,toolFileChange_overwritten:`已覆盖文件`,toolChangeUnavailable:`此工具结果未提供修改对比。`,toolTestResults:`测试结果摘要 · {{format}}`,toolTestCounts:`{{tests}} 项测试 · {{passed}} 通过 · {{failed}} 失败 · {{cancelled}} 取消`,toolTestCountsHelp:`数量来自命令输出,执行状态单独显示。`,toolReadMore:`可使用文件路径和 offset 继续读取,具体方式见原始结果。`,toolFullOutputReference:`完整输出:`,subagentBackgroundResult:`后台子代理结果 · {{count}}`,thinkingDraftHint:`请先选择工作区并创建会话。`,thinkingInactiveHint:`只有当前会话可以更改思考等级。`,thinkingLevelMismatch:`当前确认的思考等级不在此模型支持范围内;选择其它等级即可修正。`,thinkingLockedRunning:`请先停止当前轮次,再更改思考等级。`,thinkingModelPendingHint:`请等待模型切换完成。`,thinkingNotConfirmed:`思考等级未获确认,请重试。`,thinkingPendingHint:`正在应用思考等级...`,thinkingUnsupported:`暂不支持思考`,thinkingUnsupportedHint:`尚未选择模型,或当前模型不支持思考。`,unavailable:`不可用`,ungrouped:`未分组`,untitledSession:`新会话`,workspaceDeleteConfirm:`文件夹与会话记录会保留,其中的会话会被放到“未分组”;再次打开此目录时将是一个干净的工作区。`,workspaceName:`工作区名称`,workspaces:`工作区`,sidebarProjects:`项目`}}},lJ=navigator.language?.toLowerCase().startsWith(`zh`)?`zh`:`en`;In.use(tr).init({fallbackLng:`en`,initAsync:!1,interpolation:{escapeValue:!1},lng:lJ,resources:cJ}),document.documentElement.lang=lJ===`zh`?`zh-CN`:`en`;var uJ=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},dJ=10,fJ=13,pJ=32,mJ=6;function hJ(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{maxBufferSize:t,onComment:n,onError:r,onEvent:i,onId:a,onRetry:o}=e,s=[],c=0,l=!0,u,d=``,f=0,p,m=!1,h=!1,g=!1;function _(e){if(m)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,e.charCodeAt(0)===65279?e=e.slice(1):e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),(h||g)&&(e=v(e),!e))return;if(!s.length){let t=S(e);t!==``&&y(t),x();return}if(e.indexOf(` -`)===-1&&e.indexOf(`\r`)===-1){if(cthis._refresh()),eG&&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),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=CG(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,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=RW(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-wG),wG),t/=wG,t/Math.abs(t)+Math.round(t*(TG-1)))}shouldForceSelection(e){return XW?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(),EG)}_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&&!(XW&&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]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]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&&tthis._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(!(!t&&o.slice(s,c).trim()===``)){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={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=CG(n,this._bufferService.cols)}};kG=Wz([Gz(3,vB),Gz(4,bB),Gz(5,MB),Gz(6,wB),Gz(7,NB),Gz(8,jB)],kG);var AG=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},jG=class{constructor(){this._color=new AG,this._css=new AG}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},MG=Object.freeze((()=>{let e=[oW.toColor(`#2e3436`),oW.toColor(`#cc0000`),oW.toColor(`#4e9a06`),oW.toColor(`#c4a000`),oW.toColor(`#3465a4`),oW.toColor(`#75507b`),oW.toColor(`#06989a`),oW.toColor(`#d3d7cf`),oW.toColor(`#555753`),oW.toColor(`#ef2929`),oW.toColor(`#8ae234`),oW.toColor(`#fce94f`),oW.toColor(`#729fcf`),oW.toColor(`#ad7fa8`),oW.toColor(`#34e2e2`),oW.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:iW.toCss(r,i,a),rgba:iW.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:iW.toCss(n,n,n),rgba:iW.toRgba(n,n,n)})}return e})()),NG=oW.toColor(`#ffffff`),PG=oW.toColor(`#000000`),FG=oW.toColor(`#ffffff`),IG=PG,LG={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},RG=NG,zG=class extends sV{constructor(e){super(),this._optionsService=e,this._contrastCache=new jG,this._halfContrastCache=new jG,this._onChangeColors=this._register(new OV),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:NG,background:PG,cursor:FG,cursorAccent:IG,selectionForeground:void 0,selectionBackgroundTransparent:LG,selectionBackgroundOpaque:aW.blend(PG,LG),selectionInactiveBackgroundTransparent:LG,selectionInactiveBackgroundOpaque:aW.blend(PG,LG),scrollbarSliderBackground:aW.opacity(NG,.2),scrollbarSliderHoverBackground:aW.opacity(NG,.4),scrollbarSliderActiveBackground:aW.opacity(NG,.5),overviewRulerBorder:NG,ansi:MG.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=BG(e.foreground,NG),t.background=BG(e.background,PG),t.cursor=aW.blend(t.background,BG(e.cursor,FG)),t.cursorAccent=aW.blend(t.background,BG(e.cursorAccent,IG)),t.selectionBackgroundTransparent=BG(e.selectionBackground,LG),t.selectionBackgroundOpaque=aW.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=BG(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=aW.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?BG(e.selectionForeground,rW):void 0,t.selectionForeground===rW&&(t.selectionForeground=void 0),aW.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=aW.opacity(t.selectionBackgroundTransparent,.3)),aW.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=aW.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=BG(e.scrollbarSliderBackground,aW.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=BG(e.scrollbarSliderHoverBackground,aW.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=BG(e.scrollbarSliderActiveBackground,aW.opacity(t.foreground,.5)),t.overviewRulerBorder=BG(e.overviewRulerBorder,RG),t.ansi=MG.slice(),t.ansi[0]=BG(e.black,MG[0]),t.ansi[1]=BG(e.red,MG[1]),t.ansi[2]=BG(e.green,MG[2]),t.ansi[3]=BG(e.yellow,MG[3]),t.ansi[4]=BG(e.blue,MG[4]),t.ansi[5]=BG(e.magenta,MG[5]),t.ansi[6]=BG(e.cyan,MG[6]),t.ansi[7]=BG(e.white,MG[7]),t.ansi[8]=BG(e.brightBlack,MG[8]),t.ansi[9]=BG(e.brightRed,MG[9]),t.ansi[10]=BG(e.brightGreen,MG[10]),t.ansi[11]=BG(e.brightYellow,MG[11]),t.ansi[12]=BG(e.brightBlue,MG[12]),t.ansi[13]=BG(e.brightMagenta,MG[13]),t.ansi[14]=BG(e.brightCyan,MG[14]),t.ansi[15]=BG(e.brightWhite,MG[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;re.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},UG={trace:0,debug:1,info:2,warn:3,error:4,off:5},WG=`xterm.js: `,GG=class extends sV{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),KG=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=UG[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;tthis._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*JG+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*JG+0]=e|2097152|t[2]<<22):this._data[e*JG+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*JG+0]>>22}hasWidth(e){return this._data[e*JG+0]&12582912}getFg(e){return this._data[e*JG+1]}getBg(e){return this._data[e*JG+2]}hasContent(e){return this._data[e*JG+0]&4194303}getCodePoint(e){let t=this._data[e*JG+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*JG+0]&2097152}getString(e){let t=this._data[e*JG+0];return t&2097152?this._combined[e]:t&2097151?rB(t&2097151):``}isProtected(e){return this._data[e*JG+2]&536870912}loadCell(e,t){return XG=e*JG,t.content=this._data[XG+0],t.fg=this._data[XG+1],t.bg=this._data[XG+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*JG+0]=t.content,this._data[e*JG+1]=t.fg,this._data[e*JG+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*JG+0]=t|n<<22,this._data[e*JG+1]=r.fg,this._data[e*JG+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*JG+0];r&2097152?this._combined[e]+=rB(t):r&2097151?(this._combined[e]=rB(r&2097151)+rB(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*JG+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;rthis.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*ZG=0;--e)if(this._data[e*JG+0]&4194303)return e+(this._data[e*JG+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*JG+0]&4194303||this._data[e*JG+2]&50331648)return e+(this._data[e*JG+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t>22||1}return r&&r.push(t),i}};function $G(e,t,n,r,i,a){let o=[];for(let s=0;s=s&&r0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function eK(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;orK(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;sc&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function rK(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var iK=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new OV),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),nV(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};iK._nextId=1;var aK=iK,oK={},sK=oK.B;oK[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:`␤`,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},oK.A={"#":`£`},oK.B=void 0,oK[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},oK.C=oK[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},oK.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},oK.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},oK.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},oK.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},oK.E=oK[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},oK.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},oK.H=oK[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},oK[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var cK=4294967295,lK=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=YG.clone(),this.savedCharset=sK,this.markers=[],this._nullCell=dB.fromCharData([0,sB,1,0]),this._whitespaceCell=dB.fromCharData([0,cB,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new aG,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new qG(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 uB),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 uB),this._whitespaceCell}getBlankLine(e,t){return new QG(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&&ecK?cK:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=YG);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 qG(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(YG),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new QG(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),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 t=0;t.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._memoryCleanupPosition100)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 n=this._optionsService.rawOptions.reflowCursorLine,r=$G(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(YG),n);if(r.length>0){let n=eK(this.lines,r);tK(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(YG),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=rK(c,Math.max(g,0),this._cols))}for(let t=0;t0;)this.ybase===0?this.y0){let e=[],t=[];for(let e=0;e=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.linee.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},uK=class extends sV{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new OV),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 lK(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new lK(!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)}},dK=2,fK=1,pK=class extends sV{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new OV),this.onResize=this._onResize.event,this._onScroll=this._register(new OV),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,dK),this.rows=Math.max(e.rawOptions.rows||0,fK),this.buffers=this._register(new uK(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};pK=Wz([Gz(0,wB)],pK);var mK={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:XW,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},hK=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],gK=class extends sV{constructor(e){super(),this._onOptionChange=this._register(new OV),this.onOptionChange=this._onOptionChange.event;let t={...mK};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(iV(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in mK))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in mK))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=mK[e],!_K(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=mK[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=hK.includes(t)?t:mK[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw 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 Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function _K(e){return e===`block`||e===`underline`||e===`bar`}function vK(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&vK(e[r],t-1);return n}var yK=Object.freeze({insertMode:!1}),bK=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),xK=class extends sV{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new OV),this.onData=this._onData.event,this._onUserInput=this._register(new OV),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new OV),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new OV),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=vK(yK),this.decPrivateModes=vK(bK)}reset(){this.modes=vK(yK),this.decPrivateModes=vK(bK)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.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(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};xK=Wz([Gz(0,vB),Gz(1,CB),Gz(2,wB)],xK);var SK={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 CK(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var wK=String.fromCharCode,TK={DEFAULT:e=>{let t=[CK(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${wK(t[0])}${wK(t[1])}${wK(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${CK(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${CK(e,!0)};${e.x};${e.y}${t}`}},EK=class extends sV{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new OV),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(SK))this.addProtocol(e,SK[e]);for(let e of Object.keys(TK))this.addEncoding(e,TK[e]);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 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 Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+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,n){if(n){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}};EK=Wz([Gz(0,vB),Gz(1,bB),Gz(2,wB)],EK);var DK=[[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]],OK=[[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]],kK;function AK(e,t){let n=0,r=t.length-1,i;if(et[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=MK.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return MK.createPropertyValue(0,n,r)}},MK=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new OV,this.onChange=this._onChange.event;let e=new jK;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},NK=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 PK(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var FK=2147483647,IK=256,LK=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>IK)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>FK?FK:e}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>FK?FK:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,FK):e}},RK=[],zK=class{constructor(){this._state=0,this._active=RK,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 n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,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=RK}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=RK,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||RK,!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,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,iB(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,n)}}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 n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=RK,this._id=-1,this._state=0}}},BK=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=iB(e,t,n),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(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},VK=[],HK=class{constructor(){this._handlers=Object.create(null),this._active=VK,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=VK}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,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=VK,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||VK,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,iB(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=VK,this._ident=0}},UK=new LK;UK.addParam(0);var WK=class{constructor(e){this._handler=e,this._data=``,this._params=UK,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():UK,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=iB(e,t,n),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(e=>(this._params=UK,this._data=``,this._hitLimit=!1,e));return this._params=UK,this._data=``,this._hitLimit=!1,t}},GK=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;it),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,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(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,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(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(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(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(KK,0,2,0),e.add(KK,8,5,8),e.add(KK,6,0,6),e.add(KK,11,0,11),e.add(KK,13,13,13),e}(),JK=class extends sV{constructor(e=qK){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 LK,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(iV(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new zK),this._dcsParser=this._register(new HK),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;tr||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}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 n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,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 n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,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,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let n=a;n>4){case 2:for(let i=n+1;;++i){if(i>=t||(r=e[i])<32||r>126&&r=t||(r=e[i])<32||r>126&&r=t||(r=e[i])<32||r>126&&r=t||(r=e[i])<32||r>126&&r=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),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|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r=t||(r=e[i])<32||r>127&&r>4:i>>8}return n}}function QK(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function $K(e,t=16){let[n,r,i]=e;return`rgb:${QK(n,t)}/${QK(r,t)}/${QK(i,t)}`}var eq={"(":0,")":1,"*":2,"+":3,"-":1,".":2},tq=131072,nq=10;function rq(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 iq=5e3,aq=0,oq=class extends sV{constructor(e,t,n,r,i,a,o,s,c=new JK){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new aB,this._utf8Decoder=new oB,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=YG.clone(),this._eraseAttrDataInternal=YG.clone(),this._onRequestBell=this._register(new OV),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new OV),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new OV),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new OV),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new OV),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new OV),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new OV),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new OV),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new OV),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new OV),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new OV),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new OV),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new OV),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 sq(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler($.BEL,()=>this.bell()),this._parser.setExecuteHandler($.LF,()=>this.lineFeed()),this._parser.setExecuteHandler($.VT,()=>this.lineFeed()),this._parser.setExecuteHandler($.FF,()=>this.lineFeed()),this._parser.setExecuteHandler($.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler($.BS,()=>this.backspace()),this._parser.setExecuteHandler($.HT,()=>this.tab()),this._parser.setExecuteHandler($.SO,()=>this.shiftOut()),this._parser.setExecuteHandler($.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(XU.IND,()=>this.index()),this._parser.setExecuteHandler(XU.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(XU.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new BK(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new BK(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new BK(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new BK(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new BK(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new BK(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new BK(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new BK(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new BK(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new BK(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new BK(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new BK(e=>this.restoreCursorColor(e))),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 e in oK)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new WK((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),iq))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${iq} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>tq&&(a=this._parseStack.position+tq)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.lengthtq)for(let t=a;t0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;ps){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,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),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof QG&&d.copyCellsFrom(e,t,0,m,!1);t=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!rq(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new WK(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new BK(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,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}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)}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.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let c=s;for(let e=1;e0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent($.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent($.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent($.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent($.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent($.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${$.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=lB.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=YG.fg,e.bg=YG.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,n,r=this._curAttrData;for(let i=0;i=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=YG.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=YG.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=YG.fg&16777215,r.bg&=-67108864,r.bg|=YG.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${$.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[?${e};${t}R`)}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=YG.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`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!rq(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(`${$.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>nq&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>nq&&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())}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=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(cq(n))if(r===`?`)t.push({type:0,index:n});else{let e=ZK(r);e&&t.push({type:1,index:n,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,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 n=e.split(`;`);for(let e=0;e=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=ZK(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}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=[],n=e.split(`;`);for(let e=0;e=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=YG.clone(),this._eraseAttrDataInternal=YG.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 dB;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${$.ESC}${e}${$.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},sq=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(aq=e,e=t,t=aq),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};sq=Wz([Gz(0,vB)],sq);function cq(e){return 0<=e&&e<256}var lq=5e7,uq=12,dq=50,fq=class extends sV{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 OV),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 n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>lq)throw 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 n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=uq?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=uq)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>dq&&(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()}},pq=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 n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};pq=Wz([Gz(0,vB)],pq);var mq=!1,hq=class extends sV{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new cV),this._onBinary=this._register(new OV),this.onBinary=this._onBinary.event,this._onData=this._register(new OV),this.onData=this._onData.event,this._onLineFeed=this._register(new OV),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new OV),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new OV),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new OV),this._instantiationService=new HG,this.optionsService=this._register(new gK(e)),this._instantiationService.setService(wB,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(pK)),this._instantiationService.setService(vB,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(GG)),this._instantiationService.setService(CB,this._logService),this.coreService=this._register(this._instantiationService.createInstance(xK)),this._instantiationService.setService(bB,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(EK)),this._instantiationService.setService(yB,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(MK)),this._instantiationService.setService(EB,this.unicodeService),this._charsetService=this._instantiationService.createInstance(NK),this._instantiationService.setService(xB,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(pq),this._instantiationService.setService(TB,this._oscLinkService),this._inputHandler=this._register(new oq(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(hV.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(hV.forward(this._bufferService.onResize,this._onResize)),this._register(hV.forward(this.coreService.onData,this._onData)),this._register(hV.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 fq((e,t)=>this._inputHandler.parse(e,t))),this._register(hV.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new OV),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&&!mq&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),mq=!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,dK),t=Math.max(t,fK),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(PK.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(PK(this._bufferService),!1))),this._windowsWrappingHeuristics.value=iV(()=>{for(let t of e)t.dispose()})}}},gq={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 _q(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?$.ESC+`OA`:$.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?$.ESC+`OD`:$.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?$.ESC+`OC`:$.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?$.ESC+`OB`:$.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:$.DEL,e.altKey&&(i.key=$.ESC+i.key);break;case 9:if(e.shiftKey){i.key=$.ESC+`[Z`;break}i.key=$.HT,i.cancel=!0;break;case 13:i.key=e.altKey?$.ESC+$.CR:$.CR,i.cancel=!0;break;case 27:i.key=$.ESC,e.altKey&&(i.key=$.ESC+$.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`D`:t?$.ESC+`OD`:$.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`C`:t?$.ESC+`OC`:$.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`A`:t?$.ESC+`OA`:$.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`B`:t?$.ESC+`OB`:$.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=$.ESC+`[2~`);break;case 46:i.key=a?$.ESC+`[3;`+(a+1)+`~`:$.ESC+`[3~`;break;case 36:i.key=a?$.ESC+`[1;`+(a+1)+`H`:t?$.ESC+`OH`:$.ESC+`[H`;break;case 35:i.key=a?$.ESC+`[1;`+(a+1)+`F`:t?$.ESC+`OF`:$.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?$.ESC+`[5;`+(a+1)+`~`:$.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?$.ESC+`[6;`+(a+1)+`~`:$.ESC+`[6~`;break;case 112:i.key=a?$.ESC+`[1;`+(a+1)+`P`:$.ESC+`OP`;break;case 113:i.key=a?$.ESC+`[1;`+(a+1)+`Q`:$.ESC+`OQ`;break;case 114:i.key=a?$.ESC+`[1;`+(a+1)+`R`:$.ESC+`OR`;break;case 115:i.key=a?$.ESC+`[1;`+(a+1)+`S`:$.ESC+`OS`;break;case 116:i.key=a?$.ESC+`[15;`+(a+1)+`~`:$.ESC+`[15~`;break;case 117:i.key=a?$.ESC+`[17;`+(a+1)+`~`:$.ESC+`[17~`;break;case 118:i.key=a?$.ESC+`[18;`+(a+1)+`~`:$.ESC+`[18~`;break;case 119:i.key=a?$.ESC+`[19;`+(a+1)+`~`:$.ESC+`[19~`;break;case 120:i.key=a?$.ESC+`[20;`+(a+1)+`~`:$.ESC+`[20~`;break;case 121:i.key=a?$.ESC+`[21;`+(a+1)+`~`:$.ESC+`[21~`;break;case 122:i.key=a?$.ESC+`[23;`+(a+1)+`~`:$.ESC+`[23~`;break;case 123:i.key=a?$.ESC+`[24;`+(a+1)+`~`:$.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=$.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=$.DEL:e.keyCode===219?i.key=$.ESC:e.keyCode===220?i.key=$.FS:e.keyCode===221&&(i.key=$.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=gq[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=$.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=$.ESC+n}else if(e.keyCode===32)i.key=$.ESC+(e.ctrlKey?$.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=$.ESC+t,i.cancel=!0}}else n&&!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=$.US),e.key===`@`&&(i.key=$.NUL))}return i}var vq=0,yq=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new aG,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new aG,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((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,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||(vq=this._search(t),vq===-1)||this._getKey(this._array[vq])!==t)return!1;do if(this._array[vq]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(vq),!0;while(++vqe-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(vq=this._search(e),!(vq<0||vq>=this._array.length)&&this._getKey(this._array[vq])===e))do yield this._array[vq];while(++vq=this._array.length)&&this._getKey(this._array[vq])===e))do t(this._array[vq]);while(++vq=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},bq=0,xq=0,Sq=class extends sV{constructor(){super(),this._decorations=new yq(e=>e?.marker.line),this._onDecorationRegistered=this._register(new OV),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new OV),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(iV(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Cq(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.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,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e{bq=t.options.x??0,xq=bq+(t.options.width??1),e>=bq&&e=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_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)}},Eq=20,Dq=class extends sV{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,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 e=0;ethis._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,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 Tq(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` +`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register($H(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(iV(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Eq+1&&(this._liveRegion.textContent+=Yz.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 n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}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},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,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 r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(!(!a||!o)){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;ee;)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{nV(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($H(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register($H(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register($H(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register($H(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 n=e.composedPath();for(let e=0;e{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;re?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;tthis._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;ethis._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&kq(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,nV(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||e.link.decorations.underline,pointerCursor:e.link.decorations===void 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:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){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(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){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(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};Oq=Wz([Gz(1,MB),Gz(2,NB),Gz(3,vB),Gz(4,LB)],Oq);function kq(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 Aq=class extends hq{constructor(e={}){super(e),this._linkifier=this._register(new cV),this.browser=HW,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new cV),this._onCursorMove=this._register(new OV),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new OV),this.onKey=this._onKey.event,this._onRender=this._register(new OV),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new OV),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new OV),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new OV),this.onBell=this._onBell.event,this._onFocus=this._register(new OV),this._onBlur=this._register(new OV),this._onA11yCharEmitter=this._register(new OV),this._onA11yTabEmitter=this._register(new OV),this._onWillOpen=this._register(new OV),this._setup(),this._decorationService=this._instantiationService.createInstance(Sq),this._instantiationService.setService(DB,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(LW),this._instantiationService.setService(LB,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(OB)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(hV.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(hV.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(hV.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(hV.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(iV(()=>{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 e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=aW.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${$.ESC}]${n};${$K(r)}${ZU.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=iW.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=iW.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_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(Dq,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.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($.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 n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register($H(this.element,`copy`,e=>{this.hasSelection()&&Qz(e,this._selectionService)}));let e=e=>$z(e,this.textarea,this.coreService,this.optionsService);this._register($H(this.textarea,`paste`,e)),this._register($H(this.element,`paste`,e)),KW?this._register($H(this.element,`mousedown`,e=>{e.button===2&&nB(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register($H(this.element,`contextmenu`,e=>{nB(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),eG&&this._register($H(this.element,`auxclick`,e=>{e.button===1&&tB(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register($H(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register($H(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register($H(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register($H(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register($H(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register($H(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register($H(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw 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($H(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,qz.get()),tG||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`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(FW,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(jB,this._coreBrowserService),this._register($H(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register($H(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(jW,this._document,this._helperContainer),this._instantiationService.setService(AB,this._charSizeService),this._themeService=this._instantiationService.createInstance(zG),this._instantiationService.setService(IB,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(fW),this._instantiationService.setService(FB,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(sG,this.rows,this.screenElement)),this._instantiationService.setService(NB,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(QU,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(BW),this._instantiationService.setService(MB,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Oq,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(UU,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(kG,this.element,this.screenElement,r)),this._instantiationService.setService(PB,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(hV.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(WU,this.screenElement)),this._register($H(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),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(Dq,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(YU,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(YU,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(AW,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),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()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register($H(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(e)))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register($H(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=$.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!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){eB(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 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 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,n){this._selectionService.setSelection(e,t,n)}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 n=_q(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.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((n.key===$.ETX||n.key===$.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=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`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(jq(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=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new dB)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},Pq=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 Nq(t)}getNullCell(){return new dB}},Fq=class extends sV{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new OV),this.onBufferChange=this._onBufferChange.event,this._normal=new Pq(this._core.buffers.normal,`normal`),this._alternate=new Pq(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},Iq=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,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)}},Lq=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}},Rq=[`cols`,`rows`],zq=0,Bq=class extends sV{constructor(e){super(),this._core=this._register(new Aq(e)),this._addonManager=this._register(new Mq),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(Rq.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get 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||=new Iq(this._core),this._parser}get unicode(){return this._checkProposedApi(),new Lq(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._register(new Fq(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`}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,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}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 +`,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 qz.get()},set promptLabel(e){qz.set(e)},get tooMuchOutput(){return Yz.get()},set tooMuchOutput(e){Yz.set(e)}}}_verifyIntegers(...e){for(zq of e)if(zq===1/0||isNaN(zq)||zq%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(zq of e)if(zq&&(zq===1/0||isNaN(zq)||zq%1!=0||zq<0))throw Error(`This API only accepts positive integers`)}};function Vq(){return{background:`#101316`,foreground:`#d7dde3`,cursor:`#7db8ff`,selectionBackground:`#365b8a`,black:`#1d2227`,red:`#ff7b72`,green:`#56d364`,yellow:`#e3b341`,blue:`#79c0ff`,magenta:`#d2a8ff`,cyan:`#39c5cf`,white:`#e6edf3`,brightBlack:`#6e7681`,brightRed:`#ffa198`,brightGreen:`#7ee787`,brightYellow:`#f2cc60`,brightBlue:`#a5d6ff`,brightMagenta:`#d2a8ff`,brightCyan:`#56d4dd`,brightWhite:`#ffffff`}}function Hq({sessionId:e,cwd:t,tabId:n,active:r=!0,onConnectionChange:i}){let{t:a}=cr(),o=(0,_.useMemo)(()=>new rf,[]),s=wk(),c=n?s?.terminals?.[n]:s?.terminal,l=t.replace(/[\\/]+$/u,``).split(/[\\/]/u).pop()||t,u=(0,_.useRef)(r);u.current=r;let d=(0,_.useRef)(null),f=(0,_.useRef)(null),p=(0,_.useRef)(c?.id??null),[m,h]=(0,_.useState)(`connecting`),[g,v]=(0,_.useState)(null),[y,b]=(0,_.useState)(null),[x,S]=(0,_.useState)(!1),[C,T]=(0,_.useState)(!1),[E,D]=(0,_.useState)(0),O=(0,_.useRef)(null),k=(0,_.useRef)(null),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(null),I=(0,_.useRef)(i);I.current=i,(0,_.useEffect)(()=>{I.current?.({id:p.current,pending:[`connecting`,`reconnecting`,`restarting`].includes(m)})},[m]),(0,_.useEffect)(()=>{let r=d.current;if(!r)return;let i=n?s?.terminals?.[n]:s?.terminal;p.current??=i?.id??null;let c=!1,l=!1,m=!1,g=!1,_,y=!1,x=Promise.resolve(void 0),C=null,w=new AbortController;h(`connecting`),v(null),b(null),S(!1),T(!1),j(!1),N(!1),F(null);let D=new Bq({cursorBlink:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace`,fontSize:13,lineHeight:1.25,scrollback:8e3,screenReaderMode:!0,disableStdin:!0,theme:Vq()}),A=i?{...i}:void 0,M=new Bz;D.loadAddon(M),D.open(r);let P=f.current;f.current=null,!r.closest(`[hidden], [inert]`)&&(E===0||r.closest(`.interactive-terminal`)?.contains(document.activeElement)||P?.sessionId===e&&P.cwd===t&&P.generation===E&&document.activeElement===document.body)&&D.focus(),D.attachCustomKeyEventHandler(e=>{if(e.type!==`keydown`)return!0;let t=e.key.toLowerCase();return t===`escape`&&e.stopPropagation(),!((e.ctrlKey||e.metaKey)&&t===`v`||(e.ctrlKey||e.metaKey)&&t===`c`&&D.hasSelection())});let I=e=>!c&&w===e&&!e.signal.aborted,L=()=>{m=!1,y=!0,C=null,D.options.disableStdin=!0,w.abort()},R=e=>{c||(L(),v(e instanceof Error?e.message:a(`terminalError`)),h(`error`))},ee=e=>{if(y||c)return;let t=w;x=x.then(()=>{if(I(t)&&!y&&m&&!l)return e()}).catch(e=>{I(t)&&R(e)})},z=t=>{let n=p.current;if(!(!n||!u.current||!m||l||y))for(let r of t.match(/[\s\S]{1,32768}/gu)??[]){if(C&&C.data.length+r.length<=65536){C.data+=r;continue}let t={data:r};C=t,ee(async()=>{C===t&&(C=null),await o.writeInteractiveTerminal(e,n,t.data)})}},B=(t,n)=>{let r=p.current;!r||!m||l||y||(C=null,ee(()=>o.resizeInteractiveTerminal(e,r,t,n)))},V=()=>{if(!(!r.offsetWidth||!r.offsetHeight))try{M.fit()}catch{}},H=(e=D.buffer.active.viewportY)=>{let t=e>=D.buffer.active.baseY;S(!t);let r=p.current;if(s&&r&&!A){let i={...n?s.terminals?.[n]:s.terminal,id:r,viewport:e,atBottom:t};n?(s.terminals??={})[n]=i:s.terminal=i}},te=e=>{if(!c){if(e.type===`output`){if(e.reset)D.reset(),_!==void 0&&T(!0);else if(_!==void 0&&e.offset<=_)return;D.write(e.data,()=>{c||(A&&=(A.atBottom?D.scrollToBottom():D.scrollToLine(A.viewport),void 0),H())}),_=e.offset;return}l=!0,m=!1,D.options.disableStdin=!0,w.abort(),b(e.type===`exit`?e.exitCode:null),h(`exited`)}},ne=D.onData(z),re=D.onScroll(H),ie=D.onResize(({cols:e,rows:t})=>B(e,t)),ae=typeof ResizeObserver>`u`?void 0:new ResizeObserver(V);ae?.observe(r);let U=async()=>{if(c||g||m)return;g=!0,L();let r=new AbortController;w=r,x=Promise.resolve();let i=p.current;h(i?`reconnecting`:`connecting`),v(null),V();try{let c=i?await o.interactiveTerminal(e,i,r.signal):await o.createInteractiveTerminal(e,D.cols,D.rows,r.signal,n?`${n}:${E}`:void 0);if(!I(r))return;if(!c.id||c.sessionId!==e||c.cwd!==t||i&&c.id!==i)throw Error(a(`inspectionChanged`));if(g=!1,p.current=c.id,s){let e={viewport:0,atBottom:!0,...n?s.terminals?.[n]:s.terminal,id:c.id};n?(s.terminals??={})[n]=e:s.terminal=e}l=c.exited,m=!c.exited,y=c.exited,D.options.disableStdin=c.exited,h(c.exited?`exited`:`ready`),b(c.exitCode),V(),c.exited||B(D.cols,D.rows),await o.streamInteractiveTerminal(e,c.id,_,r.signal,e=>{I(r)&&te(e)}),I(r)&&!l&&R(Error(a(`terminalDisconnected`)))}catch(e){I(r)&&R(e)}finally{w===r&&(g=!1)}},oe={reconnect:()=>{U()},suspend:L,scrollToBottom:()=>{c||(D.scrollToBottom(),D.focus())}};return O.current=oe,U(),()=>{c=!0,L(),O.current===oe&&(O.current=null),k.current===oe&&(k.current=null),ae?.disconnect(),ne.dispose(),re.dispose(),ie.dispose(),x.catch(()=>void 0),D.dispose(),p.current=null}},[o,t,E,e,a,s,n]);let L=async r=>{let i=O.current;if(!i||k.current)return;k.current=i,N(!0),F(null),h(`restarting`),v(null),i.suspend();let c=p.current;try{if(c&&await o.closeInteractiveTerminal(e,c),O.current!==i)return;if(p.current=null,s)if(n){let e=s.terminals?.[n]?.title;(s.terminals??={})[n]={viewport:0,atBottom:!0,title:e}}else s.terminal=void 0;r&&(f.current={sessionId:e,cwd:t,generation:E+1}),j(!1),D(e=>e+1)}catch(e){if(O.current===i){let t=e instanceof Error?e.message:a(`terminalError`);v(t),F(t),h(`error`),k.current=null,N(!1)}}};return(0,K.jsxs)(`section`,{className:`interactive-terminal`,"aria-label":a(`terminal`),children:[(0,K.jsxs)(`header`,{className:`interactive-terminal-status`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{className:`terminal-status-dot ${m}`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`terminal-cwd`,title:t,children:l}),m===`ready`&&(0,K.jsx)(`span`,{className:`terminal-connection-state`,children:a(`connected`)})]}),(0,K.jsxs)(`div`,{className:`interactive-terminal-actions`,children:[m===`error`&&(0,K.jsxs)(`button`,{type:`button`,"aria-label":a(`reconnectTerminal`),title:a(`reconnectTerminal`),className:`terminal-reconnect-action`,disabled:M,onClick:()=>O.current?.reconnect(),children:[(0,K.jsx)(dt,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:a(`reconnectTerminal`)})]}),(0,K.jsx)(`button`,{type:`button`,"aria-label":a(`restartTerminal`),title:a(`restartTerminal`),disabled:M||m===`connecting`||m===`reconnecting`,onClick:()=>{F(null),j(!0)},children:(0,K.jsx)(ft,{"aria-hidden":`true`})})]})]}),(0,K.jsxs)(`div`,{className:`interactive-terminal-notice`,"aria-live":`polite`,children:[g?(0,K.jsx)(`span`,{className:`error`,children:g}):m===`exited`?(0,K.jsx)(`span`,{children:y===null?a(`terminalExited`):a(`terminalExitCode`,{code:y})}):m===`connecting`?(0,K.jsx)(`span`,{children:a(`terminalConnecting`)}):m===`reconnecting`?(0,K.jsx)(`span`,{children:a(`terminalReconnecting`)}):m===`restarting`?(0,K.jsx)(`span`,{children:a(`terminalRestarting`)}):null,C&&(0,K.jsx)(`span`,{className:`terminal-output-resynced`,children:a(`terminalOutputResynced`)})]}),(0,K.jsxs)(`div`,{className:`interactive-terminal-viewport`,children:[(0,K.jsx)(`div`,{ref:d,className:`interactive-terminal-host`}),x&&(0,K.jsxs)(`button`,{type:`button`,className:`terminal-scroll-bottom`,onClick:()=>O.current?.scrollToBottom(),children:[(0,K.jsx)(w,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:a(`terminalScrollToBottom`)})]})]}),(0,K.jsx)($j,{isOpen:A,purpose:`form`,width:430,"aria-label":a(`restartTerminalTitle`),onOpenChange:e=>{!e&&!k.current&&j(!1)},children:(0,K.jsxs)(`form`,{className:`openpi-dialog`,"aria-busy":M,onSubmit:e=>{e.preventDefault(),L(e.currentTarget.contains(document.activeElement))},children:[(0,K.jsx)(`strong`,{children:a(`restartTerminalTitle`)}),(0,K.jsx)(`p`,{children:a(`restartTerminalDetail`)}),P&&(0,K.jsx)(`p`,{className:`terminal-restart-error`,role:`alert`,children:P}),(0,K.jsxs)(`div`,{className:`dialog-actions`,children:[(0,K.jsx)(`button`,{type:`button`,disabled:M,onClick:()=>{k.current||j(!1)},children:a(`cancel`)}),(0,K.jsx)(`button`,{type:`submit`,className:`danger`,disabled:M,children:a(M?`terminalRestarting`:`restartTerminal`)})]})]})},`${e}:${t}`)]})}function Uq(e){return e.startsWith(`terminal:`)?`terminal`:e}function Wq(e){return e===`launcher`?{tabs:[],active:null,launcherOpen:!0,activationHistory:[]}:{tabs:[e],active:e,launcherOpen:!1,activationHistory:[e]}}function Gq(e,t){return t===`launcher`?{...e,launcherOpen:!0}:{tabs:e.tabs.includes(t)?e.tabs:[...e.tabs,t],active:t,launcherOpen:!1,activationHistory:[...e.activationHistory.filter(e=>e!==t),t]}}function Kq(e,t){return e.tabs.includes(t)?Gq(e,t):e}function qq(e,t){if(!e.tabs.includes(t))return e;let n=e.tabs.filter(e=>e!==t),r=e.activationHistory.filter(e=>e!==t);if(e.active!==t)return{...e,tabs:n,activationHistory:r};let i=r.at(-1),a=e.tabs.indexOf(t),o=n[Math.min(a,n.length-1)],s=i??o??null;return{tabs:n,active:s,launcherOpen:e.launcherOpen||s===null,activationHistory:r}}function Jq(e){return{...e,launcherOpen:e.active===null}}var Yq=[{kind:`side-conversation`,icon:qe,title:`sideConversation`,description:`sideConversationDescription`},{kind:`review`,icon:ye,title:`changeEvidence`,description:`workbarChangesDescription`},{kind:`terminal`,icon:Tt,title:`terminal`,description:`workbarTerminalDescription`},{kind:`browser`,icon:me,title:`browser`,description:`workbarBrowserDescription`},{kind:`files`,icon:G,title:`files`,description:`workbarFilesDescription`}];function Xq({onSelect:e}){let{t}=cr();return(0,K.jsx)(`section`,{className:`workbar-launcher`,"aria-label":t(`openTools`),children:(0,K.jsx)(`div`,{className:`workbar-launcher-list`,children:Yq.map(n=>{let r=n.icon;return(0,K.jsxs)(`button`,{type:`button`,onClick:()=>e(n.kind),children:[(0,K.jsx)(r,{"aria-hidden":`true`}),(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`strong`,{children:t(n.title)}),(0,K.jsx)(`small`,{children:t(n.description)})]}),(0,K.jsx)(ee,{"aria-hidden":`true`})]},n.kind)})})})}function Zq({sessionId:e,cwd:t,snapshot:n,activity:r}){let{t:i}=cr(),a=(0,_.useMemo)(()=>new rf,[]),o=wk(),[s,c]=(0,_.useState)(o?.sideConversation?.selectedId??null),[l,u]=(0,_.useState)(o?.sideConversation?.drafts??{});(0,_.useLayoutEffect)(()=>{o&&(o.sideConversation={selectedId:s,drafts:l})},[o,s,l]);let d=l[s??``]??``,f=(0,_.useRef)(0),[p,m]=(0,_.useState)(null),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(!1),b=(0,_.useRef)(!1),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(0),[E,D]=(0,_.useState)(null),O=(0,_.useRef)(null);(0,_.useEffect)(()=>()=>O.current?.abort(),[]);let A=(r?.items??[]).filter(e=>e.origin===`btw`),j=A.find(e=>e.id===s),M=j?.status??E,N=p?.id===s?p:null,P=n?.models.find(e=>s?`${e.provider}/${e.id}`===N?.model:e.current),F=s?N?.model:P&&`${P.provider}/${P.id}`,I=P?.name||P?.id||F||i(`usageUnknown`),L=!s&&n?.thinking?.supported?n.thinking.level:void 0,R=N?.cwd??t,z=n?.workspaces.find(e=>e.path===R)?.name??QA(R),B=i(s?`continueSideConversation`:`startSideConversation`),V=i(v?`sideConversationPending`:s?`send`:`start`),H=e=>{f.current++,c(e),D(null),S(null),g(null)},te=async t=>{t.preventDefault();let n=d.trim();if(!n||b.current)return;b.current=!0,O.current?.abort();let r=new AbortController,o=f.current,l=s??``;O.current=r,y(!0),S(null);try{let t=await a.subagentAction(e,s?{kind:`subagents`,action:`send-btw`,id:s,text:n}:{kind:`subagents`,action:`spawn-btw`,prompt:n},r.signal);if(r.signal.aborted)return;if(t.sessionId!==e||s&&t.detail.id!==s)throw Error(i(`inspectionChanged`));if(u(e=>e[l]===d?{...e,[l]:``}:e),o!==f.current)return;c(t.detail.id),D(t.detail.status),w(e=>e+1)}catch(e){!r.signal.aborted&&o===f.current&&S(e instanceof Error?e.message:i(`inspectionUnavailable`))}finally{r.signal.aborted||(b.current=!1,y(!1))}},ne=async()=>{if(!s||b.current)return;b.current=!0,O.current?.abort();let t=new AbortController,n=f.current;O.current=t,y(!0),S(null);try{let r=await a.subagentAction(e,{kind:`subagents`,action:`cancel-btw`,id:s},t.signal);if(t.signal.aborted||n!==f.current)return;if(r.sessionId!==e||r.detail.id!==s)throw Error(i(`inspectionChanged`));D(r.detail.status),w(e=>e+1)}catch(e){!t.signal.aborted&&n===f.current&&S(e instanceof Error?e.message:i(`inspectionUnavailable`))}finally{t.signal.aborted||(b.current=!1,y(!1))}};return(0,K.jsxs)(`div`,{className:`side-conversation-body`,children:[s?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`button`,{type:`button`,className:`workbar-back`,onClick:()=>H(null),children:[(0,K.jsx)(T,{"aria-hidden":`true`}),` `,i(`backToSideConversations`)]}),(0,K.jsx)(JI,{sessionId:e,id:s,activity:j,client:a,liveAvailable:!0,refreshRevision:C,fullView:!1,readOnlyNote:!1,onDetail:e=>m({id:e.id,cwd:e.cwd,model:e.model})},`${e}:${s}`)]}):(0,K.jsxs)(`div`,{className:`side-conversation-list`,"data-empty":A.length===0,children:[(0,K.jsxs)(`div`,{className:`side-conversation-intro`,children:[(0,K.jsx)(qe,{"aria-hidden":`true`}),(0,K.jsx)(`h3`,{children:i(`sideConversation`)}),(0,K.jsx)(`p`,{children:i(`sideConversationDescription`)})]}),A.length>0&&(0,K.jsx)(`ul`,{children:A.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsxs)(`button`,{type:`button`,onClick:()=>H(e.id),children:[(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`strong`,{children:e.title||e.id}),(0,K.jsx)(`small`,{children:i(`subagentState_${e.status}`)})]}),(0,K.jsx)(ee,{"aria-hidden":`true`})]})},e.id))})]}),x&&(0,K.jsx)(`p`,{className:`workbar-error`,role:`alert`,children:x}),(0,K.jsx)(`div`,{className:`composer-dock`,children:(0,K.jsxs)(`form`,{className:`composer composer-m02 side-conversation-composer`,onSubmit:te,"aria-busy":v,children:[(0,K.jsx)(`textarea`,{rows:1,value:d,disabled:v,"aria-label":B,placeholder:B,onChange:e=>{let t=e.currentTarget.value;u(e=>({...e,[s??``]:t}))},onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.defaultPrevented&&!e.nativeEvent.isComposing&&e.nativeEvent.keyCode!==229&&(e.preventDefault(),e.currentTarget.form?.requestSubmit())}}),(0,K.jsxs)(`div`,{className:`composer-toolbar`,children:[(0,K.jsxs)(`div`,{className:`composer-toolbar-context`,children:[(0,K.jsx)(`button`,{type:`button`,className:`composer-context-trigger icon-button`,"aria-label":i(`addContext`),title:i(`fileReference`),disabled:v,onClick:()=>g({key:s??``,generation:f.current}),children:(0,K.jsx)(lt,{"aria-hidden":`true`})}),(0,K.jsxs)(`span`,{className:`composer-workspace-label`,title:R,children:[(0,K.jsx)(De,{"aria-hidden":`true`}),` `,z]})]}),(0,K.jsxs)(`div`,{className:`composer-toolbar-controls`,children:[(0,K.jsx)(`div`,{className:`model-picker-wrap`,children:(0,K.jsx)($M,{className:`model-selector model-picker`,label:`${i(`model`)}: ${I}`,isLabelHidden:!0,value:F??``,triggerLabel:(0,K.jsxs)(`span`,{className:`model-thinking-label`,title:F||I,children:[(0,K.jsx)(`span`,{className:`model-picker-label`,children:I}),L&&(0,K.jsx)(`span`,{className:`model-picker-thinking`,children:L[0].toUpperCase()+L.slice(1)})]}),variant:`ghost`,size:`sm`,placement:`above`,alignment:`end`,isDisabled:!F,children:()=>(0,K.jsxs)(`div`,{className:`side-conversation-model-details`,children:[(0,K.jsx)(`strong`,{children:I}),(0,K.jsx)(`code`,{children:F}),(0,K.jsx)(`p`,{children:i(s?`sideConversationModelFixed`:`sideConversationModelInherited`)})]})},s??`new`)}),s&&M===`running`&&(0,K.jsx)(`button`,{type:`button`,className:`send-button`,"aria-label":i(`stop`),title:i(`stop`),disabled:v,onClick:()=>void ne(),children:(0,K.jsx)(Et,{"aria-hidden":`true`})}),(!s||M!==`running`||!!d.trim())&&(0,K.jsx)(`button`,{type:`submit`,className:`send-button`,disabled:v||!d.trim(),"aria-label":V,title:V,children:(0,K.jsx)(k,{"aria-hidden":`true`})})]})]})]})}),(0,K.jsx)(JM,{open:h!==null,sessionId:e,onClose:()=>g(null),onInsert:e=>{if(!h||h.generation!==f.current||h.key!==(s??``)||b.current)return i(`fileReferenceDraftChanged`);let t=h.key;u(n=>({...n,[t]:`${n[t]??``}${n[t]?` +`:``}${YM(e)}`}))}})]})}function Qq({sessionId:e,cwd:t,activity:n,tabId:r,active:i,onConnectionChange:a}){let{t:o}=cr(),s=n?.items??[];return(0,K.jsxs)(`div`,{className:`terminal-workspace`,children:[(0,K.jsx)(Hq,{sessionId:e,cwd:t,tabId:r,active:i,onConnectionChange:a}),s.length>0&&(0,K.jsxs)(`details`,{className:`terminal-agent-activity`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(Tt,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:o(`backgroundTerminalActivity`)}),(0,K.jsx)(`small`,{children:s.length}),(0,K.jsx)(ee,{"aria-hidden":`true`})]}),(0,K.jsx)(`ul`,{children:s.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`strong`,{children:e.title||e.id}),(0,K.jsx)(`small`,{children:o(`execution_${e.status}`,{defaultValue:e.status})})]})},e.id))})]})]})}function $q({visible:e,requestedTool:t,requestRevision:n,sessionId:r,sessionPath:i,cwd:a,snapshot:o,capabilities:s,review:c,reviewInitialFilePath:l,reviewTurn:u,onWorkspaceReview:d,conversationCollapsed:f,onRestoreConversation:p,onExpandReview:m,onClose:h,onActiveToolChange:g,canControl:v=!0,onActivateSession:y,readingState:b,onReferenceLine:x,onBrowserReady:S}){let{t:C}=cr(),w=(0,_.useRef)({}),E=b??w.current;E.terminal&&!E.terminals?.terminal&&((E.terminals??={}).terminal=E.terminal,E.terminal=void 0);let[D,O]=(0,_.useState)(()=>E?.tabs?E.requestRevision===n?E.tabs:Gq(E.tabs,t):Wq(t)),k=JSON.stringify([r,i]),A=(0,_.useRef)(new Map),j=(0,_.useRef)(null),M=(0,_.useRef)(null),N=(0,_.useRef)(null),P=(0,_.useMemo)(()=>new rf,[]),[F,I]=(0,_.useState)({}),[L,R]=(0,_.useState)([]),ee=(0,_.useRef)(new Set),z=(0,_.useRef)(0);(0,_.useEffect)(()=>()=>{z.current++},[]);let[B,V]=(0,_.useState)(null),[H,te]=(0,_.useState)(null),[ne,re]=(0,_.useState)(``),[ie,ae]=(0,_.useState)(()=>Object.fromEntries(Object.entries(E.terminals??{}).flatMap(([e,t])=>t.title?[[e,t.title]]:[]))),U=e=>ie[e]??(e===`terminal`?C(`terminal`):`${C(`terminal`)} ${D.tabs.filter(e=>Uq(e)===`terminal`).indexOf(e)+1}`);(0,_.useLayoutEffect)(()=>{let t=N.current;if(N.current=null,!t||t.scope!==k||!e||(t.tool?D.launcherOpen||D.active!==t.tool:!D.launcherOpen))return;let n=requestAnimationFrame(()=>{let e=t.tool?A.current.get(t.tool):j.current;!e?.isConnected||e.closest(`[hidden], [inert]`)||document.activeElement!==document.body&&!e.closest(`.workbar-panel`)?.contains(document.activeElement)&&!document.getElementById(j.current?.getAttribute(`aria-controls`)??``)?.contains(document.activeElement)||e.focus({preventScroll:!0})});return()=>cancelAnimationFrame(n)},[D,k,e]);let oe=e&&!D.launcherOpen&&D.active===`browser`&&v,[se,ce]=(0,_.useState)(null);(0,_.useLayoutEffect)(()=>{oe?ce(k):(!e||!v||!D.tabs.includes(`browser`)||se!==k)&&ce(null)},[oe,k,e,v,D,se]),(0,_.useLayoutEffect)(()=>{E&&(E.tabs=D,E.requestRevision=n)},[E,D,n]);let le=Nz(r,i,a,u?.promptEntryId),ue=(0,_.useRef)(n);(0,_.useEffect)(()=>(g?.(e?D.launcherOpen?`launcher`:D.active?Uq(D.active):null:null),()=>g?.(null)),[e,D.launcherOpen,D.active,g]),(0,_.useEffect)(()=>{ue.current!==n&&(ue.current=n,O(e=>Gq(e,t)))},[n,t]);let de=e=>{let t=e===`terminal`&&D.tabs.some(e=>Uq(e)===`terminal`)?`terminal:${crypto.randomUUID()}`:e;if(t!==`launcher`&&(N.current={tool:t,scope:k}),t.startsWith(`terminal:`)){let e=Math.max(1,...Object.values(ie).map(e=>Number(e.match(/\s(\d+)$/u)?.[1])||0))+1,n=`${C(`terminal`)} ${e}`;ae(e=>({...e,[t]:n})),(E.terminals??={})[t]={viewport:0,atBottom:!0,title:n}}O(e=>Gq(e,t))},fe=async(e,t)=>{let n=z.current,i=t.contains(document.activeElement);if(Uq(e)===`terminal`&&v){if(ee.current.has(e)||F[e]?.pending)return;let t=F[e]?.id??E.terminals?.[e]?.id;if(t){ee.current.add(e),R(t=>[...t,e]),V(null);try{await P.closeInteractiveTerminal(r,t)}catch(e){n===z.current&&V(e instanceof Error?e.message:C(`terminalError`));return}finally{n===z.current&&(ee.current.delete(e),R(t=>t.filter(t=>t!==e)))}if(n!==z.current)return}}Uq(e)===`terminal`&&E.terminals&&delete E.terminals[e],O(n=>{let r=qq(n,e);return(t.contains(document.activeElement)||i&&document.activeElement===document.body)&&(N.current={tool:r.launcherOpen?null:r.active,scope:k}),r})},pe=D.active?Uq(D.active):null,me=D.launcherOpen?`openTools`:Yq.find(e=>e.kind===pe)?.title??`openTools`;return Ki({isActive:e,onDismiss:()=>{D.launcherOpen&&D.active?(N.current={tool:D.active,scope:k},O(Jq)):h()},getContainer:()=>M.current,isPresent:()=>M.current?.contains(document.activeElement)??!1}),(0,K.jsx)(Ck.Provider,{value:E,children:(0,K.jsx)(Ti,{children:(0,K.jsxs)(`aside`,{ref:M,className:`workbar-panel`,hidden:!e,"aria-label":C(me??`openTools`),children:[(0,K.jsxs)(`header`,{className:`workbar-tabbar`,children:[(0,K.jsxs)(`div`,{className:`workbar-tabs`,role:`toolbar`,"aria-label":C(`openTools`),children:[D.tabs.length===0&&(0,K.jsxs)(`span`,{className:`workbar-tab-placeholder`,children:[(0,K.jsx)(lt,{"aria-hidden":`true`}),` `,C(`openTools`)]}),D.tabs.map(e=>{let t=Uq(e),n=Yq.find(e=>e.kind===t),r=n.icon,i=!D.launcherOpen&&D.active===e,a=t===`terminal`?U(e):C(n.title),o=()=>{t===`terminal`&&(re(a),te(e))};return(0,K.jsxs)(`div`,{className:`workbar-tab`,"data-active":i||void 0,children:[(0,K.jsxs)(`button`,{type:`button`,ref:t=>{t?A.current.set(e,t):A.current.delete(e)},"aria-pressed":i,title:t===`terminal`?`${a} · ${C(`renameTerminal`)}`:a,onDoubleClick:o,onContextMenu:e=>{t===`terminal`&&(e.preventDefault(),o())},onKeyDown:e=>{t===`terminal`&&e.key===`F2`&&(e.preventDefault(),o())},onClick:()=>O(t=>Kq(t,e)),children:[(0,K.jsx)(r,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:a})]}),(0,K.jsx)(`button`,{type:`button`,className:`workbar-tab-close`,"aria-label":t===`terminal`&&v?C(`workbarEndTerminal`,{name:a}):`${C(`close`)} ${a}`,title:t===`terminal`&&v?C(`workbarEndTerminal`,{name:a}):`${C(`close`)} ${a}`,disabled:t===`terminal`&&v&&(L.includes(e)||F[e]?.pending!==!1),onClick:t=>void fe(e,t.currentTarget),children:(0,K.jsx)(Lt,{"aria-hidden":`true`})})]},e)})]}),(0,K.jsxs)(`div`,{className:`workbar-tabbar-actions`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`workbar-back-to-chat`,onClick:()=>{f?p():h(),requestAnimationFrame(()=>document.querySelector(`.composer textarea`)?.focus({preventScroll:!0}))},children:[(0,K.jsx)(T,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:C(`workbarBackToChat`)})]}),!f&&D.active===`review`&&m&&(0,K.jsx)(`button`,{type:`button`,className:`icon-button review-expand`,"aria-label":C(`gitReviewExpand`),title:C(`gitReviewExpand`),onClick:m,children:(0,K.jsx)(nt,{"aria-hidden":`true`,style:{transform:`rotate(180deg)`}})}),D.active?(0,K.jsx)(jA,{className:`workbar-tool-picker`,button:{ref:j,className:`icon-button workbar-add-tab`,icon:(0,K.jsx)(lt,{"aria-hidden":`true`}),label:C(`openTools`),isIconOnly:!0,variant:`ghost`,"aria-label":C(`openTools`),tooltip:C(`openTools`)},onOpenChange:e=>{e||(N.current??={tool:D.active,scope:k},O(Jq))},items:Yq.map(e=>({id:e.kind,icon:(0,K.jsx)(e.icon,{"aria-hidden":`true`}),label:C(e.kind===`terminal`?`workbarNewTerminal`:e.title),description:C(e.description),onClick:()=>de(e.kind)})),menuWidth:`min(300px, calc(100vw - 24px))`,alignment:`end`,hasChevron:!1}):(0,K.jsx)(`button`,{type:`button`,ref:j,className:`icon-button workbar-add-tab`,"aria-label":C(`openTools`),title:C(`openTools`),"aria-pressed":D.launcherOpen,onClick:()=>O(e=>Gq(e,`launcher`)),children:(0,K.jsx)(lt,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{type:`button`,className:`icon-button`,"aria-label":C(`workbarCollapseTools`),title:C(`workbarCollapseTools`),onClick:h,children:(0,K.jsx)(rt,{"aria-hidden":`true`})})]})]}),B&&(0,K.jsx)(`p`,{className:`error`,role:`alert`,children:B}),(0,K.jsxs)(`div`,{className:`workbar-panels`,children:[(0,K.jsx)(`div`,{className:`workbar-tool-panel`,hidden:!D.launcherOpen,children:(0,K.jsx)(Xq,{onSelect:de})}),D.tabs.map(t=>{let n=Uq(t);return(0,K.jsx)(`div`,{className:`workbar-tool-panel`,"data-tool":n,"data-tab":t,hidden:D.launcherOpen||D.active!==t,inert:D.launcherOpen||D.active!==t||!e,children:n===`terminal`&&e&&v?(0,K.jsx)(Qq,{sessionId:r,cwd:a,tabId:t,active:!D.launcherOpen&&D.active===t,onConnectionChange:e=>I(n=>({...n,[t]:e})),activity:s[`background-terminals`]}):n===`browser`&&e&&v&&(oe||se===k)?(0,K.jsx)(Lz,{onReady:S},k):e&&!D.launcherOpen&&D.active===t?!v&&[`side-conversation`,`terminal`,`browser`].includes(n)?(0,K.jsxs)(`div`,{className:`workbar-empty`,children:[(0,K.jsx)(`p`,{children:C(`toolsRequireCurrentSession`)}),y&&(0,K.jsx)(`button`,{type:`button`,className:`secondary`,onClick:y,children:C(`activateViewedSession`)})]}):n===`side-conversation`?(0,K.jsx)(Zq,{sessionId:r,cwd:a,snapshot:o,activity:s.subagents}):n===`review`?(0,K.jsx)(Mz,{review:u?{...le,setSource:e=>{c.setSource?.(e),d?.()}}:c,initialFilePath:u?.filePath??l,readingScope:u?`turn:${u.promptEntryId}:${u.revision}`:`workspace:${c.source??`unstaged`}`,onOpenFiles:()=>de(`files`),onReferenceLine:v?x:void 0,onClose:()=>O(e=>qq(e,`review`)),embedded:!0},u?`${u.promptEntryId}:${u.revision}`:c.source??`workspace`):(0,K.jsx)(nz,{sessionId:r,sessionPath:i,cwd:a,active:!0,canWrite:v},JSON.stringify([r,i,a])):null},t)})]}),(0,K.jsx)($j,{isOpen:H!==null,purpose:`form`,"aria-label":C(`renameTerminal`),onOpenChange:e=>{e||te(null)},children:(0,K.jsxs)(`form`,{className:`openpi-dialog`,onSubmit:e=>{e.preventDefault();let t=ne.trim();if(!H||!t)return;ae(e=>({...e,[H]:t}));let n=(E.terminals??={})[H];E.terminals[H]={...n??{viewport:0,atBottom:!0},title:t},te(null)},children:[(0,K.jsx)(`strong`,{children:C(`renameTerminal`)}),(0,K.jsx)(`input`,{"aria-label":C(`terminalName`),value:ne,maxLength:80,onChange:e=>re(e.target.value)}),(0,K.jsxs)(`div`,{className:`dialog-actions`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:()=>te(null),children:C(`cancel`)}),(0,K.jsx)(`button`,{type:`submit`,disabled:!ne.trim(),children:C(`save`)})]})]})})]})})})}var eJ=`openpi:workbar-positions:v1`;function tJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nJ(e,t=4096){return typeof e==`string`&&e.length<=t?e:``}function rJ(e,t=0,n=0,r=5e7){return typeof e==`number`&&Number.isFinite(e)&&e>=n&&e<=r?e:t}function iJ(e,t=100){return Array.isArray(e)?e.slice(0,t).filter(e=>typeof e==`string`&&e.length<=4096):[]}function aJ(e){return YR(nJ(e),window.location.origin)}function oJ(e){return typeof e==`string`&&([`files`,`review`,`browser`,`terminal`,`side-conversation`].includes(e)||/^terminal:[a-zA-Z0-9-]{1,128}$/u.test(e))}function sJ(e){return typeof e==`string`&&[`launcher`,`files`,`review`,`browser`,`terminal`,`side-conversation`].includes(e)}function cJ(e){let t={};if(!tJ(e))return t;if(tJ(e.tabs)){let n=Array.isArray(e.tabs.tabs)?[...new Set(e.tabs.tabs.filter(oJ))].slice(0,16):[],r=oJ(e.tabs.active)&&n.includes(e.tabs.active)?e.tabs.active:null;t.tabs={tabs:n,active:r,launcherOpen:e.tabs.launcherOpen===!0||r===null,activationHistory:Array.isArray(e.tabs.activationHistory)?[...new Set(e.tabs.activationHistory.filter(oJ).filter(e=>n.includes(e)))].slice(-16):[]},t.requestRevision=rJ(e.requestRevision)}if(tJ(e.files)&&(t.files={selected:nJ(e.files.selected),treeVisible:e.files.treeVisible!==!1,query:nJ(e.files.query,200),expanded:iJ(e.files.expanded),treeScroll:rJ(e.files.treeScroll)}),tJ(e.artifact)){t.artifact={reference:nJ(e.artifact.reference),source:e.artifact.source===!0,editing:!1,scroll:rJ(e.artifact.scroll)};let n=e.artifact.document;tJ(n)&&typeof n.revision==`string`&&/^[a-f0-9]{64}$/u.test(n.revision)&&(t.artifact.document={path:nJ(n.path),revision:n.revision,page:Math.floor(rJ(n.page,1,1,1e5)),...typeof n.scale==`number`?{scale:rJ(n.scale,1,.1,8)}:{}})}let n=e.review;tJ(n)&&(n.source===`unstaged`||n.source===`staged`||n.source===`branch`||n.source===`session`)&&(t.review={scope:nJ(n.scope),source:n.source,...typeof n.baseRef==`string`?{baseRef:nJ(n.baseRef,1024)}:{},selected:typeof n.selected==`string`?nJ(n.selected):null,query:nJ(n.query,200),collapsedDirectories:iJ(n.collapsedDirectories),visibleFiles:rJ(n.visibleFiles,50,0,200),listScroll:rJ(n.listScroll),previewScroll:rJ(n.previewScroll)},tJ(n.viewed)&&typeof n.viewed.revision==`string`&&(t.review.viewed={revision:nJ(n.viewed.revision,128),paths:iJ(n.viewed.paths,200)}));let r=e.browser;if(tJ(r)&&Array.isArray(r.tabs)){let e=new Set,n=r.tabs.flatMap(t=>{if(!tJ(t)||!Number.isSafeInteger(t.id)||typeof t.id!=`number`||t.id<0||t.id>5e7||e.has(t.id))return[];e.add(t.id);let n=aJ(t.initialUrl);return[{id:t.id,title:nJ(t.title,200),...n?{initialUrl:n}:{}}]}).slice(0,8),i={};for(let e of n){let t=tJ(r.pages)?r.pages[e.id]:void 0;if(!tJ(t))continue;let n=iJ(t.history,32).flatMap(e=>aJ(e)??[]);i[e.id]={draft:aJ(t.draft)??``,history:n,index:n.length?Math.min(Math.floor(rJ(t.index)),n.length-1):-1}}t.browser={tabs:n,selected:n.some(e=>e.id===r.selected)?Number(r.selected):n[0]?.id??0,pages:i}}if(tJ(e.terminals)){t.terminals={};for(let[n,r]of Object.entries(e.terminals).slice(0,16))!oJ(n)||n!==`terminal`&&!n.startsWith(`terminal:`)||!t.tabs?.tabs.includes(n)||!tJ(r)||(t.terminals[n]={...typeof r.id==`string`?{id:nJ(r.id,128)}:{},...typeof r.title==`string`?{title:nJ(r.title,80)}:{},viewport:rJ(r.viewport),atBottom:r.atBottom!==!1})}return tJ(e.terminal)&&typeof e.terminal.id==`string`&&(t.terminal={id:nJ(e.terminal.id,128),viewport:rJ(e.terminal.viewport),atBottom:e.terminal.atBottom!==!1}),tJ(e.sideConversation)&&(t.sideConversation={selectedId:typeof e.sideConversation.selectedId==`string`?nJ(e.sideConversation.selectedId,128):null,drafts:{}}),t}function lJ(e){if(!tJ(e)||!nJ(e.sessionId,128)||!nJ(e.sessionPath)||!sJ(e.tool))return null;let t={sessionId:nJ(e.sessionId,128),sessionPath:nJ(e.sessionPath),tool:e.tool,open:e.open===!0,requestRevision:rJ(e.requestRevision),reading:cJ(e.reading)};return tJ(e.reviewTurn)&&nJ(e.reviewTurn.promptEntryId,512)&&(t.reviewTurn={promptEntryId:nJ(e.reviewTurn.promptEntryId,512),revision:rJ(e.reviewTurn.revision),...typeof e.reviewTurn.filePath==`string`?{filePath:nJ(e.reviewTurn.filePath)}:{}}),t}function uJ(){try{let e=localStorage.getItem(eJ);if(!e||e.length>256e3)return[];let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=new Map;for(let e of t.slice(-32)){let t=lJ(e);t&&n.set(JSON.stringify([t.sessionId,t.sessionPath]),t)}return[...n.values()]}catch{return[]}}function dJ(e){try{let t=e.slice(-32).flatMap(e=>lJ(e)??[]),n=JSON.stringify(t);for(;n.length>256e3&&t.length;)t.shift(),n=JSON.stringify(t);localStorage.setItem(eJ,n)}catch{}}function fJ(e,t,n){if([`session_start`,`session_switched`,`session_created`].includes(t))return e.length===0?e:[];if([`agent_settled`,`turn_settled`].includes(t))return e.some(e=>e.state===`running`)?e.map(e=>e.state===`running`?{...e,state:`unknown`}:e):e;if(!t.startsWith(`tool_execution_`))return e;let r=n.toolCallId;if(typeof r!=`string`||r.length>500)return e;let i=e.find(e=>e.call.id===r);if(i&&i.state!==`running`&&(i.state!==`unknown`||t!==`tool_execution_end`))return e;let a=Pd(n.call),o=a.type===`toolCall`&&typeof a.name==`string`&&typeof a.arguments==`string`?a:i?.call;if(!o||o.evidenceTruncated&&o.id?.includes(`[truncated]`))return e;let s=Pd(n.result),c=typeof s.content==`string`?s:i?.result,l=typeof n.parentToolCallId==`string`&&n.parentToolCallId.length<=500?n.parentToolCallId:i?.parentToolCallId,u={call:o,result:c,...l?{parentToolCallId:l}:{},state:t===`tool_execution_end`?n.isError===!0?`failed`:`returned`:`running`},d=(i?e.map(e=>e.call.id===r?u:e):[...e,u]).slice(-32);for(;d.length>0&&new TextEncoder().encode(JSON.stringify(d)).byteLength>524288;)d.shift();return d}var pJ={en:{translation:{promptPending:`Processing your request…`,commandFeedbackTruncated:`This is a limited command preview. Narrow the query or run it in the TUI for the full output.`,planMode_inactive:`Normal mode`,planMode_planning:`Planning · writes blocked`,planMode_ready:`Plan ready · awaiting review`,planMode_invalid:`Plan state invalid · writes blocked`,planModeEnter:`Plan`,promptPlanMessage:`This conversation uses Plan mode · discuss the plan; no implementation yet`,planModeUnconfirmed:`Could not confirm Plan mode. Refresh before continuing.`,planModeExit:`Exit planning`,planModeImplement:`Prepare implementation prompt`,planImplementationReplaceDraft:`Preparing this plan will replace the current draft and turn off Plan mode. The prompt will not be sent. Continue?`,commandSupport_plan:`Planning and same-session implementation prompts are available. Starting a fresh implementation session still requires the TUI.`,commandSupport_setup:`Configuration uses the active model; questions are answered in Web.`,handoffWaiting:`Manual action`,handoffDone:`Done`,handoffUnable:`Unable to complete`,handoffDoneHelp:`I performed the action. The agent still needs to verify it.`,handoffUnableHelp:`I could not finish. I can add a note about the blocker.`,handoffReview:`Review status`,handoffSubmit:`Submit status`,handoffSignal:`Expected result:`,handoffVerify:`Reporting Done lets the agent continue and verify; it is not proof of success.`,planCardLabel:`Development plan`,planCardReady:`Plan ready`,planCardResult:`Plan result`,planCardNotApproval:`This step produced a plan. It did not approve or start implementation.`,planCardCollapse:`Collapse`,planCardExpand:`Expand`,planCardCopy:`Copy plan`,planCardCopyPreview:`Copy visible preview`,planCardTruncated:`Only a bounded preview is displayed.`,planCardLoadFull:`Load full plan`,planCardLoadingFull:`Loading plan...`,planCardLoadFailed:`Could not load the full plan. Retry`,planCardEvidence:`Tool result · plan_ready`,questionWaiting:`Question`,questionPreview:`View preview`,questionSkip:`Skip`,questionProgress:`{{current}} of {{total}}`,questionReview:`Review answers`,questionReviewTitle:`Ready to send?`,questionReviewHelp:`Review your choices. Nothing is sent until you submit.`,questionEdit:`Edit answer: {{question}}`,questionDismiss:`Dismiss questions without answering`,questionCustom:`Or write your own reply`,questionCustomHelp:`Or leave it blank to ask for a clearer question.`,questionYourAnswer:`Your answer`,questionCustomPlaceholder:`Describe what you have in mind…`,questionNotes:`Additional context (optional)`,questionNotesPlaceholder:`Add a constraint or clarify your choice…`,questionRephrase:`Ask for a clearer or smaller question`,questionBack:`Back`,questionNext:`Next question`,questionSubmit:`Submit answers`,questionSubmitting:`Sending…`,questionRetry:`Check submission`,questionUncertain:`We could not confirm delivery. Your submitted answers are kept here. Check submission to recover the result without sending them twice.`,questionDisconnected:`Reconnecting… Your choices stay here; submitting is paused.`,questionLimit:`Keep each answer or note within {{count}} UTF-8 bytes.`,questionLoadFailed:`Could not check for questions awaiting your answer.`,questionDraftLimit:`Question drafts are full. Shorten or clear an existing answer before adding more text.`,questionRetryLoad:`Try again`,questionCloseReceipt:`Close question status`,questionState_dismissed:`Questions dismissed. No answers were submitted.`,questionState_cancelled:`Questions cancelled. No answers were submitted.`,questionState_expired:`Questions expired. No answers were submitted.`,questionState_stale:`This request is no longer active. Check the conversation for its result.`,conversationView:`Conversation view`,jumpToLatest:`Jump to latest`,historyLoading:`Loading history…`,historyOmitted:`{{count}} earlier entries · Scroll up to load automatically`,historyChanged:`The Session branch changed. History has been reset to the current branch.`,historyUnavailable:`Could not load history. Please retry.`,historyValidationUnavailable:`Could not verify the conversation history. Please retry.`,historyVerifying:`Checking conversation history…`,messageLoadFull:`Load full message`,messageLoadMore:`Load more`,messageLoadingFull:`Loading message…`,messageLoadFailed:`Could not load this message. Retry`,filePreview:`File preview`,changeEvidence:`Changes`,changeEvidenceScope:`Read-only Git snapshot of changes since this session started.`,turnLabel:`Turn {{number}}`,turnState_running:`Running`,turnState_complete:`Completed`,turnState_failed:`Failed`,turnState_interrupted:`Interrupted`,turnState_waiting:`Waiting for response`,turnState_forked:`Forked · Ready to continue`,turnChanges_one:`{{count}} file changed during this turn`,turnChanges_other:`{{count}} files changed during this turn`,turnChangesPartial:`At least {{count}} files changed during this turn`,turnChangesIncomplete:`This turn's change record is incomplete.`,turnChangesMore:`Show {{count}} more files`,turnChangesLess:`Show fewer files`,turnChangesReview:`Review turn changes`,turnChangesReviewButton:`Review`,turnChangesBack:`Back to turn changes`,turnChangesLoading:`Loading this turn's changes…`,turnChangesUnavailable:`This turn's saved diff is unavailable.`,messageCopyRequiresFull:`Load the full message before copying.`,filesChanged_one:`{{count}} file changed`,filesChanged_other:`{{count}} files changed`,reviewChanges:`Review changes`,workspaceChanges:`Workspace changes`,overviewChanges:`Changes`,overviewLineTotals:`Text lines added and removed across the current Git comparison`,overviewPartialTotals:`Known line counts only; some files could not be counted. Open Changes for details.`,overviewCounting:`Counting…`,overviewCountsUnknown:`Counts unavailable`,overviewReviewUnavailable:`Unavailable`,sessionSources:`Sources`,sourcesAdd:`Add source`,sourcesEmpty:`No sources yet`,sourcesFailed:`Could not load sources.`,sourcesViewAll:`View all`,sourcesLoadMore:`Load more sources`,sourcesBack:`Back to sources`,sourcesPartial:`This list has reached its display limit. Earlier sources remain in the conversation.`,turnChangesScope:`Saved workspace changes during this turn`,turnEdits_one:`Edited {{count}} file`,turnEdits_other:`Edited {{count}} files`,turnEditsPartial:`Recorded edits to {{count}} files`,turnEditsScope:`This turn's recorded file-tool writes · saved; shell and external edits are not included`,turnEditStatsUnknown:`Line counts unavailable`,turnEditReason_before_unavailable:`The write completed, but previous contents were not authorized for reading. A before/after diff is unavailable.`,turnEditReason_content_limit:`The write completed. Content exceeds the saved comparison limit, so exact line counts are unavailable.`,turnEditReason_concurrent_change:`The file changed between recorded operations. A reliable net diff for this turn is unavailable.`,gitReviewLoadedCount:`{{count}} files loaded`,gitReviewPartialLabel:`Partial`,gitReviewSearch:`Search file paths`,gitReviewExpand:`Expand review`,gitReviewSearchLoaded:`Search loaded files`,gitReviewMarkViewed:`Mark {{path}} as viewed`,gitReviewMarkCurrentViewed:`Mark current file {{path}} as viewed`,gitReviewViewedLabel:`Viewed`,gitReviewViewedProgress:`Viewed {{viewed}} / {{loaded}} loaded files`,gitReviewViewedLimit:`Up to {{count}} viewed marks are remembered for this comparison.`,gitReviewNoMatch:`No matching files.`,gitReviewNoLoadedMatch:`No matches in the loaded files.`,gitReviewLoadNext:`Load the next files`,gitReviewChanged:`The workspace changed. Refresh the list before loading more.`,gitReviewNewVersion:`New changes are available. You are reading the previous version.`,gitReviewShowLatest:`Show latest diff`,gitReviewBinary:`No text diff is available for this binary file.`,gitReviewBinaryShort:`Binary`,gitReviewPendingStats:`Not loaded`,gitReviewComparison:`{{current}} compared with {{base}}`,gitReviewWorkingTree:`Working tree compared with HEAD`,gitReviewSessionSnapshot:`Changes since this session started`,gitReviewDetached:`Detached HEAD`,gitReviewLoading:`Reading Git changes…`,gitReviewRetry:`Retry`,gitReviewRefresh:`Refresh changes`,gitReviewOlderResult:`Showing the previous result.`,gitReviewNotRepository:`This workspace is not a Git repository.`,gitReviewUnborn:`This repository has no readable HEAD yet.`,gitReviewFailed:`Git changes could not be read.`,gitReviewTruncated:`The change snapshot reached its file or diff size limit.`,gitReviewEmpty:`No changes in this comparison.`,gitReviewHiddenLines:`{{count}} more diff lines hidden.`,gitReviewDiffTruncated:`This file's diff was not loaded because the snapshot reached its size limit.`,gitReviewShowMore:`Show {{count}} more files`,gitReviewBackToFiles:`Back to changed files`,gitReviewFilePreview:`Diff for {{file}}`,gitReviewNoDiff:`No text diff is available for this file.`,changeDiff:`Change diff`,diffView:`Diff`,gitFileStatus_added:`Added`,gitFileStatus_modified:`Modified`,gitFileStatus_deleted:`Deleted`,gitFileStatus_renamed:`Renamed`,gitFileStatus_copied:`Copied`,gitFileStatus_untracked:`Untracked`,gitFileStatus_unknown:`Changed`,closePreview:`Close preview`,artifactReadOnly:`Read-only`,artifactReferenceUnavailable:`File preview is unavailable in this view: {{path}}`,artifactSession:`Session {{sessionId}}`,copyFilePath:`Copy file path`,filePathCopied:`File path copied`,refreshFile:`Refresh file`,downloadFile:`Download file`,downloadingFile:`Downloading…`,artifactOlderPreview:`Showing an older preview. `,readingFile:`Reading file…`,artifactVersion:`Version`,artifactBytes:`{{count}} bytes`,artifactPreviewTruncated:`Preview truncated. Download the file for the complete content.`,artifactUnsupported:`This file type cannot be previewed. Use Download.`,chatView:`Chat`,trajectory:`Trajectory`,trajectoryScope:`Recorded Session messages in order, not execution durations or the complete model request.`,trajectoryRunning:`Work is active. This view updates as saved records arrive; in-flight text is available in Chat.`,trajectoryTruncated:`Loaded history is partial: {{entries}} entries omitted, {{parts}} parts omitted, {{messages}} messages truncated.`,trajectoryEmpty:`No saved records yet.`,trajectoryOrder:`Record order`,trajectoryRecordCount:`{{count}} records`,trajectoryMatches:`{{count}} matches`,trajectorySearch:`Search loaded records`,trajectoryNoMatches:`No matching records.`,trajectoryEarlierGroup:`Earlier context`,trajectoryEventCount:`{{count}} Session changes`,trajectorySummary:`Overview`,trajectoryInputTab:`Input`,trajectoryResultTab:`Result`,trajectoryConversationGroup:`Conversation`,trajectoryReasoningTitle:`Thinking`,trajectoryRecordNumber:`Record {{number}}`,trajectoryRecordInfo:`Record information`,trajectoryRecordId:`Record ID`,trajectoryCallId:`Tool call ID`,trajectoryEventType:`Event type`,trajectoryEvent_model_change:`Model changed`,trajectoryEvent_thinking_level_change:`Thinking level changed`,trajectoryEvent_compaction:`Context compacted`,trajectoryEvent_session_info:`Session information updated`,trajectoryEvent_custom:`Session record`,trajectoryEarlier:`Show earlier records ({{count}} remaining in loaded history)`,trajectoryDetails:`Record details`,trajectoryRecordedAt:`Record timestamp`,trajectoryEvidenceTruncated:`This evidence was truncated in the Session projection.`,trajectoryArguments:`Tool arguments`,trajectoryRecordedContent:`Recorded content`,trajectoryThinking:`Recorded model reasoning`,trajectoryOutput:`Tool result`,trajectoryMissingResult:`No unambiguous result is included in the loaded records. This does not imply the tool is still running.`,trajectoryStructured:`Structured result`,trajectoryEventOnly:`Only this event’s type and timestamp are available.`,trajectory_user:`User message`,trajectory_assistant:`Assistant`,trajectory_call:`Tool call`,trajectory_result:`Unpaired result`,trajectory_event:`Session event`,trajectory_returned:`Tool returned a result.`,trajectory_error:`Tool returned an error`,trajectory_unknown:`Outcome not established`,runtimeStatus:`Runtime status`,refreshStatus:`Refresh status`,terminalDetails:`Terminal details`,openTools:`Open tools`,sideConversation:`Side conversation`,sideConversationDescription:`Ask a focused question in a separate Pi session without interrupting the main task.`,workbarChangesDescription:`Inspect the current Git branch and working tree.`,terminal:`Terminal`,renameTerminal:`Rename terminal`,terminalName:`Terminal name`,workbarTerminalDescription:`Open an interactive shell for the current workspace.`,backgroundTerminalActivity:`Agent command activity`,restartTerminal:`Restart terminal`,reconnectTerminal:`Reconnect terminal`,restartTerminalTitle:`Restart this terminal?`,restartTerminalDetail:`The current terminal will be closed. Running processes may be interrupted.`,terminalReconnecting:`Reconnecting terminal...`,terminalScrollToBottom:`Scroll to bottom`,terminalOutputResynced:`Terminal output resynchronized.`,terminalRestarting:`Restarting terminal...`,terminalConnecting:`Starting terminal…`,terminalExited:`Terminal exited.`,terminalExitCode:`Terminal exited with code {{code}}.`,terminalDisconnected:`Terminal connection ended unexpectedly.`,terminalError:`Terminal unavailable.`,browser:`Browser`,sessionFileRecords:`Session file records`,gitReviewSource:`Changes`,gitReviewBaseBranch:`Compare against branch`,gitReviewChooseBase:`Choose comparison branch`,gitReviewSearchBranches:`Search branches`,gitReviewLocalBranch:`Local branch`,gitReviewRemoteBranch:`Remote branch`,gitReviewBranchesTruncated:`Showing a bounded list of branches. Some branches are omitted.`,gitReviewNoMatchingBranches:`No matching branches.`,gitReviewBaseUnavailable:`No default comparison branch is available. Choose a branch to review committed changes.`,gitReviewBaseInvalid:`The selected comparison branch is unavailable. Choose another branch.`,gitReviewUnstaged:`Unstaged changes`,gitReviewStaged:`Staged changes`,gitReviewBranch:`Branch changes`,gitReviewFileMissing:`This file no longer has changes in this view. Refresh the file list.`,artifactExternalAccess:`This file is in another working directory. You can authorize read-only access to this file for this session; other files remain inaccessible.`,artifactAuthorizeFile:`Open this file read-only`,sideConversationPending:`Preparing side conversation…`,resizeSidebar:`Resize sidebar`,resizePanes:`Resize panes`,resizeWorkbar:`Resize workbar`,browserPasteTooLarge:`Paste at most {{count}} characters at a time.`,browserInputTooLarge:`Enter at most {{count}} characters at a time.`,browserInputTargetChanged:`The input target changed or could not be confirmed. An input operation was not executed.`,workbarBrowserDescription:`Open and interact with a page inside the OpenPI workbar.`,browserReady:`Enter an address to start browsing`,browserStarting:`Starting the embedded browser…`,browserOpened:`Opened in the embedded browser`,browserOpenAgain:`Open again`,browserOpenFailed:`The embedded browser is unavailable.`,browserBack:`Back`,browserForward:`Forward`,browserReload:`Reload`,browserTabs:`Browser tabs`,browserNewTab:`New tab`,browserAddTab:`New browser tab`,browserCloseTab:`Close {{title}}`,browserTabLimit:`Up to {{count}} browser tabs`,browserPageTitle:`Web page: {{address}}`,browserEnteredAddress:`Last address opened from this toolbar`,browserAddressNotAllowed:`Enter an HTTP(S) address without embedded credentials, outside this application's origin.`,browserLocationUnknown:`This page navigated. Its new address is unavailable. Reload returns to the address you entered.`,browserDirectDescription:`Browse pages directly. Sites that refuse embedding can be opened in your external browser.`,browserDirectHint:`The address records toolbar navigation only. Page popups open in your external browser. Blank page? Use Open in external browser.`,browserEnhancedHint:`Browser enhancement is on: addresses sync and ordinary popup links open in these tabs. Some site policies, login popups and cross-site history still require an external browser.`,files:`Files`,filesExplorer:`Workspace files`,filesSearch:`Filter files…`,refreshFiles:`Refresh files`,filesWorkspaceActions:`Workspace file actions`,filesCreateMenu:`New`,filesImportMenu:`Import`,filesMoreMenu:`More`,filesNewFile:`New file`,filesNewDirectory:`New folder`,filesImport:`Import files`,filesImportFolder:`Import folder`,filesImportFolderChoose:`Choose a folder to import`,filesImportFolderLimit:`Import up to 2,000 files and folders at a time, with at most 64 nested levels.`,filesSelectMultiple:`Select multiple files`,filesSelectItem:`Select {{name}}`,filesSelectedCount:`{{count}} selected`,filesRename:`Rename`,filesNewName:`New name`,filesMove:`Move`,filesMoveDestination:`Destination folder (workspace relative path)`,filesTrashAction:`Move to trash`,filesTrash:`Workspace trash`,filesTrashDetail:`Removed files stay in this workspace and can be restored. Existing names are preserved.`,filesTrashEmpty:`No removed files`,filesTrashUnavailable:`{{count}} entries could not be verified. Their contents remain in .openpi-trash; automatic restore is unavailable.`,filesRestore:`Restore`,filesRestoreItem:`Restore {{name}}`,filesUndoTrash:`Undo removal`,filesOrganizationResults:`File operation results`,filesOperationDone:`Done`,filesRefreshBeforeOrganizing:`Refresh the file tree before organizing this item.`,filesImportChoose:`Choose files to import`,filesTargetDirectory:`Destination`,filesWorkspaceRoot:`Workspace root`,filesFileName:`File name`,filesDirectoryName:`Folder name`,filesCreate:`Create`,filesCreating:`Creating…`,filesCreated:`Created: {{path}}`,filesNameInvalid:`Enter one file or folder name without path separators.`,filesNameExists:`This name already exists. Choose a different name; the existing file was preserved.`,filesMutationFailed:`Could not write this file. Your input is preserved.`,filesWriteUnavailable:`Switch to this session to write workspace files.`,filesImportLimit:`Each file can be up to 50 MiB. Existing names are never overwritten.`,filesImportTooLarge:`This file exceeds the 50 MiB import limit.`,filesImportDirectoryUnsupported:`Folders cannot be imported. Choose the files inside the folder.`,filesImportResults:`File import results`,filesImportPending:`Waiting to import`,filesImporting:`Importing…`,filesImported:`Saved to the workspace`,filesImportedNoPreview:`Saved. Preview supports up to 20 MiB; copy the path to use this file in chat.`,filesClearImported:`Clear completed imports`,filesRetryImport:`Retry import`,filesPathActions:`Path actions for {{name}}`,filesCopyRelativePath:`Copy relative path`,filesCopyAbsolutePath:`Copy absolute path`,filesPathCopied:`Copied path: {{path}}`,filesReadFailed:`Unable to read files.`,filesSymlink:`Symbolic link — not followed by the file browser`,filesTruncated:`The result is incomplete. Refine your search.`,filesNoMatches:`No matching files`,filesEmpty:`This folder is empty`,filesChoose:`Choose a file to preview`,filesChooseDetail:`Browse your workspace on the right. Files open here, keeping the explorer in place.`,filesHideTree:`Hide file tree`,filesShowTree:`Show file tree`,filesPreview:`Preview`,filesSource:`View source`,filesEdit:`Edit`,filesMode:`File view`,filesEditor:`File editor`,filesSave:`Save file`,filesSaving:`Saving…`,filesSaved:`Saved`,filesUnsaved:`Unsaved changes · draft kept in this window`,filesDiscard:`Discard draft`,filesDiscardConfirm:`Discard your unsaved changes to this file?`,filesSaveConflict:`The file changed on disk. Your draft is preserved. Refresh to inspect the current version, then reconcile your changes before saving.`,filesSaveFailed:`Could not save. Your draft is preserved; check the file and retry.`,filesEditLoadFirst:`Continue reading the complete file before editing.`,filesEditUnavailable:`Editing supports workspace UTF-8 text files up to 1 MiB. At most 16 unsaved drafts can be kept.`,filesOutline:`Document outline`,filesDiskVersion:`Inspect current disk version`,filesReconcile:`Reviewed · continue editing my draft against this version`,filesTable:`Table preview`,filesRow:`Row`,filesSheets:`Worksheets`,filesTableTruncated:`Showing a bounded table preview. Download the file for all rows and columns.`,filesOfficeLayout:`Document content preview; pagination and typography may differ from Office.`,filesSlidesLayout:`Slide text and images; themes, charts and animations may differ from PowerPoint.`,filesPreviousPage:`Previous page`,filesNextPage:`Next page`,filesZoomOut:`Zoom out`,filesZoomIn:`Zoom in`,filesZoomReset:`Reset zoom`,filesPdfPage:`Page {{page}}`,filesDocumentLimit:`This document exceeds the preview limit. Download it to open locally.`,filesPreviewFailed:`Unable to preview this file. You can still download it.`,filesDiagram:`Mermaid diagram`,filesExpandDiagram:`Expand diagram`,filesFitImage:`Fit`,filesOriginalImage:`Original size`,filesLoadMore:`Load more`,filesLoaded:`{{count}} items loaded`,filesReadMore:`Continue reading`,filesContentChanged:`The file changed. Refresh when ready; your current reading position is preserved.`,workbarFilesDescription:`Browse workspace files with an inline preview and file tree.`,backToSideConversations:`Back to side conversations`,continueSideConversation:`Send a follow-up…`,startSideConversation:`Ask a side question…`,sideConversationModelInherited:`New side conversations use the main conversation’s model and thinking level.`,sideConversationModelFixed:`This is the model used by this side conversation.`,stop:`Stop`,start:`Start`,browserAddress:`Browser address`,browserGo:`Open address`,openExternalBrowser:`Open in external browser`,invalidBrowserAddress:`Enter a valid HTTP or HTTPS address.`,addImages:`Add images`,addFiles:`Add files`,fileAttachments:`File attachments`,previewFileAttachment:`Preview file`,fileAttachmentDescription:`Documents, spreadsheets, PDFs, text, code, and other files`,fileAttachmentCount:`Attach up to {{count}} items.`,fileAttachmentTooLarge:`Files must total 50 MB or less.`,fileAttachmentReadFailed:`Could not read this file. Check the format or whether it is password protected.`,fileAttachmentTextReady:`Text ready`,fileAttachmentTextTruncated:`Partial text · original retained`,fileAttachmentOriginalReady:`Original file ready`,fileAttachmentExtractionFailed:`Text unavailable · original retained`,fileAttachmentEncodingUnavailable:`The text encoding could not be read. The original bytes are preserved.`,fileAttachmentDocumentUnavailable:`Text could not be extracted. The document may be password protected or have an unsupported format. The original bytes are preserved.`,fileAttachmentNoText:`The original file will be attached for the agent to read with its tools. No text was extracted.`,fileAttachmentPreviewTruncated:`Preview shows the first 20,000 characters. The complete extracted text will be attached.`,fileAttachmentExtractedContent:`Extracted text`,fileAttachmentPromptLabel:`User-provided files:`,fileAttachmentPromptTooLong:`The message and file references exceed the input limit. Shorten the message or attach fewer files.`,imageAttachmentDescription:`PNG, JPEG, GIF, or WebP`,imageAttachments:`Image attachments`,imageAttachmentsLoading:`Preparing attachments…`,commandOpensPanel:`Open panel`,commandPanelArguments:`This command opens a panel and cannot include arguments or images. Remove them, or use the panel directly.`,commandPanelUnavailable:`The panel could not be opened. Your command is preserved.`,commandUnavailable_terminal_only:`Requires Pi's terminal interface.`,commandUnavailable_not_integrated:`This extension command is not connected to Web yet. Use it in Pi's terminal.`,artifactImagePreviewFailed:`Unable to preview this image. Refresh the file to retry, or download it.`,artifactFileDetails:`File details`,turnElapsedRunning:`Working for {{duration}}`,compactionElapsed:`Waiting {{duration}}`,compactionRunning:`Compacting context`,compactionCompleted:`Context automatically compacted`,compactionFailed:`Context compaction failed`,compactionInterrupted:`Compaction interrupted`,compactionUnchanged:`Compaction finished without a new summary`,compactionUnavailable:`Context compaction status unavailable`,compactionReconnectHelp:`Connection interrupted. The current status will be checked after reconnecting.`,compactionDraftHelp:`Compacting history. Messages you send will be queued.`,turnElapsedFinished:`Worked for {{duration}}`,composerAdd:`Add`,composerCommands:`Commands`,composerFile:`File`,composerGoal:`Goal`,composerPlan:`Plan`,composerCompact:`Compact`,composerModel:`Model`,composerBack:`Back`,composerGoalDescription:`Set or view a long-running goal`,composerPlanDescription:`Enter or leave Plan mode`,composerCompactDescription:`Summarize earlier conversation history`,composerModelDescription:`Select this Session's model`,compactionQueueWaiting:`Waiting for compaction to finish`,compactionQueueBlocked:`Messages retained. Retry when ready or clear the queue.`,clearPromptQueue:`Clear queue`,turnElapsedOutcome_cancelled:`Stopped`,turnElapsedOutcome_failed:`Failed`,turnElapsedOutcome_uncertain:`Outcome unconfirmed`,settingsSetupBusyHint:`Agent configuration is available after this turn. Display settings can be changed now.`,resetChatContentWidth:`Reset chat content width`,resetChatFontSize:`Reset chat font size`,setupResolveAdmission:`Return to the conversation to resolve the pending message before applying settings.`,removeAttachment:`Remove attachment`,dropImagesHere:`Drop files or images here`,imageAttachmentCount:`Attach up to {{count}} images.`,imageAttachmentTooLarge:`Each image must be 10 MB or smaller.`,imageAttachmentTotalTooLarge:`The attached images must total 32 MB or less.`,imageAttachmentUnsupported:`Only valid PNG, JPEG, GIF, and WebP images are supported.`,imageAttachmentReadFailed:`Could not read this image. Add it again to retry; your message is preserved.`,attachedImage:`Attached image`,previewAttachment:`Preview image`,closeImagePreview:`Close image preview`,imagePreviewFailed:`Unable to display this image.`,fitImage:`Fit image`,originalImageSize:`Original size`,imageViewMode:`Image view`,sessionUsage:`Session token usage`,sessionInputTokens:`Input tokens`,sessionOutputTokens:`Output tokens`,sessionCacheTokens:`Cached tokens`,sessionContextUsage:`Context usage and context window`,usageContextLabel:`Context`,usageUnknown:`Unknown`,usageOpenDetails:`Input {{input}} · Output {{output}} · Context {{percent}} / {{capacity}} · View token usage`,usageContextHelp:`Estimated tokens in the current branch / model context limit.`,usageSessionTotals:`Session totals`,usageInputLabel:`Input`,usageOutputLabel:`Output`,usageTotalLabel:`Total`,usageWorkspaceLabel:`Workspace`,usageSessionId:`Session ID`,usageTotalsHelp:`Session token totals include cache usage.`,subagentDetails:`Subagents`,sessionOverview:`Session overview`,sessionOverviewChanges:`Changes in the current review scope`,subagentSummaryRunning:`{{count}} running`,subagentSummaryDone:`{{count}} completed`,subagentSummaryOther:`{{count}} other`,subagentNoneYet:`No subagents yet`,subagentOtherGroup:`Failed / interrupted`,subagentShowMore:`Show {{count}} more`,backToSubagents:`Back to subagents`,subagentActiveGroup:`Active`,subagentFinishedGroup:`Completed`,subagentNoneRunning:`No subagents running.`,subagentNoneFinished:`Completed tasks will appear here.`,subagentProgress:`Subagents: {{running}} running · {{completed}} completed`,subagentSummaryUnknown:`{{count}} without confirmed status`,subagentTasks:`Subagent tasks`,inspectSubagent:`Open subagent: {{name}}`,subagentState_running:`Running`,subagentState_done:`Completed`,subagentState_error:`Failed`,subagentState_interrupted:`Interrupted`,subagentStarting:`Starting…`,subagentSpawnFailed:`Failed to start`,subagentStateUnavailable:`Started · state unavailable`,subagentSpawnReceipt:`Start receipt`,subagentSpawnReceiptHint:`This confirms the start request, not the subagent's final result.`,subagentTask:`Assigned task`,subagentTranscript:`Subagent conversation`,subagentResult:`Result`,subagentSaved:`Saved record`,subagentRecordedState:`Last recorded state`,subagentSavedHint:`From this parent session's saved receipts. A result may include other tasks from the same batch; this is not the child's full live conversation.`,subagentLive:`Working · updates automatically`,subagentReadOnly:`Read-only view · closing this panel does not stop the task`,subagentUnavailable:`Live details are no longer available for this subagent in the current session. The start receipt is not evidence of completion.`,subagentStale:`Could not refresh. The details below are the last received snapshot.`,subagentNoMessages:`No messages received yet.`,subagentTranscriptUnavailable:`This view retains a task summary and cannot show the full child conversation.`,subagentWorkflowsTruncated:`{{count}} workflows are outside the loaded list; their task counts are unknown.`,subagentState_unknown:`Unconfirmed`,subagentUnconfirmedGroup:`Unconfirmed`,subagentTruncated:`Showing a bounded excerpt; {{count}} earlier messages omitted. Some text may be shortened.`,subagentListTruncated:`{{count}} additional tasks are outside the loaded list.`,subagentThinkingRedacted:`Reasoning was redacted by the provider.`,subagentTool_running:`Running`,subagentTool_done:`Returned`,subagentTool_error:`Failed`,subagentTool_unknown:`Result not retained`,inspectionChanged:`The active session changed. Reopen this panel.`,inspectionUnavailable:`Details are unavailable.`,inspectionLoading:`Loading status…`,thinkingUnavailable:`Thinking state is unavailable.`,trustUnavailable:`Project trust status is unavailable.`,executionState:`State`,terminalCommand:`Command`,copyTerminalCommand:`Copy command`,copyVisibleOutput:`Copy visible {{stream}}`,copySetupCommand:`Copy setup command`,savedTrustDecision:`Saved decision`,activeSessionTrust:`Active Session trust`,trustDecision_trusted:`Trusted`,trustDecision_denied:`Denied`,trustDecision_undecided:`Undecided`,trustDecision_unknown:`Unknown`,trustActiveYes:`Trusted in this Session`,trustActiveNo:`Not trusted in this Session`,terminalDirectory:`Directory`,startedAt:`Started`,exitCode:`Exit code`,detailTruncated:`Some details are shortened to keep this view bounded.`,standardOutput:`Standard output`,standardError:`Standard error`,outputTruncated:`{{count}} bytes omitted from this output view.`,outputRecovery:`The runtime reports a retained log. This view shows only a bounded excerpt.`,modelAndThinking:`Model and reasoning`,selectedModel:`Current model`,thinkingLevel:`Thinking level`,availableThinking:`Available levels`,unknownState:`Unknown`,projectTrust:`Project trust`,trust_trusted:`This session trusts the workspace.`,trust_untrusted:`Trust for this workspace has been denied.`,trust_restricted:`Project resources are restricted pending a trust decision.`,trust_unknown:`Trust state is not available.`,trustRefreshNeeded:`The saved decision and active session differ. Refresh the session through Pi to apply it.`,providerAvailability:`Provider credentials`,settings:`Settings`,settingsNavigation:`Settings navigation`,generalSettings:`General`,configurationSettings:`Configuration`,configurationIntro:`Permissions, web access and model responses.`,configurationReadFailure:`Configuration could not be read safely. Fix the settings file, then refresh.`,configurationUserScope:`User configuration`,configurationSetupHint:`Response and search changes use OpenPI setup`,configurationApproval:`Approval policy`,configurationApprovalDetail:`Tool approvals follow the installed Pi extensions.`,configurationPiPermissions:`Pi extensions`,configurationSandbox:`Sandbox`,configurationSandboxDetail:`Tools run with the host process permissions.`,configurationSandboxUnavailable:`No OS sandbox`,configurationSearchDetail:`Let the current Session model search the web when supported.`,configurationSearchOff:`Do not offer native search to the current model.`,configurationSearchOn:`Offer native search when the current connection supports it.`,configurationVerbosity:`Output verbosity`,configurationVerbosityDetail:`Choose how much detail the model includes in its response.`,configurationResponsesUnavailable:`The current connection does not use a supported Responses API.`,configurationVerbosity_default:`Model default`,configurationVerbosity_low:`Low`,configurationVerbosity_medium:`Medium`,configurationVerbosity_high:`High`,configurationVerbosityHelp_low:`Prefer short answers with fewer details.`,configurationVerbosityHelp_medium:`Include useful explanation and a moderate amount of detail.`,configurationVerbosityHelp_high:`Include more complete explanation and detail.`,configurationVerbosityRequest:`Set only response_verbosity to {{value}}; preserve the other OpenPI settings.`,configurationSummary:`Reasoning summary`,configurationSummaryDetail:`Choose the summary requested from a supported reasoning model.`,configurationSummaryUnavailable:`The current connection does not support reasoning summaries.`,configurationSummary_default:`Model default`,configurationSummary_auto:`Auto`,configurationSummary_concise:`Concise`,configurationSummary_detailed:`Detailed`,configurationSummary_none:`Off`,configurationSummaryHelp_auto:`Let the model choose the summary length.`,configurationSummaryHelp_concise:`Request a brief reasoning summary.`,configurationSummaryHelp_detailed:`Request a more detailed reasoning summary.`,configurationSummaryHelp_none:`Do not request a summary. Keep the current reasoning effort.`,configurationSummaryRequest:`Set only response_reasoning_summary to {{value}}; preserve the other OpenPI settings.`,configurationModelFeatures:`Model features`,configurationReasoningLevels:`Available reasoning efforts`,configurationReasoningDetail:`Choose which supported levels appear in model controls. The current level stays visible; its value is unchanged.`,configurationReasoningCount:`{{count}} selected`,configurationDependencies:`Workspace dependencies`,configurationEnvironment:`Local environment`,configurationEnvironmentDetail:`Node.js, Python and other tools come from your environment. OpenPI does not install a bundled workspace runtime.`,configurationRuntimeStatus:`Runtime status`,browserSettings:`Browser`,webSearchSettings:`Web search`,webSearchCurrentModel:`Current Session model`,webSearchNativeDetail:`Use your current model provider's native search with the existing connection and credentials.`,webSearchSupported:`This connection supports native search. When enabled, the model decides when to search.`,webSearchUnsupported:`Native search is unsupported or unconfirmed for this connection. No search tool is provided and no other provider is used.`,webSearchNativeRequest:`Enable native web search using the current Session model and existing Pi credentials. Do not switch model, connection protocol, or search provider. Unsupported or unknown connections must receive no search tool.`,webSearchIntro:`Let your model search current sources and read the original pages.`,webSearchPackageDetail:`Optional search, page reading, and PDF extraction through a Pi package.`,webSearchDefaultOff:`Off by default. This optional extension follows the current Session model; it needs no separate search key or plugin installation.`,webSearchLoaded:`Package loaded in this Session`,webSearchNotLoaded:`Package not loaded in this Session`,webSearchSource:`Review plugin source`,webSearchProfile:`Search setup`,webSearchExa:`Exa — no API key required`,webSearchExisting:`Keep my existing search preferences`,webSearchProfileHint:`Exa uses search queries with direct page reading. Existing preferences stay untouched. Other search services can be configured after installation.`,webSearchEnable:`Enable web search…`,webSearchDisable:`Disable web search…`,webSearchConfigure:`Change search service…`,webSearchExaRequest:`Enable optional web search with Pi Web Access and Exa, which needs no API key. Let me review the installation confirmation, preserve other preferences, and do not reload automatically.`,webSearchExistingRequest:`Enable optional web search with Pi Web Access and keep my existing search preferences unchanged. Let me review the installation confirmation, preserve other preferences, and do not reload automatically.`,webSearchDisableRequest:`Disable native web search. Preserve other settings and Session history.`,webSearchProviderRequest:`Help me change the search service for my installed Pi Web Access plugin. Explain available services and permissions, preserve unrelated preferences, keep credentials with the search plugin, and do not reload automatically.`,browserSettingsIntro:`Let OpenPI read pages, click, type and take screenshots.`,browserControl:`Browser control`,browserControlHint:`Requests a setup change. Access changes after the configuration is saved.`,browserDefault:`Default browser`,browserDefaultHint:`Requests a setup change for the browser used when none is named.`,browserEmbedded:`OpenPI browser`,browserAllowedTitle:`Allowed browsers`,browserOffHint:`Your choices take effect when browser control is on.`,browserConnected:`Connected`,browserNeedsSetup:`Extension setup needed`,browserNotFound:`Browser not detected`,browserUpdateNeeded:`Extension update needed`,browserBlocked:`Not allowed`,browserDefaultBlocked:`Your default browser is not allowed. Allow it or choose another default.`,browserSetUp:`Set up`,browserManage:`Manage`,browserSetupNamed:`Set up {{browser}}`,browserManageNamed:`Manage {{browser}}`,browserAllowNamed:`Allow {{browser}}`,browserMore:`More browsers`,browserSpeakHint:`Say “Use Chrome to…” to choose a different browser for a request.`,browserGuideTitle:`Connect {{browser}}`,browserGuideEyebrow:`One step at a time`,browserConnectionTitle:`Connection`,browserCloseGuide:`Close browser setup`,browserConnectionReady:`Connected. Choose whether OpenPI may use this browser.`,browserEmbeddedDetail:`Pages open inside OpenPI. Some websites require a regular browser to sign in or display correctly.`,browserExternalDetail:`OpenPI can use existing tabs and signed-in pages in your connected {{browser}} profile. Keep an OpenPI tab open in that profile.`,browserManageExtension:`Manage extension`,browserAllowUse:`Allow OpenPI to use it`,browserMakeDefault:`Use as default`,browserInstallIn:`Install in`,browserInstallTitle:`Install OpenPI Browser Bridge`,browserSetupSteps:`Setup steps`,browserGuidePopout:`Keep this guide in a separate window`,browserGuideDetached:`Your guide is open in a separate window. Follow it alongside the browser settings.`,browserShowGuide:`Show guide`,browserGuideInline:`Return guide here`,browserGuideBlocked:`The guide window could not open. Allow pop-ups and try again, or follow the steps here.`,browserSafariSettings:`Safari → Settings`,browserSafariDeveloper:`Developer settings`,browserSafariTemporary:`Add Temporary Extension…`,browserSafariOpenHint:`Open Safari, then choose Safari → Settings. Keep this guide alongside it. Requires Safari 26 or later on macOS.`,browserSafariDeveloperTitle:`Show Safari’s developer settings`,browserSafariDeveloperHint:`In Settings → Advanced, turn on Show features for web developers. Then select the Developer tab.`,browserSafariLoadHint:`In Developer, click Add Temporary Extension and select the folder below. Enable OpenPI Browser Bridge and allow the websites you want to control, including the local OpenPI page. Temporary extensions need reloading after Safari quits.`,browserFirefoxThis:`This Firefox`,browserFirefoxTemporary:`Load Temporary Add-on…`,browserFirefoxDeveloperTitle:`Select This Firefox`,browserFirefoxDeveloperHint:`On about:debugging, choose This Firefox in the left sidebar. Firefox does not need a Developer mode switch.`,browserFirefoxLoadHint:`Click Load Temporary Add-on and select manifest.json in the folder below. This development installation lasts until Firefox restarts; a permanent installation requires a Mozilla-signed package.`,browserFirefoxDone:`Selected. Next`,browserStepCount:`Step {{step}} of {{total}}`,browserStepLabel:`Step {{step}}: {{label}}`,browserStepOpen:`Open page`,browserStepAdd:`Add extension`,browserStepConnect:`Connect`,browserOpenManagerTitle:`Open {{browser}} extensions`,browserOpenManagerHint:`Start here. We’ll open the right page for you.`,browserOpenManager:`Open {{browser}} extensions`,browserReopenManager:`Open extensions page again`,browserAlreadyInstalled:`Already installed? Connect`,browserDeveloperMode:`Developer mode`,browserDeveloperTitle:`Turn on Developer mode`,browserDeveloperHint:`In the extensions page you just opened, turn on the Developer mode switch.`,browserDeveloperDone:`It’s on. Next`,browserIllustration:`Illustration · In {{browser}}`,browserExtensions:`Extensions`,browserLoadUnpacked:`Load unpacked`,browserLoadHint:`Click Load unpacked in your browser, then select the folder below.`,browserFolderBundled:`Included with OpenPI`,browserOpenFolder:`Open folder`,browserFolderOpened:`Extension folder opened.`,browserPathCopied:`Path copied`,browserCopyFailed:`Couldn’t copy. Select the path above and copy it manually.`,browserChooseFolderMac:`In the folder picker, press ⌘ ⇧ G, paste this path and press Return, then click Select.`,browserChooseFolderOther:`In the folder picker, paste this path into the address bar and select the folder.`,browserInstalledConnect:`Added. Connect to OpenPI`,browserPreviousStep:`Back`,browserWaiting:`Waiting for OpenPI Browser Bridge… We’ll detect it automatically.`,browserInstallBrowserFirst:`Install {{browser}} first, or open this OpenPI address in your installed browser.`,browserConnectTitle:`Connect to OpenPI`,browserConnectHint:`Open OpenPI in {{browser}}. Use the profile where you installed the extension.`,browserOpenIn:`Open in {{browser}}`,browserAllowHint:`Once connected, you can allow OpenPI to use this browser. Installing the extension does not change your browser permissions.`,browserCheck:`Check connection`,browserNotConnectedYet:`No connection yet. Finish installation, refresh OpenPI in that browser and check again.`,browserHelp:`Setup help`,browserReloadHint:`Already installed? Reload OpenPI Browser Bridge in the extension manager and refresh OpenPI. Accept the browser’s permission prompt if shown.`,browserSupportedHint:`Chrome, Edge, Brave and Chromium 145+ support embedded and native pages. Safari 26+ on macOS and Firefox 128+ use the portable extension for native tabs; nested frames must be opened separately. Temporary Safari/Firefox installations need reloading after browser restart.`,browserCopyPath:`Copy extension folder path`,browserLoading:`Checking browser connections…`,browserSaved:`Saved. Browser permissions take effect immediately.`,browserSaving:`Saving…`,modelSettings:`Models`,skillsSettings:`Skills`,subagentsSettings:`Sub-agents`,pluginsSettings:`Plugins`,configureOpenPi:`Configure OpenPI`,setupRequestReviewAll:`review every OpenPI configuration area with me`,setupRequestSetTheme:`set only the OpenPI Web theme to {{value}} and preserve every other setting`,setupRequestSetChatWidth:`set only the OpenPI Web chat content width to {{value}}px and preserve every other setting`,setupRequestSetChatFontSize:`set only the OpenPI Web chat font size to {{value}}px and preserve every other setting`,setupRequestEnableExpandedThinking:`expand thinking blocks by default in OpenPI Web and preserve every other setting`,setupRequestDisableExpandedThinking:`collapse thinking blocks by default in OpenPI Web and preserve every other setting`,setupRequestSubagents:`review and configure Agent role models and workflow limits`,setupRequestFailed:`The OpenPI setup request was not accepted.`,setupRequestRunning:`Applying OpenPI settings…`,setupRequestAccepted:`Configuration request accepted.`,setupPlanBlocked:`Exit Plan mode before changing agent configuration. Display settings can be changed directly; exiting does not start implementation.`,setupPlanBusy:`Agent configuration requires an idle turn and leaving Plan mode. Display settings can be changed now.`,setupOutcome_pending:`Configuration request is awaiting a save receipt.`,toolCallArguments:`Tool arguments`,toolCallOutput:`Tool result`,setupOutcome_saved:`OpenPI configuration was saved and applied.`,setupOutcome_unchanged:`Configuration was saved; effective settings are unchanged.`,setupOutcome_failed:`The setup request failed. Review the error and current settings before retrying.`,setupOutcome_cancelled:`Setup was cancelled without a confirmed save.`,setupOutcome_unconfirmed:`No successful save was confirmed. Review current settings before retrying /openpi-setup.`,settingsUpdateFailed:`The Web preference could not be saved.`,settingsPreferencesSaved:`Display settings saved.`,settingsPreferencesSaveFailed:`Could not save display settings. Check configuration diagnostics and retry.`,settingsCatalogLoading:`Loading Pi resources…`,settingsCatalogFailed:`Could not load Pi settings resources.`,appearance:`Appearance`,settingsPersonal:`Personal`,settingsAgent:`Agent`,settingsIntegrations:`Integrations`,settingsArchivedChats:`Archived chats`,settingsSearch:`Search settings`,settingsClearSearch:`Clear search`,settingsNoResults:`No matching settings`,appearanceVisualStyle:`Visual style`,appearanceMode:`Mode`,appearanceTheme:`Theme`,appearanceAccent:`Accent color`,appearanceBackground:`Background`,appearanceForeground:`Foreground`,appearanceFont:`Font`,appearanceFont_codex:`Codex default`,appearanceFont_sans:`Sans serif`,appearanceFont_serif:`Serif`,appearanceFont_mono:`Monospace`,appearanceAccent0:`Default`,appearanceAccent1:`Blue`,appearanceAccent2:`Purple`,appearanceAccent3:`Pink`,appearanceAccent4:`Orange`,appearanceAccent5:`Green`,appearanceCustomAccent:`Custom accent color`,appearanceAdvanced:`Advanced`,appearanceReset:`Restore defaults`,appearanceResetAction:`Reset appearance`,appearanceImport:`Import theme`,appearanceCopy:`Copy theme`,appearanceCopied:`Theme copied`,appearanceCopyFailed:`Could not copy theme. Try again.`,appearanceThemeValue:`Theme data`,appearanceImportPlaceholder:`Paste an OpenPI theme…`,appearanceImportInvalid:`Enter valid OpenPI theme data.`,appearanceImportAction:`Import`,searchArchivedChats:`Search archived chats`,archiveProjectFilter:`Filter by project`,archiveAllProjects:`All projects`,archiveProjectGroup:`{{project}} · {{count}} archived chats`,archiveSort:`Sort archived chats`,archiveSortUpdated:`Last updated`,archiveSortCreated:`Date created`,restoreArchivedChat:`Restore {{title}}`,themeLight:`Light`,themeDark:`Dark`,themeMist:`Mist`,themeRose:`Rose`,themePine:`Pine`,themeSystem:`System`,conversationSettings:`Conversation`,expandThinkingByDefault:`Expand thinking by default`,chatContentWidth:`Chat content width`,chatFontSize:`Chat font size`,agentBehavior:`Agent behavior`,capabilityDiscovery:`Capability discovery`,capabilityDiscovery_explicit:`Explicit`,capabilityDiscovery_adaptive:`Adaptive`,workflowLimits:`Workflow limits`,workflowConcurrency:`Workflow concurrency`,workflowCalls:`Total calls`,agentSettingsSetupHint:`Agent changes are applied through /openpi-setup in the current session.`,setupRequestDiscovery:`Set capability discovery to {{mode}}. Preserve other settings.`,setupRequestLimits:`Set workflow concurrency to {{concurrency}} and total agent calls to {{calls}}. Preserve other settings.`,setupRequestEnableSuggestions:`Enable next-action suggestions. Help me choose a model if required; preserve other settings.`,setupRequestDisableSuggestions:`Disable next-action suggestions. Preserve other settings.`,setupRequestPostEdit:`Help me configure or disable the post-edit command. Show the current configuration and ask which command to use.`,configurePostEdit:`Configure post-edit command`,workflowLimitsValue:`{{concurrency}} concurrent · {{calls}} total calls`,nextActionSuggestions:`Next-action suggestions`,enabled:`Enabled`,disabled:`Disabled`,configured:`Configured`,postEditCommand:`Post-edit command`,resultDisplay:`Default result display`,subagentResults:`Subagent results`,bashOperations:`Bash operations`,fileMutations:`Write / Edit operations`,footer:`Footer`,terminalFooter:`Pi terminal footer`,terminalFooterStyle:`Terminal footer style`,terminalFooterHint:`Applies to Pi's command-line interface. An already open Pi interface updates when restarted or when setup is applied.`,detailDisplay_full:`Full`,detailDisplay_compact:`Compact`,sessionSettings:`Session`,currentModel:`Current`,useThisModel:`Use model`,model:`Model`,modelConnection:`Model connection`,provider:`Provider`,modelId:`Model ID`,providerStatusUnavailable:`This provider is not present in the bounded authentication snapshot.`,providerSettings:`Provider credentials`,providerSettingsIntro:`Inspect which Pi providers can authenticate the current Web session.`,openRuntimeDetails:`Open runtime details`,currentWorkspace:`Current workspace`,providerAuth_api_key:`API key`,providerAuth_oauth:`OAuth`,providerAuthUnknown:`Authentication method not reported`,authentication:`Authentication`,accessType:`Access`,providerAccessSubscription:`Subscription account`,providerAccessStandard:`Provider credentials`,configurationOwner:`Configuration owner`,providerLoading:`Loading provider status…`,providerLoadFailed:`Could not load provider status.`,providerReadOnly:`Managed by Pi`,selectProvider:`Select a provider`,gitReviewBaselineUnavailable:`No usable session baseline was retained (it may exceed the capture limit). Choose Unstaged, Staged or Branch to inspect Git changes, or open the session file records.`,modelsIntro:`Sign in with an account or add an API key. Your existing Pi connections are available here.`,accountLoginMethod:`Connection method`,accountLoginTab:`Account`,accountLoginChatGPT:`ChatGPT account`,accountLoginClaude:`Claude account`,accountLoginKeyTab:`API key`,accountLoginConfigured:`Account signed in`,accountLoginIntro:`Continue in your browser. No API key needed.`,accountLoginExisting:`Your account credential is saved in Pi.`,accountLoginStart:`Sign in`,accountLoginAgain:`Sign in again`,accountLoginUnsaved:`Save or discard your other changes before signing in.`,accountLoginStarting:`Preparing sign-in…`,accountLoginWaiting:`Waiting for authorization`,accountLoginChoose:`Choose how to sign in`,accountLoginCancelling:`Cancelling sign-in…`,accountLoginBrowser:`Continue in browser`,accountLoginDevice:`Use a device code`,accountLoginBrowserOption:`Sign in on this computer. Returns here automatically.`,accountLoginDeviceOption:`For remote servers or when browser sign-in is unavailable.`,accountLoginBrowserHelp:`Open the sign-in page and approve access. This page updates automatically.`,accountLoginDeviceHelp:`Open the authorization page and enter this code. Keep this page open.`,accountLoginOpen:`Open sign-in page`,accountLoginCopyCode:`Copy device code`,accountLoginPaste:`Authorization code or callback URL`,accountLoginContinue:`Continue`,accountLoginFallback:`Signed in but still waiting?`,accountLoginRemoteHelp:`If automatic return does not work, copy the final callback URL from your browser and paste it here.`,accountLoginCancel:`Cancel sign-in`,accountLogin_failed:`Sign-in failed. Try again or choose another method.`,accountLogin_expired:`Sign-in expired. Start again to get a new authorization link.`,accountLogin_cancelled:`Sign-in cancelled.`,accountLoginRequestFailed:`The request did not complete. Refresh status before retrying.`,accountLoginStatusUnknown:`Cannot check sign-in status. Your authorization may still be in progress.`,accountLoginRefreshRequired:`The credential was saved, but Pi could not update its model list. Reload Pi before using this connection.`,accountLogout:`Sign out`,accountLogoutRefreshRequired:`The saved credential was removed, but Pi could not update its model list. Reload Pi to refresh the status.`,accountLogoutTitle:`Sign out of {{provider}}?`,accountLogoutDetail:`Removes this provider’s saved credential from Pi on this machine. Other Pi sessions using it will also need to sign in again. Environment credentials are unchanged.`,providerInputTypes:`Input types`,providerInputText:`Text`,providerInputImage:`Images`,providerCustomTag:`Custom`,providerEdit:`Edit`,providerRemove:`Delete`,providerSave:`Save`,editProvider:`Edit {{provider}}`,removeProvider:`Delete {{provider}}`,providerAdd:`Add model provider`,providerAddMode:`How to add`,providerAddCatalog:`Third-party providers`,providerAddCustom:`Custom model API`,providerAccountHint:`Use an existing account to connect. Choose a provider and continue in your browser.`,providerCatalogHint:`Choose a provider from the built-in catalog and enter its API key.`,providerCustomHint:`Connect a gateway or self-hosted service using an OpenAI or Anthropic compatible API.`,providerKeyKeep:`Leave blank to keep the existing key`,providerKeyOptional:`Enter an API key, or leave blank to use environment authentication`,providerDisplayName:`Provider name`,providerCustomSettings:`Custom settings`,providerSaved:`Saved {{provider}}.`,modelDefaultTitle:`Default for new chats`,modelDefaultChoose:`Choose model`,modelDefaultBadge:`Default`,modelCurrentBadge:`In use`,modelDefaultNotSet:`Not set · Pi chooses when a new chat starts`,modelDefaultHint:`Choose the model for future chats. Existing chats keep their own model. This also updates Pi's default.`,modelDefaultReadFailed:`Could not read the default model.`,modelDefaultProjectOverride:`This workspace has a Pi override: {{model}}.`,modelDefaultSave:`Save default`,modelMakeDefault:`Also make this the default for new chats`,modelDefaultSaveFailed:`The default was not confirmed. Refresh status and try again.`,modelDefaultPartial:`The chat model changed, but saving the default was not confirmed. Refresh status before retrying.`,modelConnectionNextHint:`Choose a model from this connection to use in the current chat.`,modelConnectionSearch:`Search models…`,modelConnectionChooseProvider:`Choose a model from {{provider}}`,modelConnectionUse:`Use in this chat`,modelConnectionUseFailed:`The model change was not confirmed. Refresh the model list and try again.`,modelConnectionLoadFailed:`Could not load models.`,modelConnectionNoModels:`No selectable models yet. Check the connection or add a model definition.`,modelConnectionNoMatch:`No matching models.`,modelConnectionMore:`{{count}} more models. Search to narrow the list.`,providerModelsEmpty:`No models yet. Fetch available models or add one manually.`,providerModelsInherited:`Uses the provider’s built-in model catalog.`,providerModelsReadOnly:`This provider contains model settings that must be edited in Pi’s configuration file.`,providerModelId:`Model {{number}} ID`,providerModelName:`Model {{number}} name`,providerModelDetails:`Model details: {{model}}`,providerRemoveModel:`Remove model: {{model}}`,providerIdInvalid:`Use a unique provider ID with letters, numbers, hyphens, dots or underscores.`,providerNativeAuth:`This provider uses Pi’s native sign-in.`,providerConfigurationFailed:`Could not save. Check the fields and retry when the session is idle.`,providerProfileSavedKeyFailed:`The provider was saved, but its API key was not. Retry saving the key.`,providerReload:`Discard draft and reload`,providerCurrentRemoval:`Select another model before removing the model currently in use.`,providerRemoveDetail:`Remove this provider’s configuration and custom models? Credentials managed by Pi are kept.`,providerPickerIntro:`Select the models you want to add from this provider.`,providerPickerSelected:`{{count}} selected`,providerApiKey:`API key`,providerKeyPlaceholder:`Paste a key to add or replace it`,saveProviderKey:`Save API key`,savingSettings:`Saving…`,keepEditing:`Keep editing`,discardAndContinue:`Discard and continue`,unsavedSettingsTitle:`Discard unsaved changes?`,unsavedSettingsDetail:`Unsaved model and credential changes will be lost.`,unsavedCredentialTitle:`Discard the unsaved credential?`,unsavedCredentialDetail:`The new key has not been saved and will be cleared.`,modelSelectionBusy:`This session is busy. Model changes are unavailable.`,providerKeySaved:`Saved to Pi credentials. Existing keys are never displayed.`,providerSaveFailed:`Credential save did not complete. Wait until the session is idle, refresh status and retry. Some providers need additional authentication settings.`,providerWriteDetail:`Save API keys here directly to Pi. Keys never enter a model conversation. For OAuth or additional provider fields, use Pi's native login.`,editModelConfiguration:`Add or edit a custom model`,modelConfigurationDetail:`Set up a provider connection, then choose available models or add one manually. Saving does not send a model request.`,configuredModels:`Custom model configuration`,addModel:`Add a model`,modelConfig_provider:`Provider ID`,modelConfig_id:`Model ID`,modelConfig_name:`Display name`,modelConfig_baseUrl:`API base URL`,modelConfig_api:`API format`,modelConfig_contextWindow:`Context window`,modelConfig_maxTokens:`Max output tokens`,providerCapacityLabel:`{{field}} {{number}}`,providerModelOptions:`Model options`,providerModelInvalid:`Model {{number}}: use a unique model ID and positive token counts, such as 128K or 1M. Leave capacities blank to use defaults.`,modelConfig_reasoning:`Supports reasoning`,saveModelConfiguration:`Save model`,reloadModelConfiguration:`Discard draft and load latest`,retryModelConfiguration:`Retry loading`,discardModelDraftTitle:`Discard this model draft?`,discardModelDraftDetail:`The latest configuration will replace this unsaved draft.`,discardAndReload:`Discard and reload`,modelConfigurationUnsaved:`Unsaved changes`,modelConfigurationConflict:`Model configuration changed elsewhere. Your draft is unchanged.`,modelConfigurationLoadFailed:`Could not load model configuration. Your draft is unchanged.`,modelConfigurationSaved:`Saved to Pi models.json. Configure the provider API key to make this model available.`,modelConfigurationFailed:`Model save did not complete. Your draft is unchanged.`,setupConfigurationRequest:`Configuration request`,configureViaSetup:`Apply via OpenPI setup`,setupFormDetail:`Uses /openpi-setup. Follow progress and any required confirmation in the conversation; submission does not mean the configuration is saved.`,setupSkillsPlaceholder:`Describe the skill to add or configure, including its source or local path`,setupPluginsPlaceholder:`Describe the Pi package to configure, including its exact package name or local path`,enableSkillInvocation:`Allow model invocation`,disableSkillInvocation:`Require explicit invocation`,setupSkillInvocationRequest:`Configure this Pi skill: {{path}}. Set its native disable-model-invocation field to {{disabled}}. Preserve other content and explain when the change takes effect.`,setupRoleFormRequest:`Configure the OpenPI {{role}} role to use {{model}} and set workflow concurrency to {{concurrency}}. Inherit parent thinking, validate the selection and preserve unrelated configuration.`,providerReadOnlyDetail:`This page is read-only and never receives credential values. Configure provider authentication through Pi, then refresh this status.`,openProviderSettings:`Open provider settings`,credentialConfigured:`Configured`,credentialMissing:`Not configured`,authNotVerified:`Configured credentials do not guarantee a successful model request.`,configurationViaPi:`Read-only status. Manage model credentials and trust through Pi; manage OpenPI options with /openpi-setup.`,noSkillsFound:`No skills are loaded for this Session.`,addSkill:`Add skill`,addPlugin:`Add plugin`,searchResources:`Search by name or source`,filterResourceScope:`Resource scope`,allResourceScopes:`All scopes`,noMatchingResources:`No matching resources`,resourceBulkTooLarge:`Filter the list further before submitting a bulk request.`,resourceManagement:`Pi resources`,resourceSourceAuto:`Pi automatic discovery`,resourceSourceLocal:`Local resource`,resourcePackageSource:`Package, repository or local path`,resourcePackageSourcePlaceholder:`npm:package@version · git:owner/repo · /path/to/skill`,resourceInstallIntro:`Choose a source and scope. OpenPI setup will review and apply the request in the conversation.`,resourceInstallReview:`Review the exact source and permissions in the conversation. Submitting this request does not mean it is installed or loaded.`,resourceRequestSubmitted:`Request submitted. Follow progress and confirmations in the conversation, then refresh this catalog.`,browseSkills:`Browse skills.sh`,resourceSessionState:`Apply to this Session`,resourcesReloadNote:`Refresh reads the catalog. Reload applies saved resources to this idle Session; changes are never reloaded automatically.`,reloadResources:`Reload resources`,resourceReloadReview:`Apply saved Pi skill and plugin configuration and restart extensions in the current Session? Wait for running work to finish first.`,resourceReloaded:`Resources reloaded. Review the refreshed catalog and diagnostics.`,resourceReloadFailed:`Could not reload resources. Wait for this Session to become idle and refresh before retrying.`,advancedResourceConfiguration:`Advanced configuration`,resourceDiagnostics:`Pi reports {{extensionErrors}} extension diagnostics and {{skillErrors}} skill diagnostics.`,resourceConfigurationDiagnostics:`{{count}} settings files could not be read. Review Pi configuration diagnostics.`,resourceCatalogTruncated:`This catalog is bounded; some resources are omitted.`,resourceTargetTruncated:`This source or path is truncated. Confirm the full target through Advanced configuration before making changes.`,updateResource:`Review update`,removeResource:`Review removal`,skillsEmptyTitle:`Add your first skill`,skillsEmptyIntro:`Skills give Pi reusable instructions. Add a package, repository or local skill; project skills follow Pi project trust.`,pluginsEmptyTitle:`Extend Pi with a plugin`,pluginsEmptyIntro:`Packages can include extensions, skills, prompts and themes. Add a source to review its installation through OpenPI setup.`,pluginCount:`{{count}} plugin sources`,installedVersion:`Installed version`,configuredVersion:`Configured version`,resourceVersionUnpinned:`Not pinned / local source`,pluginState_loaded:`Session resources loaded`,pluginState_installed:`Installed · not loaded`,pluginState_disabled:`Disabled in configuration`,pluginState_missing:`Package missing`,pluginState_error:`Load diagnostics`,pluginState_notLoaded:`Not loaded`,pluginLoadedResources:`{{count}} resources in this Session's catalog. Configuration changes require an explicit reload.`,pluginAction_enable:`Review enable`,pluginAction_disable:`Review disable`,pluginAction_update:`Review update`,pluginAction_remove:`Review removal`,enableVisibleSkills:`Allow model use ({{count}} shown)`,disableVisibleSkills:`Explicit use only ({{count}} shown)`,enableVisiblePlugins:`Enable {{count}} shown packages`,disableVisiblePlugins:`Disable {{count}} shown packages`,setupResourceInstallRequest:`Add these Pi {{kind}} from source {{source}} in scope {{scope}}. Inspect the source and resolve a fixed package identity, review required installation permissions with me using ask_user, then use Pi's native package/skill configuration. For a skill request, preserve unrelated extensions and other resources. Preserve existing preferences and project trust; do not reload this Session automatically. Report saved configuration and any remaining action separately. Do not change unrelated OpenPI settings.`,setupPluginOperationRequest:`Review Pi package action {{action}} for exactly configured source {{source}}, native root {{path}}, scope {{scope}}. Resolve relative sources against the native scope's settings directory. Use Pi's native package management. For updates, inspect available versions and review a fixed target identity and required permissions with me using ask_user before installing. Preserve resource filters and all unrelated preferences; if a toggle would destroy filters, stop and explain. Removal must not delete a local source directory. Do not reload automatically. Report persisted and active states separately; do not change unrelated OpenPI settings.`,setupSkillManageRequest:`Review Pi skill action {{action}} for exactly file {{path}}, source {{source}}, scope {{scope}}. Inspect native ownership first. Review the update/removal and required permissions with me using ask_user. Preserve unrelated skills and package resources; do not remove an entire shared package to remove one skill. Preserve project trust and do not reload automatically. Do not change unrelated OpenPI settings.`,setupSkillsBulkRequest:`For exactly these currently displayed Pi skill files {{paths}}, set native disable-model-invocation to {{disabled}}. Inspect ownership, preserve all other content and preferences, review necessary changes with me, and report any files that cannot be changed safely. Explicit /skill invocation remains available. Do not reload automatically or change unrelated OpenPI settings.`,setupPluginsBulkRequest:`For exactly these currently displayed Pi packages {{packages}}, set disabled to {{disabled}} through native Pi configuration. Preserve all other preferences and resource filters; skip and report entries whose filters cannot be preserved. Respect scope and project trust, review necessary changes with me, and do not reload automatically or change unrelated OpenPI settings.`,resourceRequestFinished:`The setup turn has ended. Refresh and inspect Pi's configuration and Session resources to confirm what changed.`,skillCount_one:`{{count}} skill`,skillCount_other:`{{count}} skills`,skill:`Skill`,copySkillInvocation:`Copy invocation`,source:`Source`,scope:`Scope`,invocation:`Invocation`,modelInvocation:`Model invocation`,resourceScope_user:`Global`,resourceScope_project:`Project`,resourceScope_temporary:`Temporary`,explicitOnly:`Explicit invocation only`,availableToModel:`Available to the model`,skillFile:`Skill file`,selectSkill:`Select a skill`,subagentConfiguration:`Pi-native subagent roles`,subagentConfigurationIntro:`Role models inherit from the parent unless OpenPI setup assigns an available model.`,subagentActiveCount_one:`{{count}} active`,subagentActiveCount_other:`{{count}} active`,subagentCompletedCount_one:`{{count}} recorded`,subagentCompletedCount_other:`{{count}} recorded`,subagentConcurrency:`Limit {{count}}`,builtInRoles:`Built-in roles`,subagentRole_explorer:`Explorer`,subagentRole_implementer:`Implementer`,subagentRole_reviewer:`Reviewer`,subagentRole_advisor:`Advisor`,subagentRoleShort_explorer:`Read-only investigation`,subagentRoleShort_implementer:`Focused implementation`,subagentRoleShort_reviewer:`Correctness review`,subagentRoleShort_advisor:`Technical analysis`,subagentRoleDescription_explorer:`Explores the codebase and reports evidence without modifying files.`,subagentRoleDescription_implementer:`Implements a bounded change and runs the relevant repository checks.`,subagentRoleDescription_reviewer:`Reviews correctness, safety, regressions, and missing validation.`,subagentRoleDescription_advisor:`Analyzes difficult technical questions and recommends a concrete next step.`,configureRoles:`Configure roles`,builtInRole:`Built-in role`,builtIn:`Built-in`,modelAssignment:`Model assignment`,inheritParentModel:`Inherit parent model`,effectiveModel:`Effective model`,workflowConcurrencyLabel:`Concurrent agents`,workflowCallLimit:`Total agent calls`,runtimeBoundaries:`Runtime boundaries`,subagentAuthorityNote:`Child authority is the fail-closed intersection of the parent Session and role capabilities.`,subagentModelNote:`No hardcoded provider is introduced; an unassigned role follows the parent model and thinking level.`,resourceCount_one:`{{count}} resource`,resourceCount_other:`{{count}} resources`,noPluginsFound:`No loaded plugin sources were reported.`,pluginCatalogTotals:`{{extensions}} ext · {{skills}} skills · {{prompts}} prompts · {{themes}} themes`,loaded:`Loaded`,resourceOrigin:`Origin`,resourceOrigin_package:`Package`,resourceOrigin_topLevel:`Top-level resource`,resources:`Resources`,baseDirectory:`Base directory`,notReported:`Not reported`,extensions:`Extensions`,extensionSurfaceCount:`{{tools}} tools · {{commands}} commands`,prompts:`Prompts`,themes:`Themes`,pluginResourceSummary:`{{extensions}} ext · {{skills}} skills · {{prompts}} prompts · {{themes}} themes`,pluginsManagedByPi:`These resources are loaded by Pi. Submit changes using the setup form above. Package changes follow native confirmation and take effect through Pi's reload lifecycle.`,selectPlugin:`Select a plugin source`,statusCaptured:`Snapshot at {{time}} · refresh for the latest state`,conversationViews:`Conversation views`,currentConversations:`Current`,archivedConversations:`Archived`,refreshArchives:`Refresh archived conversations`,loadingArchives:`Loading archived conversations...`,moreArchives:`Load more archived conversations`,retryArchives:`Retry archived conversations`,archiveLoadFailed:`Could not load archived conversations.`,archiveCursorStale:`Archived conversations changed. Refresh to continue.`,archiveScanBounded:`{{count}} older records have not been scanned.`,noArchivedSessions:`No archived conversations.`,noScannedArchives:`No archived conversations in the scanned history.`,noMatchingScannedArchives:`No matching archived conversations in the scanned history.`,draftLimit:`Draft storage is full. Send or clear an existing draft before adding more content.`,restoreConversation:`Restore conversation`,restoringConversation:`Restoring…`,loadedArchives:`Archived conversations in the loaded history`,loadedHistoryBounded:`{{sessions}} more sessions and {{workspaces}} workspace summaries are not loaded. Search covers the loaded list only.`,noLoadedArchives:`No archived conversations in this loaded list.`,restoreFailed:`Could not confirm restoration. Refresh and try again.`,execution_running:`Running`,execution_done:`Completed`,execution_killed:`Stopped`,execution_timed_out:`Timed out`,execution_failed:`Failed`,execution_uncertain:`Uncertain`,activeOnlyHint:`Only the active Web session accepts messages.`,acceptedHint:`Message accepted by OpenPI Web.`,promptAdmissionUnknown:`It is unclear whether the last message was received.`,promptAdmissionUnknownDetail:`Review the refreshed Session history and runtime status before deciding. Sending as a new message may create a duplicate message.`,promptAdmissionCheckingDetail:`Checking the latest Session history and runtime status before resend options are enabled.`,promptAdmissionVerificationFailedDetail:`Could not refresh the latest Session history and runtime status. Check again before sending as a new message.`,abandonAdmission:`Don't resend for now`,retryAdmissionCheck:`Check again`,retryOriginalAdmission:`Retry original message`,promptTooLong:`Message exceeds the send limit ({{count}} / {{limit}}).`,sendAsNew:`Send as new message`,sendingAsNew:`Sending…`,stopTurn:`Stop current turn`,stoppingTurn:`Stopping current turn…`,stoppedTurn:`Current turn stopped.`,pendingFollowUpsHint:`{{count}} messages queued`,sendNextTurn:`Send next turn`,steerCurrentTurn:`Steer current turn`,steeringHint:`Use this instruction after the current tool step finishes.`,pendingSteeringHint:`{{count}} instructions received; waiting for the current tool step`,steeringMessagesTitle:`Pending instructions for this turn`,steerStaleTurn:`That turn has ended or changed. Your draft is kept; choose how to send it again.`,sourceFeedbackNew:`{{path}} · new line {{line}}`,sourceFeedbackOld:`{{path}} · old line {{line}}`,forkMessage:`Fork from here`,forkMessageHint:`Create a new conversation from this message. Keep the original conversation; no message is sent.`,forkSessionPending:`Creating a fork…`,forkSessionCreated:`Fork created. The original conversation remains in the sidebar.`,forkSessionCancelled:`Fork cancelled. The original conversation is kept.`,forkSessionUncertain:`The fork could not be confirmed. Refresh and inspect your conversations before trying again.`,forkSessionUnavailable:`Switch to this conversation and let its current work and queued messages finish before forking.`,reviewQuoteLine:`Reference this line`,reviewSelectOldLine:`Select old line {{line}}`,reviewSelectNewLine:`Select new line {{line}}`,queuedMore:`{{count}} more queued`,queuedImage:`Image attachment`,queuedMessageExpand:`Expand queued message`,queuedMessageCollapse:`Collapse queued message`,backgroundSessionRunning:`This session is running in the background…`,observedSessionTools:`{{count}} active tools`,toolsRequireCurrentSession:`Switch to this session to use interactive tools.`,activateViewedSession:`Switch to this session`,activateViewedSessionHint:`Send a message to continue this conversation.`,addWorkspace:`Add workspace`,addWorkspaceMenu:`Add workspace...`,archiveConversation:`Archive conversation`,pinnedConversations:`Pinned`,sidebarOptions:`Sidebar options`,sidebarProjectOptions:`Project sidebar options`,sidebarRecentOptions:`Chat sidebar options`,sidebarActivityOptions:`Activity view options`,sidebarShow:`Show`,sidebarGroupBy:`Group conversations`,sidebarByProject:`By project`,sidebarFlatList:`All conversations`,sidebarChatSort:`Conversation order`,sidebarRecent:`Recent`,sidebarProjectsInRecents:`Show projects in Recent`,sidebarShowMore:`Show more`,sidebarShowLess:`Show less`,sidebarFilterList:`Filter this list`,sidebarSaveFailed:`Could not save the change. Please try again.`,pinWorkspace:`Pin project`,unpinWorkspace:`Unpin project`,markConversationRead:`Mark as read`,markConversationUnread:`Mark as unread`,sidebarState_unread:`Unread conversation`,sidebarActivity:`Activity`,sidebarViewActivity:`View activity`,sidebarViewChats:`View conversations`,sidebarPriority:`Priority`,sidebarActivityEmpty:`Nothing needs attention`,sidebarActivityEmptyHint:`Completed work and conversations needing your attention appear here.`,sidebarMarkAllRead:`Mark all as read`,sidebarClearRead:`Clear read chats from Priority`,sidebarReadFailed:`Could not update read status. Please try again.`,sidebarToday:`Today`,sidebarYesterday:`Yesterday`,sidebarEarlier:`Earlier`,sidebarActivityCompleted:`Completed`,sidebarActivityFailed:`Failed`,sidebarActivityRead:`Read`,modelAdvanced:`Advanced parameters`,providerConnectionHeading:`Provider connection`,providerFetchModels:`Get available models`,providerFetchHint:`Enter the provider and endpoint, then choose models in one step.`,providerPickerTitle:`Choose models to add`,providerPickerAccess:`Connection credentials`,providerPickerKey:`Access key (optional)`,providerPickerKeyHint:`Leave blank to use saved credentials for this endpoint. A key entered here is used for discovery only and is not saved.`,providerPickerSearch:`Search models`,providerPickerSelectAll:`Select all`,providerPickerClear:`Clear selection`,providerPickerLoading:`Reading available models…`,providerPickerAdded:`Added`,providerPickerNoMatch:`No matching models`,providerPickerEmpty:`No models returned. You can still add one manually.`,providerPickerBounded:`Showing the first 500 models. Add other IDs manually.`,providerPickerError_load:`Could not read the model list. Check the endpoint and credentials, then retry or add a model manually.`,providerPickerError_save:`Could not confirm the save. Your selection is kept; check the connection before retrying.`,providerPickerError_conflict:`Configuration changed elsewhere. Close this dialog and reload configuration before saving again.`,providerPickerDefaults:`New models use {{context}} context / {{output}} output tokens. You can adjust these per model after adding.`,providerPickerRetry:`Refresh list`,providerPickerCount:`{{count}} selected · up to 100`,providerPickerSave:`Add selected`,sidebarState_running:`Running`,sidebarState_compacting:`Organizing context`,sidebarState_waiting:`Waiting for your response`,sidebarState_completed:`Completed · unread result`,sidebarState_failed:`Failed · open conversation for details`,pinnedOptions:`Pinned options`,pinConversation:`Pin conversation`,unpinConversation:`Unpin conversation`,pinnedRecentlyUpdated:`Recently updated`,pinnedManualOrder:`Manual order`,movePinUp:`Move up`,movePinDown:`Move down`,pinSaveFailed:`Could not save pinned conversations. Please try again.`,cancel:`Cancel`,chooseWorkspaceHint:`Choose a workspace and describe the work`,close:`Close`,closeSearch:`Close search`,collapseSidebar:`Collapse sidebar`,confirmEdit:`Save and rerun`,editMessageHint:`Rerun from here in a new branch. Keep the original conversation, images and file references. Existing workspace changes are kept.`,regenerateMessage:`Regenerate response`,regenerateMessageHint:`Rerun this question in a new branch, keeping its original attachments and conversation.`,messageRerunStarted:`Rerun admitted in a new branch. The original conversation is kept.`,openOriginalConversation:`View original conversation`,messageRerunWorkspaceHint:`Existing workspace changes are kept.`,modelRequestRecovered:`Request recovered`,modelReconnecting:`Reconnecting`,modelReconnectUnknown:`Reconnection status unconfirmed`,modelEarlierAttempts:`Earlier request errors`,modelFailedAttempts:`Failed attempts ({{count}})`,draftStorageUnavailable:`Draft could not be saved on this device. Keep this page open or copy your message.`,draftStorageInvalid:`Some saved draft content could not be restored. Check your message and attachments.`,draftStorageRetry:`Retry saving draft`,workbarBackToChat:`Back to chat`,workbarCollapseTools:`Collapse tools`,workbarEndTerminal:`Close {{name}} and end its process`,workbarNewTerminal:`New terminal`,workbarContinueInChat:`Continue in chat`,transcriptSearch:`Search message contents`,transcriptSearchPlaceholder:`Search titles, projects, or messages…`,transcriptSearchRecent:`Recent conversations`,transcriptSearchSessions:`Conversations`,transcriptSearchMessages:`Message contents`,transcriptSearchSessionResult:`Open conversation {{session}}`,transcriptSearchSessionOpenFailed:`Could not open this conversation. Try again.`,transcriptSearchIncludeArchived:`Include archived conversations`,transcriptSearching:`Searching messages…`,transcriptSearchEmpty:`No matching messages found.`,transcriptSearchFailed:`Could not search messages. Try again.`,transcriptSearchRetry:`Retry search`,transcriptSearchPartial:`Some history could not be searched. Results may be incomplete.`,transcriptSearchOpenFailed:`This message could not be opened. It may have moved or belong to another branch.`,transcriptSearchResult:`Open message from {{source}} in {{session}}`,transcriptSearchSource_user:`you`,transcriptSearchSource_assistant:`assistant`,transcriptSearchSource_tool_call:`tool call`,transcriptSearchSource_tool_result:`tool output`,connected:`Connected`,connecting:`Connecting`,conversationName:`Conversation name`,conversationOptions:`Conversation options`,sidebarRename:`Rename`,sidebarPin:`Pin`,sidebarUnpin:`Unpin`,sidebarFork:`Fork`,sidebarForkLocal:`Fork chat`,sidebarForkSameWorktree:`Fork in same worktree`,archiveNoticeTitle:`Chat archived`,archiveNoticeView:`View`,archiveNoticeUndo:`Undo`,archiveNoticeFailed:`Could not complete this action. Try again.`,sidebarForkWorktree:`Fork chat in new worktree`,sidebarForkCancelling:`Requesting cancellation…`,sidebarForkFinishing:`Cancellation is no longer available. Confirming the result…`,sidebarForkCancelUnconfirmed:`Cancellation could not be confirmed. Waiting for the fork result.`,sidebarForkWorktreePreserved:`The worktree was kept at {{path}}. Inspect it before retrying.`,sidebarForkWorktreePending:`Creating a worktree and conversation…`,sidebarForkOptionsLoading:`Checking worktree availability…`,sidebarForkOptionsFailed:`Unable to check worktrees. Reopen menu to retry.`,sidebarForkUnavailable:`Send a message before forking this conversation.`,sidebarForkArchived:`Restore this conversation before forking.`,sidebarForkFailed:`Could not create the fork. The original conversation is unchanged.`,sidebarCopy:`Copy`,sidebarCopyLink:`Copy conversation link`,sidebarCopyMarkdown:`Copy as Markdown`,sidebarCopyCwd:`Copy working directory`,sidebarCopied:`Copied`,sidebarCopyFailed:`Could not copy. Try again.`,sidebarNewWindow:`Open in new window`,sidebarOpenIn:`Open in`,sidebarAppsLoading:`Loading available apps…`,sidebarAppsFailed:`Unable to load apps. Reopen menu to retry.`,sidebarOpenFailed:`Unable to open this project in the selected app.`,sidebarArchive:`Archive`,sidebarRestore:`Restore`,sidebarDelete:`Permanently delete`,managedWorktreeRecoveryFull:`Check earlier unfinished removal requests before starting another.`,managedWorktreesChanged:`The worktree list changed. Refresh it before reviewing a target.`,managedWorktreesRefresh:`Refresh worktrees`,managedWorktreesBack:`Back to worktrees`,managedWorktreesRetry:`Retry request`,managedWorktrees:`Retained worktrees`,managedWorktreesDescription:`Worktrees created by OpenPI are kept when a conversation is deleted. Review an exact path before requesting removal. Active, shared, changed or unverified worktrees stay in place.`,managedWorktreeConfirm:`Remove this managed worktree? The server rechecks ownership, active conversations and local changes before removal.`,managedWorktreeRemoved:`Worktree removed.`,managedWorktreePreserved:`Worktree kept:`,managedWorktreeUncertainTerminal:`Removal outcome is uncertain. Automatic removal cannot be repeated. Inspect the retained path before taking further action.`,managedWorktreeUncertain:`Removal outcome is unknown. Retry to check the original request.`,managedWorktreeRemoving:`Checking and removing…`,managedWorktreeRemove:`Remove worktree`,managedWorktreeReview:`Review removal`,managedWorktreesEmpty:`No managed worktrees were found on this page.`,managedWorktreesUnavailable:`{{count}} ownership records could not be verified.`,managedWorktreesLoadFailed:`Could not load retained worktrees. Retry without changing the target.`,managedWorktreesMore:`Load more worktrees`,managedWorktreeRetainedAfterDelete:`Conversation deleted. Worktree kept at {{path}}. Review retained worktrees in the project menu.`,sidebarDeleteTitle:`Delete conversation?`,sidebarDeleteDescription:`Permanently delete “{{name}}”? This cannot be undone.`,sidebarDeleteConfirm:`Delete`,sidebarDeleting:`Deleting…`,sidebarDeleteFailed:`Could not delete this conversation. Retry or cancel.`,sidebarActionRunning:`Let current work and queued messages finish first.`,sidebarActionDisconnected:`Reconnect before changing this conversation.`,sessionDeleteCancelled:`Deletion cancelled`,sessionDeleteUncertain:`Could not confirm whether the conversation was deleted. Refresh and try again.`,sessionDeleted:`Conversation permanently deleted`,sessionDeleteMetadataPending:`The conversation was deleted, but its sidebar records could not be fully cleared.`,sessionLinkUnavailable:`The linked conversation no longer exists or its identity has changed.`,sidebarDropPin:`Drop here to pin`,sidebarDropProjectLast:`Move project to the end`,conversationTurns:`Conversation turns`,conversationTurnPosition:`Go to turn {{position}}`,turnPreviewLoading:`Loading preview…`,turnPreviewUnavailable:`Preview unavailable. Try again.`,commands:`Slash commands`,addContext:`Add context`,fileReference:`Reference workspace file`,fileReferenceTitle:`Reference workspace file`,fileReferenceDetail:`Add a path reference to the prompt without uploading file contents.`,fileReferenceLabel:`Workspace file path`,fileReferencePlaceholder:`src/app.tsx`,fileReferenceValidatedHint:`The current Session verifies that this is a readable workspace file.`,fileReferenceDraftHint:`This path will be resolved by Pi after the new Session starts.`,fileReferenceChecking:`Checking…`,fileReferenceFailed:`Could not verify this file.`,fileReferenceDenied:`Choose a file inside the current Session workspace.`,fileReferenceMissing:`This workspace file no longer exists.`,fileReferenceUnsupported:`Only regular workspace files can be referenced.`,fileReferenceExpired:`The active Session changed. Reopen the file reference and try again.`,fileReferenceBusy:`File validation is busy. Try again shortly.`,insertReference:`Insert reference`,commandsSessionRequired:`Slash commands are available after the Session starts.`,commandsEmptyDraftOnly:`Slash commands can be inserted only into an empty draft.`,commandsLoading:`Loading commands...`,commandsUnavailable:`Commands are temporarily unavailable.`,commandsNoMatch:`No matching commands.`,commandsNoAvailable:`No discovered commands can run in Web. Type a command name to inspect its availability.`,commandsBounded:`{{count}} more commands are not shown.`,commandSessionRequired:`Commands require an active Web session.`,commandUnsupported:`Not adapted · manual commands still reach Pi`,commandAcceptsArguments:`Accepts arguments`,commandSource_extension:`Extension`,commandSource_prompt:`Prompt template`,commandSource_skill:`Skill`,copiedMessage:`Copied`,copyMessage:`Copy message`,copyFailed:`Copy failed. Please select and copy the message manually.`,copiedCode:`Code copied`,copyCode:`Copy code`,copyCodeFailed:`Could not copy this code. Select and copy it manually.`,codeBlock:`Code block`,deleteWorkspace:`Delete workspace`,describeTask:`Describe a task`,editMessage:`Edit and rerun from here`,enterHint:`Enter to send, Shift+Enter for a new line.`,expandSidebar:`Expand sidebar`,importWorkspace:`Import workspace`,loadingModels:`Loading models...`,modelsTruncated:`Showing {{shown}} models. {{omitted}} more are available; search to find them.`,searchModels:`Search available models`,searchModelsPlaceholder:`Search provider, model name, or ID...`,searchingModels:`Searching models...`,noMatchingModels:`No matching models`,modelSearchFailed:`Could not search models. Try again.`,retryModelSearch:`Retry model search`,fileReferenceDraftChanged:`The draft changed. Reopen the file reference.`,modelSearchTruncated:`{{omitted}} matching models are not shown.`,modelPreparing:`Preparing task...`,modelRetrying:`Retrying model request...`,modelRunning:`Working...`,modelRequestFailed:`Model request failed`,modelRequestStopped:`Model request stopped`,modelFailureUnknown:`The provider did not return an error reason.`,retryPrompt:`Retry prompt`,retryingPrompt:`Retrying...`,newSession:`New session`,noConversations:`No conversations yet`,noMatching:`No matching conversations`,noMatchingLoaded:`No matching conversations in the loaded history`,noModels:`No models available`,noOutput:`no output`,noSessions:`No sessions`,openSidebar:`Open sidebar`,promptMessage:`Send a message or start a task, / for commands`,promptReadonly:`A non-active session cannot receive prompts`,promptStart:`Choose a workspace to begin.`,promptTask:`Describe what you want to build.`,landingTagline:`Small harness. Clean context. Deep extensions.`,queuedHint:`The message will be queued after the current turn.`,reconnecting:`Reconnecting`,removeWorkspace:`Remove from sidebar`,workspaceOptions:`Workspace options`,renameFailed:`Could not save the name. Your changes were kept.`,savingName:`Saving...`,workspaceRemoveFailed:`Could not remove the workspace. Try again.`,removingWorkspace:`Removing...`,renameConversation:`Rename conversation`,renameWorkspace:`Rename workspace`,save:`Save`,searchConversations:`Search conversations`,searchPlaceholder:`Filter titles and workspaces…`,selectModel:`Select model`,configureModels:`Configure models`,openModelSettings:`Model settings`,selectThinking:`Select thinking level`,resetThinking:`Restore the opening level ({{level}})`,modelThinkingNotEnabled:`Thinking is not enabled for this model. Enable reasoning support in model settings if your provider supports it.`,providerReasoningHint:`Enable only if the provider supports reasoning. Available levels come from Pi; adjust the level in the composer.`,providerImageHint:`When Image is unchecked, the model will not receive image attachments.`,selectWorkspace:`Select workspace`,send:`Send`,processDetails:`Execution details`,processRunning:`Working`,processThinkingCount_one:`{{count}} reasoning note`,processThinkingCount_other:`{{count}} reasoning notes`,processToolCount_one:`{{count}} tool call`,processToolCount_other:`{{count}} tool calls`,processActivityCount_one:`{{count}} agent activity`,processActivityCount_other:`{{count}} agent activities`,switchingSession:`Switching session...`,thinkingActive:`Thinking...`,thinkingActiveLevel:`Thinking ({{level}})...`,thinkingDone:`Thinking`,thinkingLoadFull:`Load full thinking`,thinkingLoadingFull:`Loading thinking…`,thinkingLoadFailed:`Unable to load thinking. Retry`,thinkingPartialText:`Showing part of the saved thinking. More text can be loaded below.`,thinkingPreviewOnly:`Thinking preview reached its limit. The full saved text will be available when this message finishes.`,toolState_running:`Running`,toolState_returned:`Returned`,toolState_failed:`Failed`,toolState_cancelled:`Stopped`,toolState_timed_out:`Timed out`,toolState_unknown:`Unconfirmed`,toolSnapshotMissingResult:`No result at fork`,toolActivity_running:`{{action}}…`,toolActivity_failed:`{{action}} failed`,toolActivity_cancelled:`{{action}} stopped`,toolActivity_timed_out:`{{action}} timed out`,toolActivity_unknown:`{{action}}`,toolAction_read:`Read`,toolAction_write:`Write file`,toolAction_edit:`Edit file`,toolAction_command:`Run command`,toolAction_search:`Search`,toolAction_list:`List files`,toolAction_web:`Browse web`,toolAction_agent:`Agent activity`,toolAction_workflow:`Workflow`,toolAction_plan:`Prepare plan`,toolAction_task:`Update tasks`,toolAction_goal:`Update goal`,toolAction_git:`Review changes`,toolAction_call:`Use tool`,toolActionDone_read:`Read`,toolActionDone_write:`Wrote file`,toolActionDone_edit:`Edited`,toolActionDone_command:`Ran command`,toolActionDone_search:`Searched`,toolActionDone_list:`Listed files`,toolActionDone_web:`Browsed web`,toolActionDone_agent:`Agent activity returned`,toolActionDone_workflow:`Workflow tool returned`,toolActionDone_plan:`Plan tool returned`,toolActionDone_task:`Task tool returned`,toolActionDone_goal:`Goal tool returned`,toolActionDone_git:`Reviewed changes`,toolActionDone_call:`Used tool`,toolActionGroup_read:`read files`,toolActionGroup_write:`write files`,toolActionGroup_edit:`edit files`,toolActionGroup_command:`run commands`,toolActionGroup_search:`search`,toolActionGroup_list:`list files`,toolActionGroup_web:`browse web`,toolActionGroup_agent:`agent activity`,toolActionGroup_workflow:`workflow activity`,toolActionGroup_plan:`planning`,toolActionGroup_task:`tasks`,toolActionGroup_goal:`goal`,toolActionGroup_git:`review changes`,toolActionGroup_call:`use tools`,toolGroup_done:`Activity · {{actions}}`,toolGroup_running:`Working · {{actions}}`,toolGroup_unknown:`Activity · {{actions}}`,toolGroupSeparator:`, `,toolSearchTarget:`“{{pattern}}” · {{path}}`,toolDiffStatsHelp:`Added and removed lines in the displayed diff`,toolRequestedFile:`File:`,toolWorkspace:`Workspace`,toolRawEvidence:`Arguments and original result`,toolCodemodeDetails:`Script and original result`,toolNestedOutputMissing:`This session records the call and its status, but not the nested tool output.`,toolNestedArgumentsMissing:`This session omits the full arguments and nested tool output.`,toolNestedIncomplete:`The nested-call record is incomplete; some calls, arguments or final states are unavailable.`,toolPartialEvidence:`Partial output: a byte, line or item limit was reached. The original result may also be truncated.`,toolFileChange_created:`File created`,toolFileChange_unchanged:`No content changes`,toolFileChange_overwritten:`File overwritten`,toolChangeUnavailable:`This result does not include a change comparison.`,toolTestResults:`Reported test results · {{format}}`,toolTestCounts:`{{tests}} tests · {{passed}} passed · {{failed}} failed · {{cancelled}} cancelled`,toolTestCountsHelp:`Counts come from command output. The execution status is shown separately.`,toolReadMore:`Read another range using the path and offset. The original result contains continuation details.`,toolFullOutputReference:`Full output:`,subagentBackgroundResult_one:`Background subagent result · {{count}}`,subagentBackgroundResult_other:`Background subagent results · {{count}}`,thinkingDraftHint:`Choose a workspace and create a session first.`,thinkingInactiveHint:`Only the active session can change its thinking level.`,thinkingLevelMismatch:`The confirmed thinking level is not offered by the current model. Choosing another level will correct it.`,thinkingLockedRunning:`Stop the current turn before changing the thinking level.`,thinkingModelPendingHint:`Wait for the model change to finish.`,thinkingNotConfirmed:`Thinking level was not confirmed. Please try again.`,thinkingPendingHint:`Applying the thinking level...`,thinkingUnsupported:`Thinking is unavailable`,thinkingUnsupportedHint:`No model is selected, or the current model does not support thinking.`,unavailable:`Unavailable`,ungrouped:`Ungrouped`,untitledSession:`New session`,workspaceDeleteConfirm:`The folder and conversation records will be kept. Its conversations will move to Ungrouped.`,workspaceName:`Workspace name`,workspaces:`Workspaces`,sidebarProjects:`Projects`}},zh:{translation:{promptPending:`正在处理请求…`,commandFeedbackTruncated:`这里只显示部分命令结果。请缩小查询范围,或在 TUI 查看完整输出。`,planMode_inactive:`普通模式`,planMode_planning:`规划中 · 禁止写入`,planMode_ready:`计划就绪 · 等待审阅`,planMode_invalid:`计划状态异常 · 禁止写入`,planModeEnter:`进入规划`,promptPlanMessage:`本次对话使用 Plan 模式 · 继续讨论计划,暂不实施`,planModeUnconfirmed:`暂时无法确认 Plan 状态,请刷新后再继续。`,planModeExit:`退出规划`,planModeImplement:`准备实施提示`,planImplementationReplaceDraft:`准备实施会替换当前草稿并关闭规划模式,但不会发送提示词。是否继续?`,commandSupport_plan:`支持规划和准备当前会话的实施提示;新建实施会话仍需使用 TUI。`,commandSupport_setup:`通过当前模型配置,在 Web 回答问题。`,handoffWaiting:`需要你操作`,handoffDone:`已完成`,handoffUnable:`无法完成`,handoffDoneHelp:`已执行操作,接下来由模型验证结果。`,handoffUnableHelp:`未能完成,可以补充遇到的障碍。`,handoffReview:`复核状态`,handoffSubmit:`提交状态`,handoffSignal:`预期结果:`,handoffVerify:`提交完成后,模型仍需验证结果;你的反馈本身不代表验证成功。`,planCardLabel:`开发计划`,planCardReady:`计划已就绪`,planCardResult:`计划结果`,planCardNotApproval:`此步骤仅生成计划,不代表已批准或开始实施。`,planCardCollapse:`收起`,planCardExpand:`展开`,planCardCopy:`复制计划`,planCardCopyPreview:`复制可见预览`,planCardTruncated:`当前仅显示截断预览。`,planCardLoadFull:`加载完整计划`,planCardLoadingFull:`正在加载计划...`,planCardLoadFailed:`无法加载完整计划,重试`,planCardEvidence:`工具结果 · plan_ready`,questionWaiting:`问题`,questionPreview:`查看预览`,questionSkip:`跳过`,questionProgress:`{{current}} / {{total}}`,questionReview:`复核答案`,questionReviewTitle:`确认这些选择?`,questionReviewHelp:`可以返回修改,点击提交后才会发送给助手。`,questionEdit:`修改答案:{{question}}`,questionDismiss:`关闭提问,不提交答案`,questionCustom:`或自行撰写回复`,questionCustomHelp:`留空提交,表示希望助手把问题说清楚或拆小。`,questionYourAnswer:`你的答案`,questionCustomPlaceholder:`说说你的想法…`,questionNotes:`补充说明(选填)`,questionNotesPlaceholder:`补充限制条件,或解释你的选择…`,questionRephrase:`请助手把问题说清楚或拆小`,questionBack:`上一步`,questionNext:`下一题`,questionSubmit:`提交答案`,questionSubmitting:`正在提交…`,questionRetry:`核对提交结果`,questionUncertain:`暂时无法确认是否送达,已保留本次提交的答案。点击核对可恢复结果,不会重复提交。`,questionDisconnected:`正在重新连接… 已保留你的选择,暂时无法提交。`,questionLimit:`每项答案或补充说明不能超过 {{count}} 个 UTF-8 字节。`,questionLoadFailed:`暂时无法读取等待回答的问题。`,questionDraftLimit:`提问草稿已达上限,请缩短或清空已有答案后再添加内容。`,questionRetryLoad:`重试`,questionCloseReceipt:`关闭问答状态提示`,questionState_dismissed:`已关闭提问,没有提交答案。`,questionState_cancelled:`提问已取消,没有提交答案。`,questionState_expired:`提问已过期,没有提交答案。`,questionState_stale:`该提问已失效,请查看对话中的处理结果。`,conversationView:`会话视图`,jumpToLatest:`跳至最新`,historyLoading:`正在加载历史…`,historyOmitted:`还有 {{count}} 条较早记录 · 向上滚动自动加载`,historyChanged:`会话分支已更改,已切换到当前分支的历史。`,historyUnavailable:`历史记录加载失败,请重试。`,historyValidationUnavailable:`无法校验会话历史,请重试。`,historyVerifying:`正在校验会话历史…`,messageLoadFull:`加载完整消息`,messageLoadMore:`加载更多`,messageLoadingFull:`正在加载消息…`,messageLoadFailed:`无法加载这条消息,重试`,filePreview:`文件预览`,changeEvidence:`变更`,changeEvidenceScope:`按所选范围查看当前工作目录的只读 Git 变更。`,turnLabel:`第 {{number}} 轮`,turnState_running:`运行中`,turnState_complete:`已完成`,turnState_failed:`失败`,turnState_interrupted:`已中断`,turnState_waiting:`等待回复`,turnState_forked:`已分叉,可继续对话`,turnChanges:`本轮更改 {{count}} 个文件`,turnChangesPartial:`本轮已记录 {{count}} 个文件`,turnChangesIncomplete:`这一轮的变更记录不完整。`,turnChangesMore:`再显示 {{count}} 个文件`,turnChangesLess:`收起文件`,turnChangesReview:`审阅本轮变更`,turnChangesReviewButton:`审阅`,turnChangesBack:`返回本轮变更`,turnChangesLoading:`正在加载本轮变更…`,turnChangesUnavailable:`无法读取本轮保存的差异。`,messageCopyRequiresFull:`加载完整消息后才能复制。`,filesChanged:`{{count}} 个文件已更改`,reviewChanges:`查看变更`,workspaceChanges:`工作区更改`,overviewChanges:`变更`,overviewLineTotals:`当前 Git 比较范围内的文本新增与删除行数`,overviewPartialTotals:`仅展示已核实的行数,部分文件尚无法统计。点击变更查看详情。`,overviewCounting:`统计中…`,overviewCountsUnknown:`行数未知`,overviewReviewUnavailable:`暂不可用`,sessionSources:`来源`,sourcesAdd:`添加来源`,sourcesEmpty:`暂无来源`,sourcesFailed:`来源加载失败。`,sourcesViewAll:`查看全部`,sourcesLoadMore:`加载更多来源`,sourcesBack:`返回来源列表`,sourcesPartial:`已达到列表展示上限,更早的来源仍可在对话中查看。`,turnChangesScope:`该轮开始至结束的工作区差异 · 已保存`,turnEdits:`已编辑 {{count}} 个文件`,turnEditsPartial:`已记录 {{count}} 个文件的编辑`,turnEditsScope:`本轮文件工具写入记录 · 已保存;不含命令行与外部修改`,turnEditStatsUnknown:`行数未知`,turnEditReason_before_unavailable:`文件已写入,但该操作未授权读取旧内容,无法提供可靠的前后差异。`,turnEditReason_content_limit:`文件已写入,内容超过已保存对比的大小限制,无法提供准确行数。`,turnEditReason_concurrent_change:`文件在已记录的操作之间发生了变化,无法确认本轮净增删行数。`,gitReviewLoadedCount:`已载入 {{count}} 个文件`,gitReviewPartialLabel:`部分`,gitReviewSearch:`搜索文件路径`,gitReviewExpand:`展开审阅`,gitReviewSearchLoaded:`搜索已载入文件`,gitReviewMarkViewed:`标记 {{path}} 为已查看`,gitReviewMarkCurrentViewed:`标记当前文件 {{path}} 为已查看`,gitReviewViewedLabel:`已查看`,gitReviewViewedProgress:`已查看 {{viewed}} / 已加载 {{loaded}} 个文件`,gitReviewViewedLimit:`本次对比最多保留 {{count}} 个已查看标记。`,gitReviewNoMatch:`没有匹配的文件。`,gitReviewNoLoadedMatch:`已载入文件中没有匹配项。`,gitReviewLoadNext:`载入下一批文件`,gitReviewChanged:`工作区已有变化,请刷新清单后继续载入。`,gitReviewNewVersion:`有新的更改,当前仍显示你正在阅读的版本。`,gitReviewShowLatest:`查看最新差异`,gitReviewBinary:`此二进制文件无法显示文本差异。`,gitReviewBinaryShort:`二进制`,gitReviewPendingStats:`待读取`,gitReviewComparison:`{{current}} 对比 {{base}}`,gitReviewWorkingTree:`工作区对比 HEAD`,gitReviewSessionSnapshot:`自本会话开始后的变更`,gitReviewDetached:`游离 HEAD`,gitReviewLoading:`正在读取 Git 变更…`,gitReviewRetry:`重试`,gitReviewRefresh:`刷新变更`,gitReviewOlderResult:`当前显示上一次读取结果。`,gitReviewNotRepository:`此工作区不是 Git 仓库。`,gitReviewUnborn:`此仓库还没有可读取的 HEAD。`,gitReviewFailed:`无法读取 Git 变更。`,gitReviewTruncated:`结果不完整,部分文件或差异未载入。`,gitReviewEmpty:`当前范围内没有文件变更。`,gitReviewHiddenLines:`另有 {{count}} 行 diff 未显示。`,gitReviewDiffTruncated:`快照已达到大小上限,未加载此文件的 diff。`,gitReviewShowMore:`再显示 {{count}} 个文件`,gitReviewBackToFiles:`返回变更文件`,gitReviewFilePreview:`{{file}} 的差异`,gitReviewNoDiff:`此文件没有可显示的文本差异。`,changeDiff:`变更差异`,diffView:`差异`,gitFileStatus_added:`已新增`,gitFileStatus_modified:`已修改`,gitFileStatus_deleted:`已删除`,gitFileStatus_renamed:`已重命名`,gitFileStatus_copied:`已复制`,gitFileStatus_untracked:`未跟踪`,gitFileStatus_unknown:`已变更`,closePreview:`关闭预览`,artifactReadOnly:`只读`,artifactReferenceUnavailable:`此视图无法打开文件预览:{{path}}`,artifactSession:`所属会话 {{sessionId}}`,copyFilePath:`复制文件路径`,filePathCopied:`已复制文件路径`,refreshFile:`刷新文件`,downloadFile:`下载文件`,downloadingFile:`正在下载…`,artifactOlderPreview:`当前显示旧版预览。`,readingFile:`正在读取文件…`,artifactVersion:`版本`,artifactBytes:`{{count}} 字节`,artifactPreviewTruncated:`预览已截断;下载文件可获取完整内容。`,artifactUnsupported:`此类型无法预览,请下载文件。`,chatView:`对话`,trajectory:`执行轨迹`,trajectoryScope:`按记录顺序展示会话消息,不表示执行耗时,也不是完整模型请求。`,trajectoryRunning:`任务仍在进行。已保存记录到达后自动更新;实时生成内容可在“对话”中查看。`,trajectoryTruncated:`当前历史不完整:省略 {{entries}} 条记录、{{parts}} 个内容片段,{{messages}} 条消息被截断。`,trajectoryEmpty:`尚无已保存记录。`,trajectoryOrder:`记录顺序`,trajectoryRecordCount:`{{count}} 条记录`,trajectoryMatches:`{{count}} 条匹配`,trajectorySearch:`搜索已加载记录`,trajectoryNoMatches:`没有匹配的记录。`,trajectoryEarlierGroup:`较早上下文`,trajectoryEventCount:`{{count}} 条会话变更`,trajectorySummary:`概览`,trajectoryInputTab:`输入`,trajectoryResultTab:`结果`,trajectoryConversationGroup:`本轮对话`,trajectoryReasoningTitle:`思考`,trajectoryRecordNumber:`记录 {{number}}`,trajectoryRecordInfo:`记录信息`,trajectoryRecordId:`记录 ID`,trajectoryCallId:`工具调用 ID`,trajectoryEventType:`事件类型`,trajectoryEvent_model_change:`切换模型`,trajectoryEvent_thinking_level_change:`调整思考级别`,trajectoryEvent_compaction:`压缩上下文`,trajectoryEvent_session_info:`更新会话信息`,trajectoryEvent_custom:`会话记录`,trajectoryEarlier:`显示更早记录(已加载历史中还有 {{count}} 条)`,trajectoryDetails:`记录详情`,trajectoryRecordedAt:`记录时间`,trajectoryEvidenceTruncated:`此证据在会话投影中已被截断。`,trajectoryArguments:`工具参数`,trajectoryRecordedContent:`已记录内容`,trajectoryThinking:`模型返回的推理内容`,trajectoryOutput:`工具结果`,trajectoryMissingResult:`当前记录中没有可明确配对的结果。这不表示工具仍在运行。`,trajectoryStructured:`结构化结果`,trajectoryEventOnly:`当前仅提供此事件的类型和记录时间。`,trajectory_user:`用户消息`,trajectory_assistant:`助手回复`,trajectory_call:`工具调用`,trajectory_result:`未配对结果`,trajectory_event:`会话事件`,trajectory_returned:`工具已返回结果。`,trajectory_error:`工具返回错误`,trajectory_unknown:`尚无法确定结果`,runtimeStatus:`运行状态`,refreshStatus:`刷新状态`,terminalDetails:`终端详情`,openTools:`打开工具`,sideConversation:`侧边对话`,sideConversationDescription:`在独立 Pi 会话中追问具体问题,不打断当前主任务。`,workbarChangesDescription:`查看当前目录的未暂存、已暂存、分支或会话变更。`,terminal:`终端`,renameTerminal:`重命名终端`,terminalName:`终端名称`,workbarTerminalDescription:`打开当前工作区的交互式终端。`,backgroundTerminalActivity:`Agent 命令活动`,restartTerminal:`重新启动终端`,reconnectTerminal:`重新连接终端`,restartTerminalTitle:`重新启动此终端?`,restartTerminalDetail:`当前终端会被关闭,其中运行的进程可能被中断。`,terminalReconnecting:`正在重新连接终端...`,terminalScrollToBottom:`回到底部`,terminalOutputResynced:`终端输出已重新同步`,terminalRestarting:`正在重新启动终端...`,terminalConnecting:`正在启动终端…`,terminalExited:`终端已退出。`,terminalExitCode:`终端已退出,状态码 {{code}}。`,terminalDisconnected:`终端连接意外中断。`,terminalError:`终端不可用。`,browser:`浏览器`,sessionFileRecords:`本会话文件记录`,gitReviewSource:`变更范围`,gitReviewBaseBranch:`对比分支`,gitReviewChooseBase:`选择对比分支`,gitReviewSearchBranches:`搜索分支`,gitReviewLocalBranch:`本地分支`,gitReviewRemoteBranch:`远程分支`,gitReviewBranchesTruncated:`显示有数量限制的分支列表,部分分支已省略。`,gitReviewNoMatchingBranches:`没有匹配的分支。`,gitReviewBaseUnavailable:`没有可用的默认对比分支。请选择分支以审阅已提交的变更。`,gitReviewBaseInvalid:`所选对比分支已不可用,请选择其他分支。`,gitReviewUnstaged:`未暂存(含未跟踪)`,gitReviewStaged:`已暂存变更`,gitReviewBranch:`分支变更`,gitReviewFileMissing:`此文件在当前范围内已无变更,请刷新文件列表。`,artifactExternalAccess:`此文件位于其他工作目录。可为当前会话授权只读打开这一个文件,不会开放其他文件的访问。`,artifactAuthorizeFile:`只读打开此文件`,sideConversationPending:`正在准备侧边会话…`,resizeSidebar:`调整侧边栏宽度`,resizePanes:`调整面板宽度`,resizeWorkbar:`调整工具栏宽度`,browserPasteTooLarge:`每次最多粘贴 {{count}} 个字符。`,browserInputTooLarge:`每次最多输入 {{count}} 个字符。`,browserInputTargetChanged:`输入目标已变化或无法确认,有输入操作未执行。`,workbarBrowserDescription:`在 OpenPI 工作栏内打开并操作网页。`,browserReady:`输入地址开始浏览`,browserStarting:`正在启动内嵌浏览器…`,browserOpened:`已在内嵌浏览器中打开`,browserOpenAgain:`再次打开`,browserOpenFailed:`内嵌浏览器暂不可用。`,browserBack:`后退`,browserForward:`前进`,browserReload:`重新加载`,browserTabs:`网页标签页`,browserNewTab:`新标签页`,browserAddTab:`新建网页标签页`,browserCloseTab:`关闭 {{title}}`,browserTabLimit:`最多打开 {{count}} 个网页标签页`,browserPageTitle:`网页:{{address}}`,browserEnteredAddress:`最近从此地址栏打开的地址`,browserAddressNotAllowed:`请输入不含用户名或密码、且不属于 OpenPI 自身地址的 HTTP(S) 网址。`,browserLocationUnknown:`网页已跳转,新地址无法读取。重新加载会返回你输入的地址。`,browserDirectDescription:`直接浏览网页。不允许嵌入的网站可在外部浏览器打开。`,browserDirectHint:`地址栏仅记录手动打开的地址。网页弹窗在外部浏览器打开;遇到空白页,可点击外部打开。`,browserEnhancedHint:`浏览增强已开启:地址自动同步,普通弹窗链接在内部标签页打开。部分站点限制、登录弹窗和跨站历史仍需外部浏览器。`,files:`文件`,filesExplorer:`工作区文件`,filesSearch:`筛选文件…`,refreshFiles:`刷新文件`,filesWorkspaceActions:`工作区文件操作`,filesCreateMenu:`新建`,filesImportMenu:`导入`,filesMoreMenu:`更多`,filesNewFile:`新建文件`,filesNewDirectory:`新建文件夹`,filesImport:`导入文件`,filesImportFolder:`导入文件夹`,filesImportFolderChoose:`选择要导入的文件夹`,filesImportFolderLimit:`每次最多导入 2,000 个文件和文件夹,目录层级最多 64 层。`,filesSelectMultiple:`多选文件`,filesSelectItem:`选择 {{name}}`,filesSelectedCount:`已选 {{count}} 项`,filesRename:`重命名`,filesNewName:`新名称`,filesMove:`移动`,filesMoveDestination:`目标文件夹(工作区内相对路径)`,filesTrashAction:`移入回收站`,filesTrash:`工作区回收站`,filesTrashDetail:`移除的文件保留在当前工作区,可恢复;不会覆盖同名文件。`,filesTrashEmpty:`暂无已移除文件`,filesTrashUnavailable:`{{count}} 项记录无法核验,内容仍保留在 .openpi-trash 中,暂不能自动恢复。`,filesRestore:`恢复`,filesRestoreItem:`恢复 {{name}}`,filesUndoTrash:`撤销移除`,filesOrganizationResults:`文件操作结果`,filesOperationDone:`完成`,filesRefreshBeforeOrganizing:`请先刷新文件树,再整理这项文件。`,filesImportChoose:`选择要导入的文件`,filesTargetDirectory:`目标目录`,filesWorkspaceRoot:`工作区根目录`,filesFileName:`文件名称`,filesDirectoryName:`文件夹名称`,filesCreate:`创建`,filesCreating:`创建中…`,filesCreated:`已创建:{{path}}`,filesNameInvalid:`请输入单个文件或文件夹名称,不要包含路径分隔符。`,filesNameExists:`此名称已存在,请更换名称;原有文件已保留。`,filesMutationFailed:`写入失败,输入已保留。`,filesWriteUnavailable:`请先切换到此会话,再修改工作区文件。`,filesImportLimit:`每个文件最多 50 MiB,同名文件不会覆盖。`,filesImportTooLarge:`此文件超过 50 MiB 导入上限。`,filesImportDirectoryUnsupported:`不支持导入整个文件夹,请选择其中的文件。`,filesImportResults:`文件导入结果`,filesImportPending:`等待导入`,filesImporting:`导入中…`,filesImported:`已保存到工作区`,filesImportedNoPreview:`已保存。预览上限为 20 MiB;可复制路径,在对话中引用此文件。`,filesClearImported:`清除已完成的导入`,filesRetryImport:`重试导入`,filesPathActions:`{{name}} 的路径操作`,filesCopyRelativePath:`复制相对路径`,filesCopyAbsolutePath:`复制绝对路径`,filesPathCopied:`已复制路径:{{path}}`,filesReadFailed:`无法读取文件。`,filesSymlink:`符号链接,文件浏览器不会自动跟随`,filesTruncated:`结果不完整,请缩小搜索范围。`,filesNoMatches:`没有匹配的文件`,filesEmpty:`此文件夹为空`,filesChoose:`选择文件进行预览`,filesChooseDetail:`从右侧浏览工作区文件,在这里直接预览。`,filesHideTree:`收起文件树`,filesShowTree:`显示文件树`,filesPreview:`预览`,filesSource:`查看源代码`,filesEdit:`编辑`,filesMode:`文件视图`,filesEditor:`文件编辑器`,filesSave:`保存文件`,filesSaving:`保存中…`,filesSaved:`已保存`,filesUnsaved:`未保存的修改 · 草稿保留在当前窗口`,filesDiscard:`放弃草稿`,filesDiscardConfirm:`放弃此文件尚未保存的修改?`,filesSaveConflict:`磁盘上的文件已改变,编辑草稿已保留。请刷新查看最新内容,核对修改后再保存。`,filesSaveFailed:`保存失败,编辑草稿已保留。请检查文件后重试。`,filesEditLoadFirst:`请先继续读取完整文件,再编辑。`,filesEditUnavailable:`支持编辑工作区内不超过 1 MiB 的 UTF-8 文本,最多保留 16 份未保存草稿。`,filesOutline:`章节目录`,filesDiskVersion:`查看当前磁盘版本`,filesReconcile:`已核对,保留草稿并基于此版本继续编辑`,filesTable:`表格预览`,filesRow:`行`,filesSheets:`工作表`,filesTableTruncated:`当前显示部分表格;下载文件可查看全部行列。`,filesOfficeLayout:`文档内容预览;分页和排版可能与 Office 不同。`,filesSlidesLayout:`幻灯片文字与图片预览;主题、图表和动画可能与 PowerPoint 不同。`,filesPreviousPage:`上一页`,filesNextPage:`下一页`,filesZoomOut:`缩小`,filesZoomIn:`放大`,filesZoomReset:`重置缩放`,filesPdfPage:`第 {{page}} 页`,filesDocumentLimit:`此文档超出预览处理范围,请下载后在本地打开。`,filesPreviewFailed:`无法预览此文件,仍可下载后打开。`,filesDiagram:`Mermaid 图表`,filesExpandDiagram:`放大图表`,filesFitImage:`适应宽度`,filesOriginalImage:`原始尺寸`,filesLoadMore:`加载更多`,filesLoaded:`已加载 {{count}} 项`,filesReadMore:`继续读取`,filesContentChanged:`文件已更新。当前阅读内容已保留,可在准备好后刷新。`,workbarFilesDescription:`浏览工作区文件,在文件树旁直接预览。`,backToSideConversations:`返回侧边对话`,continueSideConversation:`继续追问…`,startSideConversation:`提出一个侧边问题…`,sideConversationModelInherited:`新侧边对话使用主会话的模型与思考等级。`,sideConversationModelFixed:`这是当前侧边对话使用的模型。`,stop:`停止`,start:`开始`,browserAddress:`浏览器地址`,browserGo:`打开地址`,openExternalBrowser:`在外部浏览器打开`,invalidBrowserAddress:`请输入有效的 HTTP 或 HTTPS 地址。`,addImages:`添加图片`,addFiles:`添加文件`,fileAttachments:`文件附件`,previewFileAttachment:`预览文件`,fileAttachmentDescription:`文档、表格、PDF、文本、代码及其他文件`,fileAttachmentCount:`最多可添加 {{count}} 个附件。`,fileAttachmentTooLarge:`文件总大小不能超过 50 MB。`,fileAttachmentReadFailed:`无法读取此文件,请检查格式或是否有密码保护。`,fileAttachmentTextReady:`文本已就绪`,fileAttachmentTextTruncated:`部分文本 · 保留原文件`,fileAttachmentOriginalReady:`原文件已就绪`,fileAttachmentExtractionFailed:`未提取文本 · 原文件保留`,fileAttachmentEncodingUnavailable:`无法读取文本编码,原文件字节已保留。`,fileAttachmentDocumentUnavailable:`无法提取文本。文件可能受密码保护或格式暂不支持,原文件字节已保留。`,fileAttachmentNoText:`发送后,代理可通过工具读取原文件;此文件未提取出文本。`,fileAttachmentPreviewTruncated:`预览显示前 20,000 个字符,发送时会附上全部已提取文本。`,fileAttachmentExtractedContent:`已提取文本`,fileAttachmentPromptLabel:`用户提供的文件:`,fileAttachmentPromptTooLong:`消息和文件引用超过输入限制,请缩短消息或减少附件。`,imageAttachmentDescription:`支持 PNG、JPEG、GIF 或 WebP`,imageAttachments:`图片附件`,imageAttachmentsLoading:`正在准备附件…`,commandOpensPanel:`打开面板`,commandPanelArguments:`此命令用于打开面板,不能携带参数或图片。请移除后重试,或直接使用对应面板。`,commandPanelUnavailable:`未能打开面板,已保留命令。`,commandUnavailable_terminal_only:`需要在 Pi 终端界面中使用。`,commandUnavailable_not_integrated:`此扩展命令尚未接入 Web,请在 Pi 终端中使用。`,artifactImagePreviewFailed:`图片预览失败。请刷新文件重试,或下载后查看。`,artifactFileDetails:`文件信息`,turnElapsedRunning:`已处理 {{duration}}`,compactionElapsed:`已等待 {{duration}}`,compactionRunning:`正在压缩上下文`,compactionCompleted:`上下文已自动压缩`,compactionFailed:`上下文压缩失败`,compactionInterrupted:`压缩已中断`,compactionUnchanged:`压缩已结束,未生成新的摘要`,compactionUnavailable:`上下文压缩状态暂不可用`,compactionReconnectHelp:`连接已中断,恢复连接后将核实当前状态。`,compactionDraftHelp:`正在压缩上下文,发送的消息会排队等待。`,turnElapsedFinished:`用时 {{duration}}`,composerAdd:`添加`,composerCommands:`指令`,composerFile:`文件`,composerGoal:`目标`,composerPlan:`计划`,composerCompact:`压缩`,composerModel:`模型`,composerBack:`返回`,composerGoalDescription:`设置或查看长期任务目标`,composerPlanDescription:`进入或退出计划模式`,composerCompactDescription:`整理之前的对话,释放上下文空间`,composerModelDescription:`选择本会话使用的模型`,compactionQueueWaiting:`等待压缩完成`,compactionQueueBlocked:`消息已保留,可重试或清空队列。`,clearPromptQueue:`清空队列`,turnElapsedOutcome_cancelled:`已停止`,turnElapsedOutcome_failed:`失败`,turnElapsedOutcome_uncertain:`结果待确认`,settingsSetupBusyHint:`Agent 配置需等待当前轮次结束;显示设置可直接调整。`,resetChatContentWidth:`恢复默认聊天宽度`,resetChatFontSize:`恢复默认字体大小`,setupResolveAdmission:`请先返回对话,处理尚未确认的消息,再应用设置。`,removeAttachment:`移除附件`,dropImagesHere:`将文件或图片拖到这里`,imageAttachmentCount:`最多可添加 {{count}} 张图片。`,imageAttachmentTooLarge:`单张图片不能超过 10 MB。`,imageAttachmentTotalTooLarge:`图片总大小不能超过 32 MB。`,imageAttachmentUnsupported:`仅支持有效的 PNG、JPEG、GIF 和 WebP 图片。`,imageAttachmentReadFailed:`无法读取此图片,请重新添加重试;消息内容已保留。`,attachedImage:`已附加图片`,previewAttachment:`预览图片`,closeImagePreview:`关闭图片预览`,imagePreviewFailed:`无法显示这张图片。`,fitImage:`适应窗口`,originalImageSize:`原始尺寸`,imageViewMode:`图片查看`,sessionUsage:`会话 Token 用量`,sessionInputTokens:`输入 Token`,sessionOutputTokens:`输出 Token`,sessionCacheTokens:`缓存 Token`,sessionContextUsage:`上下文占用与窗口大小`,usageContextLabel:`上下文`,usageUnknown:`未知`,usageOpenDetails:`输入 {{input}} · 输出 {{output}} · 上下文 {{percent}} / {{capacity}} · 查看会话用量`,usageContextHelp:`当前分支的估算占用 / 模型上下文容量上限。`,usageSessionTotals:`累计用量`,usageInputLabel:`输入`,usageOutputLabel:`输出`,usageTotalLabel:`总计`,usageWorkspaceLabel:`工作区`,usageSessionId:`会话 ID`,usageTotalsHelp:`本会话累计 Token 用量,包含缓存。`,subagentDetails:`子代理`,sessionOverview:`会话概览`,sessionOverviewChanges:`当前审阅范围的更改`,subagentSummaryRunning:`{{count}} 运行中`,subagentSummaryDone:`{{count}} 完成`,subagentSummaryOther:`{{count}} 其他记录`,subagentNoneYet:`暂无子代理`,subagentOtherGroup:`失败 / 已中断`,subagentShowMore:`再显示 {{count}} 个`,backToSubagents:`返回子代理列表`,subagentActiveGroup:`运行中`,subagentFinishedGroup:`完成`,subagentNoneRunning:`暂无正在运行的子代理。`,subagentNoneFinished:`任务结束后会显示在这里。`,subagentProgress:`子代理:{{running}} 运行中 · {{completed}} 已完成`,subagentSummaryUnknown:`{{count}} 个状态未确认`,subagentTasks:`子代理任务列表`,inspectSubagent:`打开子代理:{{name}}`,subagentState_running:`运行中`,subagentState_done:`已完成`,subagentState_error:`失败`,subagentState_interrupted:`已中断`,subagentStarting:`正在启动…`,subagentSpawnFailed:`启动失败`,subagentStateUnavailable:`已启动 · 状态未保留`,subagentSpawnReceipt:`启动回执`,subagentSpawnReceiptHint:`此回执仅确认启动请求,不表示子代理任务已完成。`,subagentTask:`分配的任务`,subagentTranscript:`子代理对话`,subagentResult:`执行结果`,subagentSaved:`已保存记录`,subagentRecordedState:`最后记录的状态`,subagentSavedHint:`来自当前父会话已保存的回执;结果可能包含同批其他任务,并非子代理的完整实时对话。`,subagentLive:`正在执行 · 自动更新`,subagentReadOnly:`只读查看 · 关闭此面板不会停止任务`,subagentUnavailable:`当前会话已无法提供此子代理的实时详情。启动回执不代表任务已完成。`,subagentStale:`刷新失败,下方保留的是上次收到的状态。`,subagentNoMessages:`暂未收到消息。`,subagentTranscriptUnavailable:`此视图仅保留任务摘要,无法显示完整子代理对话。`,subagentWorkflowsTruncated:`另有 {{count}} 个 workflow 未包含在当前列表中,其任务数量未知。`,subagentState_unknown:`未确认`,subagentUnconfirmedGroup:`未确认`,subagentTruncated:`当前显示有界摘录,已省略 {{count}} 条较早消息,部分文本可能已截短。`,subagentListTruncated:`另有 {{count}} 个任务未包含在当前列表中。`,subagentThinkingRedacted:`服务商已隐藏此段思考内容。`,subagentTool_running:`执行中`,subagentTool_done:`已返回`,subagentTool_error:`失败`,subagentTool_unknown:`结果未保留`,inspectionChanged:`当前会话已切换,请重新打开详情。`,inspectionUnavailable:`暂时无法读取详情。`,inspectionLoading:`正在读取状态…`,thinkingUnavailable:`暂时无法读取思考等级。`,trustUnavailable:`暂时无法读取项目信任状态。`,executionState:`状态`,terminalCommand:`命令`,copyTerminalCommand:`复制命令`,copyVisibleOutput:`复制当前可见{{stream}}`,copySetupCommand:`复制配置命令`,savedTrustDecision:`已保存决定`,activeSessionTrust:`当前会话信任`,trustDecision_trusted:`已信任`,trustDecision_denied:`已拒绝`,trustDecision_undecided:`未决定`,trustDecision_unknown:`未知`,trustActiveYes:`当前会话已信任`,trustActiveNo:`当前会话未信任`,terminalDirectory:`目录`,startedAt:`启动时间`,exitCode:`退出码`,detailTruncated:`部分详情已截断,以限制页面加载量。`,standardOutput:`标准输出`,standardError:`错误输出`,outputTruncated:`此输出视图省略了 {{count}} 字节。`,outputRecovery:`运行时报告已保留日志;此处仅显示有大小限制的片段。`,modelAndThinking:`模型与思考`,selectedModel:`当前模型`,thinkingLevel:`思考等级`,availableThinking:`支持的等级`,unknownState:`未知`,projectTrust:`项目信任`,trust_trusted:`当前会话信任此工作区。`,trust_untrusted:`此工作区的信任已被拒绝。`,trust_restricted:`项目资源受到限制,等待信任决定。`,trust_unknown:`尚无法确定信任状态。`,trustRefreshNeeded:`保存的信任决定与当前会话不同,请通过 Pi 刷新会话后生效。`,providerAvailability:`服务商凭据`,settings:`设置`,settingsNavigation:`设置导航`,generalSettings:`常规`,configurationSettings:`配置`,configurationIntro:`配置工具权限、网络访问与模型响应。`,configurationReadFailure:`无法安全读取配置。请修复设置文件后刷新。`,configurationUserScope:`用户配置`,configurationSetupHint:`响应与搜索选项通过 OpenPI setup 应用`,configurationApproval:`批准策略`,configurationApprovalDetail:`工具审批沿用已安装 Pi 扩展的权限机制。`,configurationPiPermissions:`由 Pi 扩展管理`,configurationSandbox:`沙箱设置`,configurationSandboxDetail:`工具使用宿主进程的权限运行。`,configurationSandboxUnavailable:`未提供 OS 沙箱`,configurationSearchDetail:`允许当前会话模型在支持时访问网络。`,configurationSearchOff:`不向当前模型提供原生搜索。`,configurationSearchOn:`在当前连接支持时允许原生搜索。`,configurationVerbosity:`输出详细程度`,configurationVerbosityDetail:`选择模型回复包含细节的详细程度。`,configurationResponsesUnavailable:`当前连接未使用支持的 Responses 接口。`,configurationVerbosity_default:`模型默认`,configurationVerbosity_low:`简短`,configurationVerbosity_medium:`适中`,configurationVerbosity_high:`详细`,configurationVerbosityHelp_low:`简短直接地回答,减少额外细节。`,configurationVerbosityHelp_medium:`给出必要解释与适量细节。`,configurationVerbosityHelp_high:`提供更完整的解释与细节。`,configurationVerbosityRequest:`只把 response_verbosity 设为 {{value}},保留其他 OpenPI 配置。`,configurationSummary:`推理摘要`,configurationSummaryDetail:`选择向支持的推理模型请求哪种摘要。`,configurationSummaryUnavailable:`当前连接不支持推理摘要。`,configurationSummary_default:`模型默认`,configurationSummary_auto:`自动`,configurationSummary_concise:`简洁`,configurationSummary_detailed:`详细`,configurationSummary_none:`关闭`,configurationSummaryHelp_auto:`由模型自动选择摘要长度。`,configurationSummaryHelp_concise:`请求简洁的推理摘要。`,configurationSummaryHelp_detailed:`请求较详细的推理摘要。`,configurationSummaryHelp_none:`不请求推理摘要;保留当前推理强度。`,configurationSummaryRequest:`只把 response_reasoning_summary 设为 {{value}},保留其他 OpenPI 配置。`,configurationModelFeatures:`模型功能`,configurationReasoningLevels:`可用推理强度`,configurationReasoningDetail:`选择在模型控件中显示哪些受支持的级别。当前级别仍会显示,推理强度不变。`,configurationReasoningCount:`已选择 {{count}} 个`,configurationDependencies:`工作空间依赖项`,configurationEnvironment:`本地运行环境`,configurationEnvironmentDetail:`Node.js、Python 等工具由当前环境提供。OpenPI 不安装捆绑的工作空间运行时。`,configurationRuntimeStatus:`运行状态`,browserSettings:`浏览器`,webSearchSettings:`联网搜索`,webSearchCurrentModel:`当前会话模型`,webSearchNativeDetail:`调用当前模型供应商的原生搜索,复用现有连接和凭据。`,webSearchSupported:`当前连接支持原生搜索。开启后,由模型决定何时联网。`,webSearchUnsupported:`当前连接不支持或尚未确认支持原生搜索,不提供搜索工具,也不会切换到其他供应商。`,webSearchNativeRequest:`开启联网搜索,使用当前会话模型的原生搜索和已有 Pi 凭据。不要切换模型、连接协议或搜索供应商;当前连接不支持或支持情况未知时,不提供搜索工具。`,webSearchIntro:`让模型搜索最新资料,并打开原始网页核实。`,webSearchPackageDetail:`通过可选 Pi 插件提供搜索、网页读取和 PDF 提取。`,webSearchDefaultOff:`默认关闭。可选扩展跟随当前会话模型,无需另填搜索密钥或安装插件。`,webSearchLoaded:`本会话已加载插件`,webSearchNotLoaded:`本会话尚未加载插件`,webSearchSource:`查看插件源码`,webSearchProfile:`搜索设置`,webSearchExa:`Exa — 无需 API 密钥`,webSearchExisting:`保留我已有的搜索偏好`,webSearchProfileHint:`Exa 提供搜索,网页由本机直接读取。已有偏好会原样保留;安装后也可更换搜索服务。`,webSearchEnable:`启用联网搜索…`,webSearchDisable:`关闭联网搜索…`,webSearchConfigure:`更换搜索服务…`,webSearchExaRequest:`启用可选联网搜索,使用 Pi Web Access 和无需 API 密钥的 Exa。让我审阅插件安装确认,保留其他偏好,不要自动重新加载。`,webSearchExistingRequest:`启用可选联网搜索,使用 Pi Web Access,原样保留我已有的搜索偏好。让我审阅插件安装确认,保留其他偏好,不要自动重新加载。`,webSearchDisableRequest:`关闭原生联网搜索。保留其他设置和会话记录。`,webSearchProviderRequest:`帮我更换已安装 Pi Web Access 插件的搜索服务。介绍可用服务与权限,保留无关偏好,密钥留在搜索插件中,不要自动重新加载。`,browserSettingsIntro:`让 OpenPI 阅读网页、点击、输入和截图。`,browserControl:`浏览器控制`,browserControlHint:`提交设置变更请求,保存配置后生效。`,browserDefault:`默认浏览器`,browserDefaultHint:`提交设置变更请求,选择未指定浏览器时使用的默认项。`,browserEmbedded:`OpenPI 内置浏览器`,browserAllowedTitle:`允许使用的浏览器`,browserOffHint:`下方选择将在开启浏览器控制后生效。`,browserConnected:`已连接`,browserNeedsSetup:`需要连接浏览器扩展`,browserNotFound:`未检测到此浏览器`,browserUpdateNeeded:`需要更新扩展`,browserBlocked:`未授权`,browserDefaultBlocked:`当前默认浏览器未获授权,请允许使用或更换默认值。`,browserSetUp:`设置`,browserManage:`管理`,browserSetupNamed:`设置 {{browser}}`,browserManageNamed:`管理 {{browser}}`,browserAllowNamed:`允许使用 {{browser}}`,browserMore:`更多浏览器`,browserSpeakHint:`对话中说“使用 Chrome …”,即可指定这次使用的浏览器。`,browserGuideTitle:`连接 {{browser}}`,browserGuideEyebrow:`跟着做,一次一步`,browserConnectionTitle:`连接状态`,browserCloseGuide:`收起浏览器设置引导`,browserConnectionReady:`连接正常,可选择是否允许 OpenPI 使用。`,browserEmbeddedDetail:`网页在 OpenPI 内打开。部分网站需要使用普通浏览器才能登录或正常显示。`,browserExternalDetail:`OpenPI 可以使用已连接的 {{browser}} 配置中的现有标签和登录状态。请在该配置中保留一个 OpenPI 标签页。`,browserManageExtension:`管理扩展`,browserAllowUse:`允许 OpenPI 使用`,browserMakeDefault:`设为默认`,browserInstallIn:`安装到`,browserInstallTitle:`安装 OpenPI Browser Bridge`,browserSetupSteps:`设置步骤`,browserGuidePopout:`在独立窗口中跟随操作`,browserGuideDetached:`引导已在独立窗口打开,可以对照浏览器设置逐步完成。`,browserShowGuide:`显示引导窗口`,browserGuideInline:`把引导放回这里`,browserGuideBlocked:`未能打开引导窗口。可允许弹出式窗口后重试,也可继续查看这里的步骤。`,browserSafariSettings:`Safari → 设置`,browserSafariDeveloper:`开发者设置`,browserSafariTemporary:`添加临时扩展…`,browserSafariOpenHint:`打开 Safari 后,在菜单栏选择「Safari → 设置」,对照此引导操作。需要 macOS 上的 Safari 26 或更新版本。`,browserSafariDeveloperTitle:`显示 Safari 开发者设置`,browserSafariDeveloperHint:`在「设置 → 高级」中开启「显示网页开发者功能」,再进入「开发者」标签。`,browserSafariLoadHint:`在「开发者」中点击「添加临时扩展」,选择下方文件夹。启用 OpenPI Browser Bridge,允许访问要控制的网站及本地 OpenPI 页面。退出 Safari 后需重新加载临时扩展。`,browserFirefoxThis:`此 Firefox`,browserFirefoxTemporary:`临时载入附加组件…`,browserFirefoxDeveloperTitle:`选择「此 Firefox」`,browserFirefoxDeveloperHint:`在 about:debugging 左侧选择「此 Firefox」。Firefox 不需要开启「开发者模式」开关。`,browserFirefoxLoadHint:`点击「临时载入附加组件」,选择下方文件夹中的 manifest.json。此安装在 Firefox 重启后失效;永久安装需要经过 Mozilla 签名的扩展包。`,browserFirefoxDone:`已选中,下一步`,browserStepCount:`第 {{step}} 步,共 {{total}} 步`,browserStepLabel:`第 {{step}} 步:{{label}}`,browserStepOpen:`打开扩展页`,browserStepAdd:`添加扩展`,browserStepConnect:`连接`,browserOpenManagerTitle:`打开 {{browser}} 扩展页`,browserOpenManagerHint:`从这里开始,我们会帮你打开对应的页面。`,browserOpenManager:`打开 {{browser}} 扩展页`,browserReopenManager:`重新打开扩展页`,browserAlreadyInstalled:`已经安装?直接连接`,browserDeveloperMode:`开发者模式`,browserDeveloperTitle:`开启「开发者模式」`,browserDeveloperHint:`在刚打开的扩展页,找到并开启「开发者模式」开关。`,browserDeveloperDone:`已开启,下一步`,browserIllustration:`操作示意 · 在 {{browser}} 中完成`,browserExtensions:`扩展程序`,browserLoadUnpacked:`加载已解压的扩展程序`,browserLoadHint:`在浏览器中点击「加载已解压的扩展程序」,选择下面的文件夹。`,browserFolderBundled:`已随 OpenPI 准备好`,browserOpenFolder:`打开文件夹`,browserFolderOpened:`扩展文件夹已打开。`,browserPathCopied:`已复制路径`,browserCopyFailed:`未能复制,请选中上方路径手动复制。`,browserChooseFolderMac:`在文件选择窗口按 ⌘ ⇧ G,粘贴路径并回车,再点击「选择」。`,browserChooseFolderOther:`在文件选择窗口的地址栏粘贴路径,再选择该文件夹。`,browserInstalledConnect:`已添加,连接 OpenPI`,browserPreviousStep:`上一步`,browserWaiting:`等待 OpenPI Browser Bridge 连接,连接后会自动进入下一步。`,browserInstallBrowserFirst:`请先安装 {{browser}},或在已安装的浏览器中打开当前 OpenPI 地址。`,browserConnectTitle:`连接 OpenPI`,browserConnectHint:`在 {{browser}} 中打开 OpenPI,使用刚安装扩展的浏览器配置。`,browserOpenIn:`在 {{browser}} 中打开`,browserAllowHint:`连接成功后,可以允许 OpenPI 使用此浏览器。安装扩展不会自动开启浏览器控制。`,browserCheck:`检查连接`,browserNotConnectedYet:`还未连接。请完成安装,在该浏览器中刷新 OpenPI 后再次检查。`,browserHelp:`设置帮助`,browserReloadHint:`已安装旧版?在扩展页重新加载 OpenPI Browser Bridge,再刷新 OpenPI。如浏览器提示权限,请完成其原生确认。`,browserSupportedHint:`Chrome、Edge、Brave、Chromium 145+ 可控制内置页面及普通标签。macOS Safari 26+、Firefox 128+ 通过兼容扩展控制普通标签,嵌套框架需单独打开。Safari、Firefox 的临时安装需在浏览器重启后重新加载。`,browserCopyPath:`复制扩展文件夹路径`,browserLoading:`正在检查浏览器连接…`,browserSaved:`已保存,浏览器权限立即生效。`,browserSaving:`正在保存…`,modelSettings:`模型`,skillsSettings:`技能`,subagentsSettings:`子代理`,pluginsSettings:`插件`,configureOpenPi:`配置 OpenPI`,setupRequestReviewAll:`和我一起检查全部 OpenPI 配置项`,setupRequestSetTheme:`仅将 OpenPI Web 主题设置为 {{value}},其他配置保持不变`,setupRequestSetChatWidth:`仅将 OpenPI Web 聊天内容宽度设置为 {{value}}px,其他配置保持不变`,setupRequestSetChatFontSize:`仅将 OpenPI Web 聊天字体大小设置为 {{value}}px,其他配置保持不变`,setupRequestEnableExpandedThinking:`仅将 OpenPI Web 的思考块改为默认展开,其他配置保持不变`,setupRequestDisableExpandedThinking:`仅将 OpenPI Web 的思考块改为默认折叠,其他配置保持不变`,setupRequestSubagents:`检查并配置 Agent 角色模型和工作流上限`,setupRequestFailed:`OpenPI 配置请求未被接收。`,setupRequestRunning:`正在应用 OpenPI 设置…`,setupRequestAccepted:`配置请求已接收。`,setupPlanBlocked:`Agent 配置需先退出 Plan 模式;显示设置可直接调整。退出不会开始实施计划。`,setupPlanBusy:`Agent 配置需等待当前回合结束并退出 Plan 模式;显示设置可直接调整。`,setupOutcome_pending:`配置请求正在处理,尚未收到保存回执。`,toolCallArguments:`工具参数`,toolCallOutput:`工具结果`,setupOutcome_saved:`OpenPI 配置已保存并应用。`,setupOutcome_unchanged:`配置已保存,实际设置没有变化。`,setupOutcome_failed:`配置请求失败,请查看错误和当前设置后再重试。`,setupOutcome_cancelled:`配置过程已取消,未确认成功保存。`,setupOutcome_unconfirmed:`本次未确认成功保存,请核对当前设置后再运行 /openpi-setup。`,settingsUpdateFailed:`无法保存 Web 显示设置。`,settingsPreferencesSaved:`显示设置已保存。`,settingsPreferencesSaveFailed:`无法保存显示设置,请检查配置诊断后重试。`,settingsCatalogLoading:`正在加载 Pi 资源…`,settingsCatalogFailed:`无法加载 Pi 设置资源。`,appearance:`外观`,settingsPersonal:`个人`,settingsAgent:`Agent`,settingsIntegrations:`集成`,settingsArchivedChats:`已归档聊天`,settingsSearch:`搜索设置`,settingsClearSearch:`清除搜索`,settingsNoResults:`没有匹配的设置`,appearanceVisualStyle:`视觉风格`,appearanceMode:`模式`,appearanceTheme:`主题`,appearanceAccent:`强调色`,appearanceBackground:`背景`,appearanceForeground:`前景`,appearanceFont:`字体`,appearanceFont_codex:`Codex 默认`,appearanceFont_sans:`无衬线`,appearanceFont_serif:`衬线`,appearanceFont_mono:`等宽`,appearanceAccent0:`默认`,appearanceAccent1:`蓝色`,appearanceAccent2:`紫色`,appearanceAccent3:`粉色`,appearanceAccent4:`橙色`,appearanceAccent5:`绿色`,appearanceCustomAccent:`自定义强调色`,appearanceAdvanced:`高级`,appearanceReset:`恢复默认设置`,appearanceResetAction:`重置外观`,appearanceImport:`导入主题`,appearanceCopy:`复制主题`,appearanceCopied:`主题已复制`,appearanceCopyFailed:`无法复制主题,请重试。`,appearanceThemeValue:`主题数据`,appearanceImportPlaceholder:`粘贴 OpenPI 主题…`,appearanceImportInvalid:`请输入有效的 OpenPI 主题数据。`,appearanceImportAction:`导入`,searchArchivedChats:`搜索已归档聊天`,archiveProjectFilter:`按项目筛选`,archiveAllProjects:`所有项目`,archiveProjectGroup:`{{project}} · {{count}} 条归档聊天`,archiveSort:`归档聊天排序`,archiveSortUpdated:`最近更新`,archiveSortCreated:`创建时间`,restoreArchivedChat:`恢复 {{title}}`,themeLight:`浅色`,themeDark:`深色`,themeMist:`雾青`,themeRose:`蔷薇`,themePine:`松夜`,themeSystem:`跟随系统`,conversationSettings:`对话`,expandThinkingByDefault:`默认展开思考块`,chatContentWidth:`聊天内容宽度`,chatFontSize:`聊天字体大小`,agentBehavior:`Agent 行为`,capabilityDiscovery:`能力发现`,capabilityDiscovery_explicit:`明确请求`,capabilityDiscovery_adaptive:`自适应`,workflowLimits:`工作流上限`,workflowConcurrency:`工作流并行上限`,workflowCalls:`总调用次数`,agentSettingsSetupHint:`Agent 设置通过当前会话中的 /openpi-setup 生效。`,setupRequestDiscovery:`将能力发现设置为 {{mode}},保留其他配置。`,setupRequestLimits:`将工作流并行上限设置为 {{concurrency}},总子代理调用上限设置为 {{calls}},保留其他配置。`,setupRequestEnableSuggestions:`启用下一步建议。如需模型配置,请帮助我选择模型,保留其他配置。`,setupRequestDisableSuggestions:`关闭下一步建议,保留其他配置。`,setupRequestPostEdit:`帮我配置或关闭编辑后命令。先展示当前配置,再询问要使用的命令。`,configurePostEdit:`配置编辑后命令`,workflowLimitsValue:`并行 {{concurrency}} · 总调用 {{calls}}`,nextActionSuggestions:`下一步建议`,enabled:`已启用`,disabled:`已关闭`,configured:`已配置`,postEditCommand:`编辑后命令`,resultDisplay:`默认结果显示`,subagentResults:`子代理结果`,bashOperations:`Bash 操作`,fileMutations:`Write / Edit 操作`,footer:`页脚`,terminalFooter:`Pi 终端页脚`,terminalFooterStyle:`终端页脚样式`,terminalFooterHint:`影响 Pi 命令行界面的页脚;已打开的 Pi 界面在下次启动或配置应用后更新。`,detailDisplay_full:`完整`,detailDisplay_compact:`紧凑`,sessionSettings:`会话`,currentModel:`当前`,useThisModel:`使用此模型`,model:`模型`,modelConnection:`模型连接`,provider:`服务商`,modelId:`模型 ID`,providerStatusUnavailable:`此服务商不在当前有界认证快照中。`,providerSettings:`服务商凭据`,providerSettingsIntro:`查看当前 Web 会话可通过哪些 Pi 服务商完成认证。`,openRuntimeDetails:`打开运行详情`,currentWorkspace:`当前工作区`,providerAuth_api_key:`API 密钥`,providerAuth_oauth:`OAuth`,providerAuthUnknown:`未报告认证方式`,authentication:`认证方式`,accessType:`访问方式`,providerAccessSubscription:`订阅账户`,providerAccessStandard:`服务商凭据`,configurationOwner:`配置归属`,providerLoading:`正在加载服务商状态…`,providerLoadFailed:`无法加载服务商状态。`,providerReadOnly:`由 Pi 管理`,selectProvider:`选择服务商`,gitReviewBaselineUnavailable:`未保留可用的会话基线,可能超出了捕获限额。请切换到未暂存、已暂存或分支查看 Git 变更,也可打开本会话文件记录。`,modelsIntro:`登录账户或添加 API 密钥。已有的 Pi 连接也会显示在这里。`,accountLoginMethod:`连接方式`,accountLoginTab:`账户登录`,accountLoginChatGPT:`ChatGPT 账户`,accountLoginClaude:`Claude 账户`,accountLoginKeyTab:`API 密钥`,accountLoginConfigured:`账户已登录`,accountLoginIntro:`在浏览器中完成授权,无需填写 API 密钥。`,accountLoginExisting:`账户凭据已保存在 Pi 中。`,accountLoginStart:`登录`,accountLoginAgain:`重新登录`,accountLoginUnsaved:`请先保存或放弃其他修改,再登录账户。`,accountLoginStarting:`正在准备登录…`,accountLoginWaiting:`等待账户授权`,accountLoginChoose:`选择登录方式`,accountLoginCancelling:`正在取消登录…`,accountLoginBrowser:`在浏览器中继续`,accountLoginDevice:`使用设备码登录`,accountLoginBrowserOption:`在当前电脑上登录,完成后自动返回。`,accountLoginDeviceOption:`适合远程服务器,或无法自动返回的情况。`,accountLoginBrowserHelp:`打开登录页并完成授权,这里会自动更新。`,accountLoginDeviceHelp:`打开授权页并输入下方代码,请保持此页面打开。`,accountLoginOpen:`打开登录页`,accountLoginCopyCode:`复制设备码`,accountLoginPaste:`授权码或回调地址`,accountLoginContinue:`继续`,accountLoginFallback:`已登录,但这里没有更新?`,accountLoginRemoteHelp:`如果无法自动返回,请复制浏览器最后的回调地址,并粘贴到下方。`,accountLoginCancel:`取消登录`,accountLogin_failed:`登录未完成,请重试或选择其他登录方式。`,accountLogin_expired:`登录已过期,请重新开始获取新的授权链接。`,accountLogin_cancelled:`已取消登录。`,accountLoginRequestFailed:`请求未完成,请先刷新状态再重试。`,accountLoginStatusUnknown:`暂时无法查询登录状态,账户授权可能仍在进行。`,accountLoginRefreshRequired:`凭据已保存,但 Pi 未能更新模型列表。请重载 Pi 后使用此连接。`,accountLogout:`退出登录`,accountLogoutRefreshRequired:`已移除保存的凭据,但 Pi 未能更新模型列表。请重载 Pi 刷新状态。`,accountLogoutTitle:`退出 {{provider}}?`,accountLogoutDetail:`将移除此电脑上 Pi 保存的该服务凭据,其他使用它的 Pi 会话也需要重新登录。环境凭据不受影响。`,providerInputTypes:`输入类型`,providerInputText:`文本`,providerInputImage:`图片`,providerCustomTag:`自定义`,providerEdit:`编辑`,providerRemove:`删除`,providerSave:`保存`,editProvider:`编辑 {{provider}}`,removeProvider:`删除 {{provider}}`,providerAdd:`添加模型提供商`,providerAddMode:`添加方式`,providerAddCatalog:`第三方模型提供商`,providerAddCustom:`自定义模型 API`,providerAccountHint:`使用已有账户连接模型,选择服务商后前往浏览器授权。`,providerCatalogHint:`从内置目录中选择提供商,填入其 API 密钥即可使用。`,providerCustomHint:`连接中转站、自部署服务或其他兼容 OpenAI / Anthropic 协议的接口,需填写 API 地址、协议和模型。`,providerKeyKeep:`已配置密钥,留空保持不变`,providerKeyOptional:`输入 API 密钥,或留空使用环境认证`,providerDisplayName:`提供商名称`,providerCustomSettings:`自定义设置`,providerSaved:`已保存 {{provider}}。`,modelDefaultTitle:`新会话默认模型`,modelDefaultChoose:`选择模型`,modelDefaultBadge:`默认`,modelCurrentBadge:`当前使用`,modelDefaultNotSet:`未设置 · 新会话启动时由 Pi 选择`,modelDefaultHint:`选择以后新会话使用的模型,已有会话保留自己的选择。此设置也会更新 Pi 的默认模型。`,modelDefaultReadFailed:`暂时无法读取默认模型。`,modelDefaultProjectOverride:`此工作区有 Pi 独立设置:{{model}}。`,modelDefaultSave:`保存默认模型`,modelMakeDefault:`同时设为新会话默认模型`,modelDefaultSaveFailed:`默认模型保存尚未确认,请刷新状态后重试。`,modelDefaultPartial:`当前模型已切换,但默认模型保存尚未确认,请刷新状态后再试。`,modelConnectionNextHint:`从此连接选择一个模型,用于当前会话。`,modelConnectionSearch:`搜索模型…`,modelConnectionChooseProvider:`选择 {{provider}} 的模型`,modelConnectionUse:`用于当前会话`,modelConnectionUseFailed:`模型切换尚未确认,请刷新模型列表后重试。`,modelConnectionLoadFailed:`暂时无法读取模型列表。`,modelConnectionNoModels:`暂无可选模型,请检查连接或添加模型定义。`,modelConnectionNoMatch:`没有匹配的模型。`,modelConnectionMore:`还有 {{count}} 个模型,可搜索缩小范围。`,providerModelsEmpty:`还没有模型,获取可用模型或手动添加。`,providerModelsInherited:`使用提供商的内置模型目录。`,providerModelsReadOnly:`此提供商包含当前页面未支持的模型设置,请在 Pi 配置文件中编辑。`,providerModelId:`模型 {{number}} ID`,providerModelName:`模型 {{number}} 名称`,providerModelDetails:`模型参数:{{model}}`,providerRemoveModel:`删除模型:{{model}}`,providerIdInvalid:`请使用未被占用的提供商 ID,仅包含字母、数字、连字符、点或下划线。`,providerNativeAuth:`此提供商使用 Pi 原生登录。`,providerConfigurationFailed:`保存失败,请检查填写内容,并在会话空闲时重试。`,providerProfileSavedKeyFailed:`提供商配置已保存,但密钥保存失败。重试将只保存密钥。`,providerReload:`放弃草稿并重新加载`,providerCurrentRemoval:`请先切换当前使用的模型,再删除。`,providerRemoveDetail:`删除此提供商的配置和自定义模型?由 Pi 管理的凭据将保留。`,providerPickerIntro:`以下是模型提供商的可用模型,勾选要添加的模型。`,providerPickerSelected:`已选 {{count}} 个`,providerApiKey:`API 密钥`,providerKeyPlaceholder:`粘贴密钥以添加或替换`,saveProviderKey:`保存密钥`,savingSettings:`正在保存…`,keepEditing:`继续编辑`,discardAndContinue:`放弃更改并继续`,unsavedSettingsTitle:`放弃未保存的更改?`,unsavedSettingsDetail:`未保存的模型和凭据修改将被丢弃。`,unsavedCredentialTitle:`放弃未保存的凭据?`,unsavedCredentialDetail:`新密钥尚未保存,继续后将清空。`,modelSelectionBusy:`当前会话忙碌,暂不能切换模型。`,providerKeySaved:`已保存到 Pi 凭据存储。已有密钥不会回显。`,providerSaveFailed:`密钥保存未完成。请等待会话空闲,刷新状态后重试;部分服务商需要额外认证信息。`,providerWriteDetail:`在这里直接保存到 Pi 凭据存储,密钥不会进入模型对话。OAuth 或需要额外字段的认证请使用 Pi 原生登录。`,editModelConfiguration:`添加或编辑自定义模型`,modelConfigurationDetail:`先设置提供商连接,再获取模型列表或手动添加。保存配置不会调用模型。`,configuredModels:`自定义模型配置`,addModel:`添加模型`,modelConfig_provider:`服务商 ID`,modelConfig_id:`模型 ID`,modelConfig_name:`显示名称`,modelConfig_baseUrl:`API 地址`,modelConfig_api:`API 格式`,modelConfig_contextWindow:`上下文窗口`,modelConfig_maxTokens:`最大输出 token 数`,providerCapacityLabel:`{{field}} {{number}}`,providerModelOptions:`模型选项`,providerModelInvalid:`模型 {{number}}:模型 ID 不能为空或重复;容量需为正数,例如 128K 或 1M,留空使用默认值。`,modelConfig_reasoning:`支持推理`,saveModelConfiguration:`保存模型`,reloadModelConfiguration:`放弃草稿并载入最新配置`,retryModelConfiguration:`重试读取`,discardModelDraftTitle:`放弃这份模型草稿?`,discardModelDraftDetail:`最新配置将替换这份未保存的草稿。`,discardAndReload:`放弃并重新载入`,modelConfigurationUnsaved:`未保存的更改`,modelConfigurationConflict:`模型配置已在别处更改,当前草稿已保留。`,modelConfigurationLoadFailed:`无法读取模型配置,草稿已保留。`,modelConfigurationSaved:`已保存到 Pi models.json。配置服务商密钥后即可选择此模型。`,modelConfigurationFailed:`模型保存未完成,草稿已保留。`,setupConfigurationRequest:`配置需求`,configureViaSetup:`通过 OpenPI setup 应用`,setupFormDetail:`统一走 /openpi-setup。请在对话中查看进度及必要的确认;提交成功不等于配置已保存。`,setupSkillsPlaceholder:`填写要添加或调整的技能,以及来源或本地路径`,setupPluginsPlaceholder:`填写要配置的 Pi 插件,以及准确的包名或本地路径`,enableSkillInvocation:`允许模型调用`,disableSkillInvocation:`改为仅显式调用`,setupSkillInvocationRequest:`配置这个 Pi 技能:{{path}}。将原生 disable-model-invocation 字段设为 {{disabled}},保留其余内容,并说明何时生效。`,setupRoleFormRequest:`将 OpenPI 的 {{role}} 角色配置为使用 {{model}},工作流并发设为 {{concurrency}}。推理级别继承父会话,校验选择有效性,并保留其他配置。`,providerReadOnlyDetail:`此页面只读且不会接收凭据内容。请通过 Pi 配置服务商认证,然后刷新此状态。`,openProviderSettings:`打开服务商设置`,credentialConfigured:`已配置`,credentialMissing:`未配置`,authNotVerified:`凭据已配置不代表模型请求一定成功。`,configurationViaPi:`此处为只读状态。模型凭据与信任由 Pi 管理,OpenPI 选项通过 /openpi-setup 配置。`,noSkillsFound:`当前会话没有加载技能。`,addSkill:`添加技能`,addPlugin:`添加插件`,searchResources:`搜索名称或来源`,filterResourceScope:`资源范围`,allResourceScopes:`全部范围`,noMatchingResources:`没有匹配的资源`,resourceBulkTooLarge:`请进一步筛选列表后,再提交批量配置请求。`,resourceManagement:`Pi 资源`,resourceSourceAuto:`Pi 自动发现`,resourceSourceLocal:`本地资源`,resourcePackageSource:`软件包、仓库或本地路径`,resourcePackageSourcePlaceholder:`npm:包名@版本 · git:owner/repo · /path/to/skill`,resourceInstallIntro:`选择来源和范围,在对话中通过 OpenPI setup 审查并应用。`,resourceInstallReview:`请在对话中确认准确来源和权限。提交请求不代表已安装或已加载。`,resourceRequestSubmitted:`请求已提交。请在对话中查看进度和确认,完成后刷新此目录。`,browseSkills:`浏览 skills.sh 技能`,resourceSessionState:`应用到当前会话`,resourcesReloadNote:`刷新只读取目录;重新加载才会将已保存的资源应用到空闲会话。配置变更不会自动重新加载。`,reloadResources:`重新加载资源`,resourceReloadReview:`将已保存的 Pi 技能与插件配置应用到当前会话,并重新启动扩展?请先等待运行中的工作结束。`,resourceReloaded:`资源已重新加载,请查看更新后的目录和诊断。`,resourceReloadFailed:`无法重新加载资源。请等待当前会话空闲,刷新后重试。`,advancedResourceConfiguration:`高级配置`,resourceDiagnostics:`Pi 报告了 {{extensionErrors}} 项扩展诊断与 {{skillErrors}} 项技能诊断。`,resourceConfigurationDiagnostics:`{{count}} 项设置读取失败,请检查 Pi 配置诊断。`,resourceCatalogTruncated:`此目录有数量上限,部分资源未展示。`,resourceTargetTruncated:`此来源或路径已截断,请通过高级配置确认完整目标后再进行管理。`,updateResource:`检查更新`,removeResource:`审查移除`,skillsEmptyTitle:`添加你的第一个技能`,skillsEmptyIntro:`技能为 Pi 提供可复用的指引。可以添加软件包、仓库或本地技能;项目技能遵循 Pi 的项目信任。`,pluginsEmptyTitle:`用插件扩展 Pi`,pluginsEmptyIntro:`软件包可以包含扩展、技能、提示词和主题。添加来源后,通过 OpenPI setup 审查安装。`,pluginCount:`{{count}} 个插件来源`,installedVersion:`已安装版本`,configuredVersion:`配置版本`,resourceVersionUnpinned:`未固定版本 / 本地来源`,pluginState_loaded:`本会话资源已加载`,pluginState_installed:`已安装 · 未加载`,pluginState_disabled:`配置已禁用`,pluginState_missing:`软件包缺失`,pluginState_error:`加载诊断`,pluginState_notLoaded:`未加载`,pluginLoadedResources:`当前会话目录包含 {{count}} 项资源。配置变更需要明确重新加载后才会应用。`,pluginAction_enable:`审查启用`,pluginAction_disable:`审查禁用`,pluginAction_update:`检查更新`,pluginAction_remove:`审查移除`,enableVisibleSkills:`允许模型使用(当前 {{count}} 项)`,disableVisibleSkills:`仅显式调用(当前 {{count}} 项)`,enableVisiblePlugins:`启用当前 {{count}} 个软件包`,disableVisiblePlugins:`禁用当前 {{count}} 个软件包`,setupResourceInstallRequest:`添加 Pi {{kind}},来源为 {{source}},范围为 {{scope}}。先检查来源并确定固定的软件包身份,通过 ask_user 与我确认安装权限,再使用 Pi 原生的软件包或技能配置。添加技能时保留其他扩展和资源。保留现有偏好与项目信任,不要自动重新加载当前会话。分别报告已保存的配置与仍需执行的操作,不要改动无关的 OpenPI 设置。`,setupPluginOperationRequest:`审查 Pi 软件包操作 {{action}},只针对配置来源 {{source}}、原生安装目录 {{path}}、范围 {{scope}}。相对来源应以该范围的原生设置目录解析。使用 Pi 原生包管理;更新时检查可用版本,通过 ask_user 与我确认固定的目标身份和安装权限。保留资源过滤器及所有无关偏好;如果切换会破坏过滤器,停止并说明。移除时不得删除本地来源目录。不要自动重新加载,分别报告已持久化与当前会话状态,不要改动无关的 OpenPI 设置。`,setupSkillManageRequest:`审查 Pi 技能操作 {{action}},只针对文件 {{path}}、来源 {{source}}、范围 {{scope}}。先检查原生资源归属,通过 ask_user 与我确认更新或移除及所需权限。保留无关技能与软件包资源,不要为了移除一个技能删除整个共享软件包。保留项目信任,不要自动重新加载,也不要改动无关的 OpenPI 设置。`,setupSkillsBulkRequest:`只针对当前展示的 Pi 技能文件 {{paths}},将原生 disable-model-invocation 设为 {{disabled}}。检查资源归属,保留其余内容和偏好,与我审查必要变更,报告无法安全修改的文件。显式 /skill 调用仍应可用。不要自动重新加载,也不要改动无关的 OpenPI 设置。`,setupPluginsBulkRequest:`只针对当前展示的 Pi 软件包 {{packages}},通过 Pi 原生配置将 disabled 设为 {{disabled}}。保留其他偏好与资源过滤器;无法保留过滤器的条目应跳过并报告。遵循范围与项目信任,与我审查必要变更,不要自动重新加载,也不要改动无关的 OpenPI 设置。`,resourceRequestFinished:`配置回合已结束。请刷新并查看 Pi 原生配置与会话资源,确认实际变更。`,skillCount_one:`{{count}} 个技能`,skillCount_other:`{{count}} 个技能`,skill:`技能`,copySkillInvocation:`复制调用命令`,source:`来源`,scope:`范围`,invocation:`调用方式`,modelInvocation:`模型调用`,resourceScope_user:`全局`,resourceScope_project:`项目`,resourceScope_temporary:`临时`,explicitOnly:`仅允许明确调用`,availableToModel:`模型可按需使用`,skillFile:`技能文件`,selectSkill:`选择一个技能`,subagentConfiguration:`Pi 原生子代理角色`,subagentConfigurationIntro:`未在 OpenPI 配置中指定模型时,角色继承父会话模型。`,subagentActiveCount_one:`{{count}} 个运行中`,subagentActiveCount_other:`{{count}} 个运行中`,subagentCompletedCount_one:`{{count}} 条记录`,subagentCompletedCount_other:`{{count}} 条记录`,subagentConcurrency:`上限 {{count}}`,builtInRoles:`内置角色`,subagentRole_explorer:`探索者`,subagentRole_implementer:`实现者`,subagentRole_reviewer:`审查者`,subagentRole_advisor:`顾问`,subagentRoleShort_explorer:`只读调查`,subagentRoleShort_implementer:`聚焦实现`,subagentRoleShort_reviewer:`正确性审查`,subagentRoleShort_advisor:`技术分析`,subagentRoleDescription_explorer:`调查代码库并报告证据,不修改文件。`,subagentRoleDescription_implementer:`实现边界明确的改动并运行相关仓库检查。`,subagentRoleDescription_reviewer:`审查正确性、安全性、回归风险和缺失验证。`,subagentRoleDescription_advisor:`分析困难技术问题并提出具体下一步建议。`,configureRoles:`配置角色`,builtInRole:`内置角色`,builtIn:`内置`,modelAssignment:`模型分配`,inheritParentModel:`继承父会话模型`,effectiveModel:`实际模型`,workflowConcurrencyLabel:`并行 Agent`,workflowCallLimit:`Agent 总调用数`,runtimeBoundaries:`运行时边界`,subagentAuthorityNote:`子会话权限是父会话与角色能力的故障关闭交集,不会静默扩大权限。`,subagentModelNote:`不会硬编码服务商;未分配的角色继承父会话模型和思考等级。`,resourceCount_one:`{{count}} 项资源`,resourceCount_other:`{{count}} 项资源`,noPluginsFound:`Pi 未报告已加载的插件来源。`,pluginCatalogTotals:`{{extensions}} 扩展 · {{skills}} 技能 · {{prompts}} 提示词 · {{themes}} 主题`,loaded:`已加载`,resourceOrigin:`来源类型`,resourceOrigin_package:`软件包`,resourceOrigin_topLevel:`顶层资源`,resources:`资源`,baseDirectory:`基础目录`,notReported:`未报告`,extensions:`扩展`,extensionSurfaceCount:`{{tools}} 个工具 · {{commands}} 个命令`,prompts:`提示词`,themes:`主题`,pluginResourceSummary:`{{extensions}} 扩展 · {{skills}} 技能 · {{prompts}} 提示词 · {{themes}} 主题`,pluginsManagedByPi:`这些资源由 Pi 加载。可通过上方 setup 表单提交变更;软件包操作沿用原生确认,并通过 Pi 的重新加载流程生效。`,selectPlugin:`选择一个插件来源`,statusCaptured:`采集于 {{time}} · 刷新查看最新状态`,conversationViews:`会话视图`,currentConversations:`当前`,archivedConversations:`已归档`,refreshArchives:`刷新归档会话`,loadingArchives:`正在加载归档会话...`,moreArchives:`加载更多归档会话`,retryArchives:`重试读取归档会话`,archiveLoadFailed:`无法加载归档会话。`,archiveCursorStale:`归档会话已变化,请刷新后继续。`,archiveScanBounded:`还有 {{count}} 条更早记录未扫描。`,noArchivedSessions:`没有归档会话。`,noScannedArchives:`已扫描历史中没有归档会话。`,noMatchingScannedArchives:`已扫描历史中没有匹配的归档会话。`,draftLimit:`草稿暂存已满,请先发送或清空已有草稿。`,restoreConversation:`恢复会话`,restoringConversation:`正在恢复…`,loadedArchives:`已加载历史中的归档会话`,loadedHistoryBounded:`另有 {{sessions}} 个会话和 {{workspaces}} 个工作区摘要未加载。搜索仅覆盖已加载列表。`,noLoadedArchives:`已加载列表中没有归档会话。`,restoreFailed:`暂时无法确认恢复结果,请刷新后重试。`,execution_running:`运行中`,execution_done:`已完成`,execution_killed:`已停止`,execution_timed_out:`已超时`,execution_failed:`失败`,execution_uncertain:`状态不确定`,activeOnlyHint:`只有当前 Web 会话可以接收消息。`,stopTurn:`停止当前轮次`,stoppingTurn:`正在停止当前轮次…`,stoppedTurn:`当前轮次已停止。`,pendingFollowUpsHint:`{{count}} 条消息正在排队`,sendNextTurn:`下一轮发送`,steerCurrentTurn:`当前执行纠偏`,steeringHint:`在当前工具步骤结束后加入这条指示。`,pendingSteeringHint:`已接收 {{count}} 条纠偏指示,等待当前工具步骤结束`,steeringMessagesTitle:`当前轮次待处理的纠偏指示`,steerStaleTurn:`目标轮次已结束或变化。草稿已保留,请重新选择发送方式。`,sourceFeedbackNew:`{{path}} · 新版本第 {{line}} 行`,sourceFeedbackOld:`{{path}} · 旧版本第 {{line}} 行`,forkMessage:`从此处分叉`,forkMessageHint:`从此消息创建新聊天,保留原聊天;不会自动发送消息。`,forkSessionPending:`正在创建分叉会话…`,forkSessionCreated:`已创建分叉会话,原会话保留在侧栏。`,forkSessionCancelled:`分叉已取消,原会话已保留。`,forkSessionUncertain:`无法确认分叉结果。请先刷新并检查会话列表,再决定是否重试。`,forkSessionUnavailable:`切换到此会话并等待当前执行和排队消息结束后,可以从这里创建新会话。`,reviewQuoteLine:`引用此行`,reviewSelectOldLine:`选择旧版本第 {{line}} 行`,reviewSelectNewLine:`选择新版本第 {{line}} 行`,queuedMore:`还有 {{count}} 条排队消息`,queuedImage:`图片附件`,queuedMessageExpand:`展开排队消息`,queuedMessageCollapse:`收起排队消息`,backgroundSessionRunning:`此会话正在后台运行…`,observedSessionTools:`{{count}} 个正在执行的工具`,toolsRequireCurrentSession:`切换到此会话后可使用交互工具。`,activateViewedSession:`切换到此会话`,activateViewedSessionHint:`发送消息即可继续此会话。`,acceptedHint:`OpenPI Web 已接收消息。`,promptAdmissionUnknown:`无法确认上次发送的消息是否已被接收。`,promptAdmissionUnknownDetail:`请先核对已刷新的会话历史和运行状态,再决定下一步。作为新消息发送可能产生重复消息。`,promptAdmissionCheckingDetail:`正在核对最新的会话历史和运行状态,核对完成前不能作为新消息发送。`,promptAdmissionVerificationFailedDetail:`暂时无法刷新最新的会话历史和运行状态。请重新核对后再决定是否作为新消息发送。`,abandonAdmission:`暂不重新发送`,retryAdmissionCheck:`重新核对`,retryOriginalAdmission:`重试原消息`,promptTooLong:`文本超出发送上限({{count}} / {{limit}})。`,sendAsNew:`作为新消息发送`,sendingAsNew:`正在发送…`,addWorkspace:`添加工作区`,addWorkspaceMenu:`添加工作区...`,archiveConversation:`归档会话`,pinnedConversations:`置顶`,sidebarOptions:`侧栏选项`,sidebarProjectOptions:`项目侧栏选项`,sidebarRecentOptions:`会话侧栏选项`,sidebarActivityOptions:`动态视图选项`,sidebarShow:`显示`,sidebarGroupBy:`会话分组`,sidebarByProject:`按项目分组`,sidebarFlatList:`所有会话`,sidebarChatSort:`会话排序`,sidebarRecent:`最近`,sidebarProjectsInRecents:`在最近列表显示项目会话`,sidebarShowMore:`展开显示`,sidebarShowLess:`收起显示`,sidebarFilterList:`筛选当前列表`,sidebarSaveFailed:`更改未能保存,请重试。`,pinWorkspace:`置顶项目`,unpinWorkspace:`取消置顶项目`,markConversationRead:`标记为已读`,markConversationUnread:`标记为未读`,sidebarState_unread:`未读会话`,sidebarActivity:`动态`,sidebarViewActivity:`查看动态`,sidebarViewChats:`查看会话`,sidebarPriority:`优先关注`,sidebarActivityEmpty:`没有需要关注的会话`,sidebarActivityEmptyHint:`已完成的工作和需要你处理的会话会显示在这里。`,sidebarMarkAllRead:`全部标记为已读`,sidebarClearRead:`清除优先关注中的已读会话`,sidebarReadFailed:`未能更新已读状态,请重试。`,sidebarToday:`今天`,sidebarYesterday:`昨天`,sidebarEarlier:`更早`,sidebarActivityCompleted:`已完成`,sidebarActivityFailed:`执行失败`,sidebarActivityRead:`已读`,modelAdvanced:`高级参数`,providerConnectionHeading:`提供商连接`,providerFetchModels:`获取可用模型`,providerFetchHint:`填写提供商和端点后,可一次选择多个模型。`,providerPickerTitle:`选择要添加的模型`,providerPickerAccess:`连接凭据`,providerPickerKey:`访问密钥(可选)`,providerPickerKeyHint:`留空使用此端点已保存的凭据。此处输入的密钥仅用于获取列表,不会保存。`,providerPickerSearch:`搜索模型`,providerPickerSelectAll:`全选`,providerPickerClear:`清空选择`,providerPickerLoading:`正在获取可用模型…`,providerPickerAdded:`已添加`,providerPickerNoMatch:`没有匹配的模型`,providerPickerEmpty:`提供商没有返回模型,仍可手动添加。`,providerPickerBounded:`当前显示前 500 个模型,其他模型可手动填写 ID。`,providerPickerError_load:`未能获取模型列表,请检查端点和凭据后重试,也可以手动添加。`,providerPickerError_save:`尚未确认保存成功。已保留你的选择,请检查连接后重试。`,providerPickerError_conflict:`配置已在其他地方更新,请关闭弹窗、重新读取配置后再保存。`,providerPickerDefaults:`新模型使用 {{context}} 上下文 / {{output}} 输出 token,添加后可逐个调整。`,providerPickerRetry:`刷新列表`,providerPickerCount:`已选 {{count}} 个 · 最多 100 个`,providerPickerSave:`添加所选`,sidebarState_running:`执行中`,sidebarState_compacting:`正在整理上下文`,sidebarState_waiting:`等待你的回复`,sidebarState_completed:`已完成 · 结果未读`,sidebarState_failed:`执行失败 · 打开会话查看详情`,pinnedOptions:`置顶选项`,pinConversation:`置顶会话`,unpinConversation:`取消置顶`,pinnedRecentlyUpdated:`最近更新`,pinnedManualOrder:`手动排序`,movePinUp:`上移`,movePinDown:`下移`,pinSaveFailed:`置顶设置未能保存,请重试。`,cancel:`取消`,chooseWorkspaceHint:`选择工作区并描述任务`,close:`关闭`,closeSearch:`关闭搜索`,collapseSidebar:`收起侧边栏`,confirmEdit:`保存并重新运行`,editMessageHint:`从这里创建新分支并重新运行;保留原对话、图片和文件引用。已有工作区改动会保留。`,regenerateMessage:`重新生成回答`,regenerateMessageHint:`在新分支重新运行这条问题,保留原附件和原对话。`,messageRerunStarted:`已在新分支接收重跑消息,原对话已保留。`,openOriginalConversation:`查看原对话`,messageRerunWorkspaceHint:`已有工作区改动会保留。`,modelRequestRecovered:`请求已恢复`,modelReconnecting:`正在重新连接`,modelReconnectUnknown:`重连状态待确认`,modelEarlierAttempts:`先前请求错误`,modelFailedAttempts:`失败尝试({{count}} 次)`,draftStorageUnavailable:`草稿未能保存到此设备,请保持页面打开或复制消息。`,draftStorageInvalid:`部分保存的草稿内容无法恢复,请检查消息和附件。`,draftStorageRetry:`重试保存草稿`,workbarBackToChat:`返回聊天`,workbarCollapseTools:`收起工具栏`,workbarEndTerminal:`关闭 {{name}} 并结束进程`,workbarNewTerminal:`新建终端`,workbarContinueInChat:`继续追问`,transcriptSearch:`搜索消息内容`,transcriptSearchPlaceholder:`搜索标题、项目或消息…`,transcriptSearchRecent:`最近会话`,transcriptSearchSessions:`会话`,transcriptSearchMessages:`消息内容`,transcriptSearchSessionResult:`打开会话 {{session}}`,transcriptSearchSessionOpenFailed:`暂时无法打开此会话,请重试。`,transcriptSearchIncludeArchived:`包含归档会话`,transcriptSearching:`正在搜索消息…`,transcriptSearchEmpty:`没有匹配的消息。`,transcriptSearchFailed:`暂时无法搜索消息,请重试。`,transcriptSearchRetry:`重试搜索`,transcriptSearchPartial:`部分历史未能搜索,结果可能不完整。`,transcriptSearchOpenFailed:`无法打开这条消息,它可能已移动或位于其他分支。`,transcriptSearchResult:`打开 {{session}} 中来自{{source}}的消息`,transcriptSearchSource_user:`你`,transcriptSearchSource_assistant:`助手`,transcriptSearchSource_tool_call:`工具调用`,transcriptSearchSource_tool_result:`工具结果`,connected:`已连接`,connecting:`正在连接`,conversationName:`会话名称`,conversationOptions:`会话选项`,sidebarRename:`重命名`,sidebarPin:`置顶`,sidebarUnpin:`取消置顶`,sidebarFork:`分叉`,sidebarForkLocal:`创建聊天分支`,sidebarForkSameWorktree:`在同一工作树中分叉`,archiveNoticeTitle:`聊天已归档`,archiveNoticeView:`查看`,archiveNoticeUndo:`撤销`,archiveNoticeFailed:`操作未完成,请重试。`,sidebarForkWorktree:`在新工作树中创建聊天分支`,sidebarForkCancelling:`正在请求取消…`,sidebarForkFinishing:`无法再取消,正在确认创建结果…`,sidebarForkCancelUnconfirmed:`无法确认取消,正在等待分叉结果。`,sidebarForkWorktreePreserved:`工作树已保留在 {{path}},请检查后再重试。`,sidebarForkWorktreePending:`正在创建工作树和聊天分支…`,sidebarForkOptionsLoading:`正在检查工作树是否可用…`,sidebarForkOptionsFailed:`无法检查工作树,请重新打开菜单重试。`,sidebarForkUnavailable:`发送消息后才能创建此聊天的分支。`,sidebarForkArchived:`请先恢复此会话,再创建分叉。`,sidebarForkFailed:`未能创建分叉,原会话已保留。`,sidebarCopy:`复制`,sidebarCopyLink:`复制会话链接`,sidebarCopyMarkdown:`复制为 Markdown`,sidebarCopyCwd:`复制工作目录`,sidebarCopied:`已复制`,sidebarCopyFailed:`复制失败,请重试。`,sidebarNewWindow:`在新窗口中打开`,sidebarOpenIn:`打开方式`,sidebarAppsLoading:`正在加载可用应用…`,sidebarAppsFailed:`无法加载应用,请重新打开菜单重试。`,sidebarOpenFailed:`无法在所选应用中打开此项目。`,sidebarArchive:`归档`,sidebarRestore:`恢复`,sidebarDelete:`永久删除`,managedWorktreeRecoveryFull:`请先核对先前未确认的移除请求,再开始新的请求。`,managedWorktreesChanged:`工作树列表已变化,请刷新后重新核对目标。`,managedWorktreesRefresh:`刷新工作树列表`,managedWorktreesBack:`返回工作树列表`,managedWorktreesRetry:`重试请求`,managedWorktrees:`保留的工作树`,managedWorktreesDescription:`删除会话会保留 OpenPI 创建的工作树。请核对准确路径后再请求移除。使用中、共享、有改动或无法确认归属的工作树会保留。`,managedWorktreeConfirm:`移除此工作树?服务端会重新核对归属、使用中的会话及本地改动后再操作。`,managedWorktreeRemoved:`工作树已移除。`,managedWorktreePreserved:`工作树已保留:`,managedWorktreeUncertainTerminal:`移除结果无法确认,不能自动重复移除。请先检查保留路径,再决定后续操作。`,managedWorktreeUncertain:`尚不能确认移除结果。重试会核对原请求。`,managedWorktreeRemoving:`正在核对并移除…`,managedWorktreeRemove:`移除工作树`,managedWorktreeReview:`核对移除`,managedWorktreesEmpty:`这一页没有找到托管工作树。`,managedWorktreesUnavailable:`有 {{count}} 条归属记录无法确认。`,managedWorktreesLoadFailed:`无法加载保留的工作树。请重试,目标不会改变。`,managedWorktreesMore:`加载更多工作树`,managedWorktreeRetainedAfterDelete:`会话已删除,工作树保留在 {{path}}。可从项目菜单核对保留的工作树。`,sidebarDeleteTitle:`删除会话?`,sidebarDeleteDescription:`确定永久删除“{{name}}”?此操作无法撤销。`,sidebarDeleteConfirm:`删除`,sidebarDeleting:`正在删除…`,sidebarDeleteFailed:`未能删除此会话,请重试或取消。`,sidebarActionRunning:`请等待当前工作和排队消息结束。`,sidebarActionDisconnected:`请先恢复连接,再修改此会话。`,sessionDeleteCancelled:`删除已取消`,sessionDeleteUncertain:`无法确认会话是否删除,请刷新后重试`,sessionDeleted:`会话已永久删除`,sessionDeleteMetadataPending:`会话已删除,但侧栏记录未清理完成`,sessionLinkUnavailable:`链接中的会话已不存在或身份已变化`,sidebarDropPin:`拖到此处置顶`,sidebarDropProjectLast:`将项目移到最后`,conversationTurns:`会话轮次`,conversationTurnPosition:`前往第 {{position}} 轮`,turnPreviewLoading:`正在加载预览…`,turnPreviewUnavailable:`暂时无法读取,请重试。`,commands:`斜杠命令`,addContext:`添加上下文`,fileReference:`引用工作区文件`,fileReferenceTitle:`引用工作区文件`,fileReferenceDetail:`将路径引用加入提示词,不上传文件内容。`,fileReferenceLabel:`工作区文件路径`,fileReferencePlaceholder:`src/app.tsx`,fileReferenceValidatedHint:`当前会话会验证该路径是可读取的工作区文件。`,fileReferenceDraftHint:`新会话启动后,Pi 会按其工具权限解析该路径。`,fileReferenceChecking:`正在检查…`,fileReferenceFailed:`无法验证该文件。`,fileReferenceDenied:`请选择当前会话工作区内的文件。`,fileReferenceMissing:`该工作区文件已不存在。`,fileReferenceUnsupported:`只能引用工作区中的普通文件。`,fileReferenceExpired:`活动会话已变化,请重新打开文件引用后再试。`,fileReferenceBusy:`文件校验正忙,请稍后重试。`,insertReference:`插入引用`,commandsSessionRequired:`会话启动后才能插入斜杠命令。`,commandsEmptyDraftOnly:`只能在空白草稿中插入斜杠命令。`,commandsLoading:`正在加载命令…`,commandsUnavailable:`暂时无法读取命令。`,commandsNoMatch:`没有匹配的命令。`,commandsNoAvailable:`已发现的命令均不能在 Web 中运行。输入具体命令名可查看其可用性。`,commandsBounded:`另有 {{count}} 个命令未显示。`,commandSessionRequired:`命令仅在已创建的 Web 会话中可用。`,commandUnsupported:`尚未适配 · 手动命令仍交给 Pi`,commandAcceptsArguments:`可输入参数`,commandSource_extension:`扩展命令`,commandSource_prompt:`提示词模板`,commandSource_skill:`技能`,copiedMessage:`已复制`,copyMessage:`复制消息`,copyFailed:`复制失败,请选中消息后手动复制。`,copiedCode:`代码已复制`,copyCode:`复制代码`,copyCodeFailed:`无法复制代码,请选中后手动复制。`,codeBlock:`代码块`,deleteWorkspace:`删除工作区`,describeTask:`描述任务`,editMessage:`修改并从这里重跑`,enterHint:`按 Enter 发送,Shift+Enter 换行。`,expandSidebar:`展开侧边栏`,importWorkspace:`导入工作区`,loadingModels:`正在加载模型...`,modelsTruncated:`当前显示 {{shown}} 个模型,还有 {{omitted}} 个可用;搜索即可查找。`,searchModels:`搜索可用模型`,searchModelsPlaceholder:`搜索服务商、模型名称或 ID...`,searchingModels:`正在搜索模型...`,noMatchingModels:`没有匹配的模型`,modelSearchFailed:`模型搜索失败,请重试。`,retryModelSearch:`重试模型搜索`,fileReferenceDraftChanged:`草稿已变化,请重新打开文件引用。`,modelSearchTruncated:`还有 {{omitted}} 个匹配模型未显示。`,modelPreparing:`正在准备任务...`,modelRetrying:`模型请求重试中...`,modelRunning:`正在运行...`,modelRequestFailed:`模型请求失败`,modelRequestStopped:`模型请求已停止`,modelFailureUnknown:`服务商没有返回具体失败原因。`,retryPrompt:`重试消息`,retryingPrompt:`正在重试…`,newSession:`新建会话`,noConversations:`暂无对话`,noMatching:`没有匹配的会话`,noMatchingLoaded:`已加载历史中没有匹配的会话`,noModels:`没有可用模型`,noOutput:`无输出`,noSessions:`暂无会话`,openSidebar:`打开侧边栏`,promptMessage:`发消息或创建任务,/ 调用指令`,promptReadonly:`非当前会话不能接收消息`,promptStart:`选择一个工作区开始`,promptTask:`描述你想要构建的任务`,landingTagline:`小骨架 · 净上下文 · 深扩展`,queuedHint:`当前回合结束后将发送消息。`,reconnecting:`正在重连`,removeWorkspace:`从侧边栏移除`,workspaceOptions:`工作区选项`,renameFailed:`无法保存名称,已保留你的修改。`,savingName:`正在保存...`,workspaceRemoveFailed:`无法移出工作区,请重试。`,removingWorkspace:`正在移出...`,renameConversation:`重命名会话`,renameWorkspace:`重命名工作区`,save:`保存`,searchConversations:`搜索会话`,searchPlaceholder:`筛选标题与工作目录…`,selectModel:`选择模型`,configureModels:`配置模型`,openModelSettings:`模型设置`,selectThinking:`选择思考等级`,resetThinking:`恢复打开时的等级({{level}})`,modelThinkingNotEnabled:`此模型未启用思考。如提供商支持,可在模型设置中开启「支持推理」。`,providerReasoningHint:`按提供商能力开启;可用档位由 Pi 提供,在聊天输入框调节强度。`,providerImageHint:`未勾选图片时,模型不会收到图片附件。`,selectWorkspace:`选择工作区`,send:`发送`,processDetails:`执行过程`,processRunning:`正在执行`,processThinkingCount:`{{count}} 段思考`,processToolCount:`{{count}} 次工具调用`,processActivityCount:`{{count}} 项 Agent 活动`,switchingSession:`正在切换会话...`,thinkingActive:`思考中...`,thinkingActiveLevel:`思考中({{level}})...`,thinkingDone:`思考过程`,thinkingLoadFull:`查看完整思考`,thinkingLoadingFull:`正在加载思考…`,thinkingLoadFailed:`思考加载失败,点击重试`,thinkingPartialText:`当前显示部分已保存的思考,可继续加载下方内容。`,thinkingPreviewOnly:`思考预览已达到显示上限,此消息保存后可查看完整内容。`,toolState_running:`执行中`,toolState_returned:`已返回`,toolState_failed:`失败`,toolState_cancelled:`已停止`,toolState_timed_out:`超时`,toolState_unknown:`未确认`,toolSnapshotMissingResult:`分叉时尚无结果`,toolActivity_running:`正在{{action}}`,toolActivity_failed:`{{action}}失败`,toolActivity_cancelled:`{{action}}已停止`,toolActivity_timed_out:`{{action}}超时`,toolActivity_unknown:`{{action}}`,toolAction_read:`读取`,toolAction_write:`写入文件`,toolAction_edit:`编辑文件`,toolAction_command:`运行`,toolAction_search:`搜索`,toolAction_list:`列出文件`,toolAction_web:`浏览网页`,toolAction_agent:`使用子代理`,toolAction_workflow:`调用工作流`,toolAction_plan:`准备计划`,toolAction_task:`处理任务`,toolAction_goal:`处理目标`,toolAction_git:`查看变更`,toolAction_call:`调用工具`,toolActionDone_read:`已读取`,toolActionDone_write:`已写入`,toolActionDone_edit:`已编辑`,toolActionDone_command:`已运行`,toolActionDone_search:`已搜索`,toolActionDone_list:`已列出的文件`,toolActionDone_web:`已浏览网页`,toolActionDone_agent:`子代理工具已返回`,toolActionDone_workflow:`工作流工具已返回`,toolActionDone_plan:`计划工具已返回`,toolActionDone_task:`任务工具已返回`,toolActionDone_goal:`目标工具已返回`,toolActionDone_git:`已查看变更`,toolActionDone_call:`已调用工具`,toolActionGroup_read:`读取文件`,toolActionGroup_write:`写入文件`,toolActionGroup_edit:`编辑文件`,toolActionGroup_command:`运行命令`,toolActionGroup_search:`搜索`,toolActionGroup_list:`列出文件`,toolActionGroup_web:`浏览网页`,toolActionGroup_agent:`子代理活动`,toolActionGroup_workflow:`工作流活动`,toolActionGroup_plan:`准备计划`,toolActionGroup_task:`处理任务`,toolActionGroup_goal:`处理目标`,toolActionGroup_git:`查看变更`,toolActionGroup_call:`调用工具`,toolGroup_done:`已{{actions}}`,toolGroup_running:`正在{{actions}}`,toolGroup_unknown:`{{actions}}`,toolGroupSeparator:`、`,toolSearchTarget:`“{{pattern}}” · {{path}}`,toolDiffStatsHelp:`当前显示差异中的新增和删除行数`,toolRequestedFile:`文件:`,toolWorkspace:`工作区`,toolRawEvidence:`参数与原始结果`,toolCodemodeDetails:`脚本与原始结果`,toolNestedOutputMissing:`会话记录保留了调用和状态,未保存此子工具的输出。`,toolNestedArgumentsMissing:`会话记录未保留完整参数和此子工具的输出。`,toolNestedIncomplete:`子调用记录不完整,部分调用、参数或最终状态不可用。`,toolPartialEvidence:`输出未完整显示:已达到字节、行数或条目上限。原始结果也可能被截断。`,toolFileChange_created:`已创建文件`,toolFileChange_unchanged:`文件内容未改变`,toolFileChange_overwritten:`已覆盖文件`,toolChangeUnavailable:`此工具结果未提供修改对比。`,toolTestResults:`测试结果摘要 · {{format}}`,toolTestCounts:`{{tests}} 项测试 · {{passed}} 通过 · {{failed}} 失败 · {{cancelled}} 取消`,toolTestCountsHelp:`数量来自命令输出,执行状态单独显示。`,toolReadMore:`可使用文件路径和 offset 继续读取,具体方式见原始结果。`,toolFullOutputReference:`完整输出:`,subagentBackgroundResult:`后台子代理结果 · {{count}}`,thinkingDraftHint:`请先选择工作区并创建会话。`,thinkingInactiveHint:`只有当前会话可以更改思考等级。`,thinkingLevelMismatch:`当前确认的思考等级不在此模型支持范围内;选择其它等级即可修正。`,thinkingLockedRunning:`请先停止当前轮次,再更改思考等级。`,thinkingModelPendingHint:`请等待模型切换完成。`,thinkingNotConfirmed:`思考等级未获确认,请重试。`,thinkingPendingHint:`正在应用思考等级...`,thinkingUnsupported:`暂不支持思考`,thinkingUnsupportedHint:`尚未选择模型,或当前模型不支持思考。`,unavailable:`不可用`,ungrouped:`未分组`,untitledSession:`新会话`,workspaceDeleteConfirm:`文件夹与会话记录会保留,其中的会话会被放到“未分组”;再次打开此目录时将是一个干净的工作区。`,workspaceName:`工作区名称`,workspaces:`工作区`,sidebarProjects:`项目`}}},mJ=navigator.language?.toLowerCase().startsWith(`zh`)?`zh`:`en`;In.use(tr).init({fallbackLng:`en`,initAsync:!1,interpolation:{escapeValue:!1},lng:mJ,resources:pJ}),document.documentElement.lang=mJ===`zh`?`zh-CN`:`en`;var hJ=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},gJ=10,_J=13,vJ=32,yJ=6;function bJ(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{maxBufferSize:t,onComment:n,onError:r,onEvent:i,onId:a,onRetry:o}=e,s=[],c=0,l=!0,u,d=``,f=0,p,m=!1,h=!1,g=!1;function _(e){if(m)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,e.charCodeAt(0)===65279?e=e.slice(1):e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),(h||g)&&(e=v(e),!e))return;if(!s.length){let t=S(e);t!==``&&y(t),x();return}if(e.indexOf(` +`)===-1&&e.indexOf(`\r`)===-1){if(c0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0,t=n+1,n=e.indexOf(` -`,t);continue}let r=e.charCodeAt(t);if(gJ(e,t,r)){let r=e.charCodeAt(t+5)===pJ?t+6:t+5,o=e.slice(r,n);if(f===0&&e.charCodeAt(n+1)===dJ){u!==void 0&&a?.(u),i?.({id:u,event:p,data:o}),u=void 0,d=``,p=void 0,t=n+2,n=e.indexOf(` -`,t);continue}d=f===0?o:`${d}\n${o}`,f++}else _J(e,t,r)?p=e.slice(e.charCodeAt(t+6)===pJ?t+7:t+6,n)||void 0:C(e,t,n);t=n+1,n=e.indexOf(` +`,t);continue}let r=e.charCodeAt(t);if(xJ(e,t,r)){let r=e.charCodeAt(t+5)===vJ?t+6:t+5,o=e.slice(r,n);if(f===0&&e.charCodeAt(n+1)===gJ){u!==void 0&&a?.(u),i?.({id:u,event:p,data:o}),u=void 0,d=``,p=void 0,t=n+2,n=e.indexOf(` +`,t);continue}d=f===0?o:`${d}\n${o}`,f++}else SJ(e,t,r)?p=e.slice(e.charCodeAt(t+6)===vJ?t+7:t+6,n)||void 0:C(e,t,n);t=n+1,n=e.indexOf(` `,t)}return e.slice(t)}for(;t20?`${e.slice(0,20)}…`:e}"`,{type:`unknown-field`,field:e,value:t,line:n}))}}function T(){u!==void 0&&a?.(u),f>0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0}function E(e={}){if(e.consume&&s.length>0){let e=s.join(``);C(e,0,e.length)}l=!0,u=void 0,d=``,f=0,p=void 0,s.length=0,c=0,m=!1,h=!1,g=!1}return{feed:_,reset:E}}function gJ(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function _J(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}function vJ(e,t){let n=1;for(;nt.abort();e.signal.addEventListener(`abort`,n,{once:!0}),e.signal.aborted&&n();let r=window.setTimeout(n,45e3),i=await fetch(`/events?cursor=${e.cursor}`,{headers:await e.client.headers(),signal:t.signal}).finally(()=>{window.clearTimeout(r),e.signal.removeEventListener(`abort`,n)});if(i.status===409)throw new yJ(`event replay expired`);if(!i.ok||!i.body)throw Error(`event connection failed`);e.onConnected();let a=e.cursor,o=0,s=hJ({onComment(t){t.trim()===`heartbeat`&&++o>=4&&(o=0,e.onHeartbeat?.())},onEvent(t){let n=JSON.parse(t.data);if(!Number.isSafeInteger(n.sequence))throw new yJ(`invalid event cursor`);if(!(n.sequence<=a)){if(n.sequence!==a+1)throw new yJ(`event cursor gap`);if(a=n.sequence,n.type===`state_invalidated`)throw new yJ(`state invalidated`);e.onEvent(n)}}}),c=i.body.getReader(),l=new TextDecoder;try{for(;!e.signal.aborted;){let t,n,r=c.read(),i=new Promise((r,i)=>{n=()=>i(Error(`event stream aborted`)),e.signal.addEventListener(`abort`,n,{once:!0}),window.addEventListener(`offline`,n,{once:!0}),(e.signal.aborted||navigator.onLine===!1)&&n(),t=window.setTimeout(()=>i(Error(`event stream stalled`)),45e3)}),{done:a,value:o}=await Promise.race([r,i]).finally(()=>{window.clearTimeout(t),n&&(e.signal.removeEventListener(`abort`,n),window.removeEventListener(`offline`,n))});if(a)throw Error(`event connection closed`);s.feed(l.decode(o,{stream:!0}))}}finally{await c.cancel().catch(()=>void 0)}}var xJ=`openpi.collapsed-workspaces`,SJ=`openpi.sidebar-collapsed`,CJ=new Set(`agent_start.turn_started.turn_settled.agent_settled.prompt_settled.message_end.tool_execution_end.session_start.session_switched.session_progress.queue_update.prompt_failed.prompt_discarded.model_select.settings_changed.workspace_imported.workspace_removed.workspace_renamed.session_renamed.session_archived.session_unarchived.session_pins_changed.sidebar_pins_changed.workspace_order_changed.session_order_changed.session_read_state_changed.session_created.session_forked.session_deleted.prompt_accepted.runtime_changed.questions_changed.command_feedback.command_submitted.plan_mode_changed`.split(`.`));function wJ(e){try{let t=JSON.parse(window.sessionStorage.getItem(e)||`[]`);return new Set(Array.isArray(t)?t.filter(e=>typeof e==`string`):[])}catch{return new Set}}function TJ(e){try{return window.sessionStorage.getItem(e)===`true`}catch{return!1}}function EJ(e,t){try{window.sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function DJ(e){let t=8,n=[];for(let r=e.length-1;r>=0;r--){let i=e[r];(i.optimistic||t-->0)&&n.push(i)}return n.reverse()}var OJ=1e3,kJ=new Set,AJ=new WeakMap;function jJ(e){if(e){if(e.role===`toolResult`&&e.toolCallId)return`tool-result-${e.toolCallId}`;if(e.timestamp!==void 0)return`message-${e.role}-${e.timestamp}`}}function MJ(e){return e?.parts?.some(e=>e.type===`thinking`)===!0}function NJ(e){if(!e)return kJ;let t=AJ.get(e);if(t)return t;let n=new Set;for(let t of e){if(!MJ(t.message))continue;n.add(t.id);let e=jJ(t.message);e&&n.add(e)}return AJ.set(e,n),n}function PJ(e,t){for(let n of Object.keys(e))if(!t.has(n)){let n={};for(let r of Object.keys(e))t.has(r)&&(n[r]=e[r]);return n}return e}function FJ(e,t){if(e.length!==t.length)return!1;for(let n=0;ne.optimistic?.sessionId===t?.id&&e.optimistic?.sessionPath===t?.path&&e.optimistic!==void 0)}function LJ(e,t,n,r){return e.map(e=>e.optimistic?.sessionId===t&&e.optimistic.sessionPath===n&&e.optimistic.commandId===r&&!e.optimistic.admitted?{...e,optimistic:{...e.optimistic,admitted:!0}}:e)}function RJ(e,t){return t.aborted?Promise.resolve():new Promise(n=>{let r=()=>{window.clearTimeout(i),t.removeEventListener(`abort`,r),n()},i=window.setTimeout(r,e);t.addEventListener(`abort`,r,{once:!0})})}function zJ(e){return/^\/(?![\\/])/u.test(e)||/^[a-z]:[\\/]/iu.test(e)||/^\\\\(?![?.]\\)[^\\/]+\\[^\\/]+\\/u.test(e)||/^\/\/[^\\/]+\/[^\\/]+\//u.test(e)}function BJ(e=new rf,t={}){let n=t.consumeEvents??bJ,r=new URLSearchParams(window.location.search),i=r.get(`sessionPath`),a=r.get(`sessionId`),o=i!==null||a!==null,s=i&&zJ(i)&&i.length<=4096&&a&&a.length<=128&&!/[\u0000-\u001f\u007f]/u.test(i+a)&&r.getAll(`sessionPath`).length===1&&r.getAll(`sessionId`).length===1?{path:i,id:a}:null,c=0,l=0,u=null,d=!1,f=new Map,p=0,m=0,h=null,g=0,_=null,v=null,y=null,b=null,x=Promise.resolve(),S=null,C=null,w=!1,T=!1,E=null,D=null,O=0,k=null,A=0,j=!1,M=0,N=0,P=null,F=-1,I=null,L=0,R=0,ee=new Set,z=new Set,B=[],V=(e,t)=>{if(typeof t==`string`)for(e.add(t);e.size>32;){let t=e.values().next().value;t&&e.delete(t)}},H=()=>(R++,B=[],{planSelectionPending:!1,activeTurn:null,turnCancellationPending:!1,turnTerminalStatus:null,pendingFollowUpsReceipt:null,pendingSteeringReceipt:null,liveMessages:[],liveRunning:!1,livePhase:`idle`,liveRetry:null,thinkingStarts:{},thinkingDurations:{}}),te=e=>{let t=B.indexOf(e);for(t>=0&&B.splice(t,1),B.push(e);B.length>OJ;)B.shift()},ne=(e,t,n,r)=>{let i=NJ(t);B.some(e=>i.has(e))&&(B=B.filter(e=>!i.has(e)));let a=new Set(i);for(let t of e){a.add(t.key);let e=jJ(t.message);e&&a.add(e)}for(let e of B)a.add(e);let o=PJ(n,a),s=PJ(r,a);return o===n&&s===r?null:{thinkingStarts:o,thinkingDurations:s}},re=()=>(O++,D?.abort(),D=null,{modelSearch:{query:``,status:`idle`,models:[],totalMatches:0,matchesOmitted:0,error:null}}),ie=()=>({sessionId:null,status:`idle`,commands:[],totalAvailable:0,commandsOmitted:0,error:null}),ae=(e,t)=>({liveRunning:t===`running`||!e,livePhase:t===`running`?`running`:e?`idle`:`preparing`});return dr((t,r)=>{let i=e=>{h=null,t({notice:e instanceof Error?e.message:String(e)})},a=e=>{let t=r().snapshot;return e.epoch===c&&r().selectedWorkspace===e.workspacePath&&t?.currentSessionId===e.sessionId&&rj(t)&&t.selectedSession?.id===e.sessionId&&r().selectedPath===t.selectedSession.path&&t.selectedSession.cwd===e.workspacePath&&(!e.sessionPath||t.selectedSession.path===e.sessionPath)},B=()=>{L++,I?.abort(),I=null,t({commandDiscovery:ie()})},U=async(n,a,o,s)=>{if(r().modelSelectionPending)return!1;t({modelSelectionPending:!0});try{let i=await e.selectModel(n.provider,n.id,o,s);if(a!==c||s!==r().selectedPath||o!==r().snapshot?.selectedSession?.id)return!1;if(i.provider!==n.provider||i.id!==n.id||!i.current)throw Error(`Model selection was not confirmed. Please select a model again.`);if(!await r().actions.refreshSnapshot({epoch:a})||a!==c||s!==r().selectedPath||o!==r().snapshot?.selectedSession?.id)return!1;let l=r().snapshot?.models.find(e=>e.current);if(l?.provider!==n.provider||l.id!==n.id)throw Error(`The Session model changed. Please select a model again.`);return t({draftModel:null,notice:null}),!0}catch(e){return a===c&&s===r().selectedPath&&o===r().snapshot?.selectedSession?.id&&i(e),!1}finally{a===c&&t({modelSelectionPending:!1})}},oe=(e=160)=>{if(w){T=!0;return}C===null&&(C=window.setTimeout(async()=>{C=null,w=!0;try{await r().actions.refreshSnapshot()}finally{w=!1,T&&(T=!1,oe())}},e))},se=()=>{P=null,N=0,F=-1},ce=()=>{let e=r().snapshot;if(!e)return;P&&F!==c&&se();let n=e.thinking;if(n){if(!P||n.revision>=N){P=n,N=n.revision,F=c;return}n!==P&&t({snapshot:{...e,thinking:P}})}},le=e=>{P&&F!==c&&se(),e&&e.revision>=N&&(P=e,N=e.revision,F=c),ce()},ue=()=>{k=null,A++,j=!1,t({thinkingPendingLevel:null})},de=async()=>{let t=c,n=r().snapshot?.selectedSession?.id,i=r().selectedPath;if(n)try{let a=await e.thinking(n,new AbortController().signal);if(t!==c||i!==r().selectedPath||n!==r().snapshot?.selectedSession?.id)return;le(a)}catch{}},fe=async()=>{if(j)return;j=!0;let n=++M;try{for(;k!==null;){let n=k,a=A,o=c,s=r().snapshot?.selectedSession?.id,l=r().selectedPath;if(!s||!l||s!==r().snapshot?.currentSessionId||l!==r().snapshot?.selectedSession?.path||r().modelSelectionPending){ue();return}if(r().snapshot?.thinking?.level===n){a===A&&(k=null,t({thinkingPendingLevel:null}));continue}let u;try{u=await e.setThinkingLevel(s,n,l)}catch(e){if(o!==c||l!==r().selectedPath)return;if(a!==A)continue;ue(),i(e),de();return}if(o!==c||l!==r().selectedPath||s!==r().snapshot?.selectedSession?.id)return;if(a===A){if(u.level!==n){ue(),i(Error(In.t(`thinkingNotConfirmed`)));return}le(u),k=null,t({thinkingPendingLevel:null}),oe();return}}}finally{n===M&&(j=!1)}},pe=e=>{let n=r(),i=e.detail??{},a=i.sessionId,o=[`session_start`,`session_switched`,`session_created`].includes(e.type);if(n.cursor!==null&&e.sequence<=n.cursor)return;t({cursor:e.sequence});let s=n.promptAdmissionRecovery,l=s?.commandId,u=n.snapshot?.selectedSession,d=u?.id===a&&u?.path===n.selectedPath&&(i.sessionPath===void 0||i.sessionPath===u?.path);if(d&&s?.sessionId===u?.id&&s?.sessionPath===u?.path&&typeof i.commandId==`string`&&i.commandId===l&&[`prompt_accepted`,`prompt_failed`,`prompt_settled`,`turn_started`,`turn_settled`].includes(e.type)){let r=e.type!==`prompt_failed`;t({promptAdmissionRecovery:null,promptAdmissionResolution:s?{sessionId:s.sessionId,sessionPath:s.sessionPath,commandId:s.commandId,content:s.content,images:s.images}:n.promptAdmissionResolution,liveMessages:r&&s&&!s.delivery?.retryEntryId&&!n.liveMessages.some(e=>e.key===s.optimisticKey)?DJ([...n.liveMessages,{key:s.optimisticKey,timestamp:s.timestamp??e.timestamp,optimistic:{sessionId:s.sessionId,sessionPath:s.sessionPath,commandId:s.commandId,afterEntryId:s.afterEntryId??null,admitted:e.type===`prompt_accepted`},message:{role:`user`,content:s.content}}]):n.liveMessages})}if(e.type===`prompt_accepted`&&d&&u&&typeof i.commandId==`string`&&t({liveMessages:LJ(r().liveMessages,u.id,u.path,i.commandId)}),n=r(),(e.type===`runtime_changed`||e.type===`settings_changed`)&&t(re()),e.type===`runtime_changed`&&B(),n.sessionSwitching&&!o){oe();return}if(typeof a==`string`&&a!==n.snapshot?.currentSessionId&&!o){oe();return}if([`auto_retry_start`,`auto_retry_end`].includes(e.type)&&typeof i.sessionPath==`string`&&i.sessionPath!==(n.snapshot?.currentSessionPath??n.snapshot?.selectedSession?.path)){oe();return}if(!o&&(i.message||e.type.startsWith(`tool_execution_`))&&!rj(n.snapshot)){CJ.has(e.type)&&oe();return}if(n.snapshot){let r=n.snapshot.runtime.liveTools??[],a=sJ(r,e.type,i);a!==r&&t({snapshot:{...n.snapshot,runtime:{...n.snapshot.runtime,liveTools:a}}})}if(o){let o=i.commandId;if(typeof o==`string`&&z.has(o)){oe();return}let s=i.sessionPath,l=n.snapshot?.sessions.some(e=>e.path===s),u=!1;if(y?.kind===`select`?u=y.expectedPath===s:(y?.kind===`create`&&y.commandId===o&&e.type===`session_switched`&&typeof a==`string`&&(!y.expectedSessionId||y.expectedSessionId===a)&&(typeof s!=`string`||!l)||y?.kind===`create`&&y.commandId===o&&e.type===`session_created`&&typeof a==`string`&&(!y.expectedSessionId||a===y.expectedSessionId))&&(u=!0),u&&y?.epoch!==c)return;if(u)t({...H(),liveMessages:IJ(n.liveMessages,n.snapshot?.selectedSession)});else{if(!y&&n.selectedPath&&n.snapshot?.selectedSession?.path===n.selectedPath){B(),ue(),t({...H(),liveMessages:IJ(n.liveMessages,n.snapshot.selectedSession),snapshot:{...n.snapshot,currentSessionId:void 0,currentSessionPath:void 0},modelSelectionPending:!1});let e=c;r().actions.refreshSnapshot({epoch:e});return}B();let e=++c;ue(),_=null,v=null,t({...H(),promptAdmissionPending:!1,promptAdmissionRecovery:null,selectedPath:typeof s==`string`?s:null,draftModel:n.workspaceDraft?n.draftModel:null,modelSelectionPending:!1,sessionSwitching:!0}),r().actions.refreshSnapshot({epoch:e}).then(n=>{e===c&&t({selectedPath:n?r().selectedPath:null,sessionSwitching:!1})})}}else if(e.type===`prompt_accepted`){let e=ee.has(String(i.commandId??``));t({...ae(e,n.livePhase),liveRetry:null,pendingFollowUpsReceipt:Number.isInteger(i.pendingFollowUps)?Number(i.pendingFollowUps):n.pendingFollowUpsReceipt,pendingSteeringReceipt:Number.isInteger(i.pendingSteering)?Number(i.pendingSteering):n.pendingSteeringReceipt})}else if(e.type===`turn_started`)m=e.sequence,t({activeTurn:{sessionId:String(i.sessionId),commandId:String(i.commandId),epoch:Number(i.epoch),...typeof i.sessionPath==`string`?{sessionPath:i.sessionPath}:{},...typeof i.promptEntryId==`string`?{promptEntryId:i.promptEntryId}:{},...typeof i.startedAt==`number`?{startedAt:i.startedAt}:{},...typeof i.elapsedMs==`number`?{elapsedMs:i.elapsedMs}:{}},liveRunning:!0,livePhase:`running`,liveRetry:null,turnTerminalStatus:null});else if(e.type===`agent_start`)m=e.sequence,t({...i.activeTurn?{activeTurn:i.activeTurn}:{},liveRunning:!0,livePhase:`running`,liveRetry:null});else if(e.type===`turn_settled`){V(ee,i.commandId);let r=n.activeTurn;r?.sessionId===i.sessionId&&r?.commandId===i.commandId&&r?.epoch===i.epoch&&(m=e.sequence,t({activeTurn:null,liveRunning:!1,livePhase:`idle`,liveRetry:null,turnTerminalStatus:typeof i.outcome==`string`?i.outcome:null}))}else if(e.type===`agent_settled`)n.activeTurn||(m=e.sequence),t({pendingFollowUpsReceipt:null,pendingSteeringReceipt:null,...n.activeTurn?{}:{liveRunning:!1,livePhase:`idle`,liveRetry:null}});else if(e.type===`prompt_settled`)V(ee,i.commandId),n.livePhase!==`running`&&t({liveRunning:!1,livePhase:`idle`,liveRetry:null});else if(i.message&&typeof i.message==`object`){let r=i.message,a=n.liveMessages,o=typeof i.messageKey==`string`?i.messageKey:`${r.role||`message`}-${e.sequence}`,s={key:o,message:r},c=a.findIndex(e=>e.key===o);a=c>=0?a.map((e,t)=>t===c?s:e):DJ([...a,s]);let l=!FJ(n.liveMessages,a),u=n.thinkingStarts,d=n.thinkingDurations,f=!1;if(r.parts?.some(e=>e.type===`thinking`)&&(u[o]===void 0&&(u={...u,[o]:Date.now()},f=!0),e.type===`message_end`)){let e=jJ(r),t=Date.now()-u[o];d={...d,[o]:t},e&&(d[e]=t),te(e??o),f=!0}if(f||l){let e=ne(a,n.snapshot?.selectedSession?.entries,u,d);e&&(u=e.thinkingStarts,d=e.thinkingDurations,f=!0)}t({liveMessages:a,...f?{thinkingStarts:u,thinkingDurations:d}:{}})}if(e.type===`prompt_discarded`&&typeof i.commandId==`string`&&(V(ee,i.commandId),t({liveMessages:r().liveMessages.filter(e=>e.optimistic?.commandId!==i.commandId)})),e.type===`prompt_failed`){V(ee,i.commandId);let e=typeof i.commandId==`string`&&n.activeTurn?.commandId===i.commandId;t({liveMessages:r().liveMessages.filter(e=>!e.optimistic||e.optimistic.commandId!==i.commandId),...e||n.livePhase!==`running`?{liveRunning:!1,livePhase:`idle`,liveRetry:null}:{},notice:typeof i.error==`string`?i.error:`Prompt failed`})}if(e.type===`auto_retry_start`&&t({liveRunning:!0,livePhase:`running`,liveRetry:{attempt:Number(i.attempt)||0,maxAttempts:Number(i.maxAttempts)||0}}),e.type===`auto_retry_end`&&t({liveRetry:null}),e.type===`thinking_level_changed`){let t=r().snapshot?.thinking;t&&typeof i.level==`string`&&le({...t,level:i.level,revision:e.sequence})}CJ.has(e.type)&&oe()},me=async i=>{let a=500,o=!1;for(;!i.aborted;){let s=!1;try{if(r().cursor===null){if(s=!0,!await r().actions.refreshSnapshot({resetCursor:!0}))throw Error(`snapshot unavailable`);s=!1}if(i.aborted)return;await n({client:e,cursor:r().cursor??0,onConnected:()=>{a=500,t({connection:`connected`}),o&&(o=!1,oe(0))},onEvent:pe,onHeartbeat:()=>oe(0),signal:i})}catch(e){if(i.aborted)return;t({connection:`reconnecting`});let n=!s&&await r().actions.refreshSnapshot({resetCursor:!0});o=!n,n||t(H()),await RJ(a,i),a=Math.min(a*2,5e3),e instanceof SyntaxError&&t({notice:`Invalid event data`})}}},W={rememberPromptProjection(e,n,i){let a=r(),o=a.snapshot?.selectedSession;if(a.selectedPath!==n||o?.id!==e||o.path!==n)return;let s=new Set(o.entries.map(e=>e.id)),c=new Set(a.liveMessages.flatMap(t=>t.optimistic?.sessionId===e&&t.optimistic.sessionPath===n&&t.optimistic.projectedEntryId?[t.optimistic.projectedEntryId]:[])),l=new Map(i.map(e=>[e.key,e.entryId])),u=!1,d=a.liveMessages.map(t=>{let r=l.get(t.key);return!r||!s.has(r)||c.has(r)||t.optimistic?.sessionId!==e||t.optimistic.sessionPath!==n||!t.optimistic.admitted||t.optimistic.projectedEntryId?t:(u=!0,c.add(r),{...t,optimistic:{...t.optimistic,projectedEntryId:r},message:{role:`user`,content:``}})});u&&t({liveMessages:d})},setHistoryAnchor(e){let n=r().snapshot?.selectedSession;if(e&&(n?.id!==e.sessionId||n.path!==e.sessionPath))return;let i=r().historyAnchor;(i?.entryId!==e?.entryId||i?.sessionId!==e?.sessionId||i?.sessionPath!==e?.sessionPath)&&t({historyAnchor:e})},start(){E||(E=new AbortController,me(E.signal))},stop(){E?.abort(),E=null,C!==null&&window.clearTimeout(C),C=null,ue(),B()},async refreshSnapshot(n={}){let a=n.epoch??c,o=++p,l=r().selectedPath;try{let i=r().historyAnchor,u=s?.path===l?s:null,d=u?await e.snapshot(l,void 0,u.id):i&&i.sessionPath===l?await e.snapshot(l,i):await e.snapshot(l);if(a!==c||o!==p)return!1;if(u&&(d.selectedSession?.id!==u.id||d.selectedSession.path!==u.path))throw new tf(In.t(`sessionLinkUnavailable`),409,`SESSION_CONFLICT`);u&&(s=null);let f=typeof d.currentSessionId==`string`,g=f?d.sessions.find(e=>rj(d,e)):void 0,_=f?rj(d):d.selectedSession===void 0,y=d.selectedSession?d.sessions.some(e=>e.id===d.selectedSession.id&&e.path===d.selectedSession.path):!f,b=!l||d.sessions.some(e=>e.path===l),x=!l||d.selectedSession?.path===l;if(!b||!x||!y||!l&&!_)return t({selectedPath:null}),!n.canonicalRetry&&W.refreshSnapshot({...n,canonicalRetry:!0,epoch:a});let S=d.selectedSession?.cwd,C=d.workspaces.find(e=>e.current)?.path,w=d.workspaces.some(e=>e.path===r().selectedWorkspace)?r().selectedWorkspace:void 0,T=r().workspaceDraft?r().selectedWorkspace:S??C??w??null,E=n.resetCursor;r().snapshot?.selectedSession?.path!==d.selectedSession?.path&&(ue(),se()),E&&se();let D=r().snapshot?.currentSessionId,O=r().snapshot?.sessions.find(e=>rj(r().snapshot,e)),k=D!==d.currentSessionId||O?.path!==g?.path,A=r().snapshot?.selectedSession?.id!==d.selectedSession?.id||r().snapshot?.selectedSession?.path!==d.selectedSession?.path,j=r().collapsed;if(A&&!r().workspaceDraft&&d.selectedSession){let e=d.sessions.find(e=>e.id===d.selectedSession.id&&e.path===d.selectedSession.path),t=e?.workspacePath??d.selectedSession.cwd;!e?.archived&&!e?.ungrouped&&j.has(t)&&(j=new Set(j),j.delete(t),EJ(xJ,[...j]))}let M=r().snapshot,N=E||k||A||M?.currentSessionPath!==d.currentSessionPath||JSON.stringify(M?.models)!==JSON.stringify(d.models)||M?.truncation.modelsOmitted!==d.truncation.modelsOmitted;k&&(B(),ue(),se());let P=h!==null&&r().notice===h;h=null,(E||k||A)&&(m=0);let F=m>d.cursor;if(t({...P?{notice:null}:{},...E||k||A?{...H(),liveMessages:IJ(r().liveMessages,d.selectedSession)}:{},connection:r().connection===`connecting`?`connecting`:r().connection,cursor:E||r().cursor===null?d.cursor:Math.max(r().cursor??0,d.cursor),activeTurn:F?r().activeTurn:d.runtime.activeTurn??null,livePhase:F?r().livePhase:d.runtime.status===`running`?`running`:!r().promptAdmissionPending&&!v?`idle`:r().livePhase,liveRetry:!F&&d.runtime.status!==`running`&&!r().promptAdmissionPending&&!v?null:r().liveRetry,liveRunning:F?r().liveRunning:d.runtime.status===`running`?!0:!r().promptAdmissionPending&&!v?!1:r().liveRunning,selectedPath:d.selectedSession?.path??null,selectedWorkspace:T,collapsed:j,snapshot:d,...N?re():{}}),!(E||k||A)){let e=ne(r().liveMessages,d.selectedSession?.entries,r().thinkingStarts,r().thinkingDurations);e&&t(e)}return le(),!0}catch(e){if(a!==c||o!==p)return!1;if(s?.path===l&&e instanceof tf&&[400,404,409].includes(e.status)){s=null,t({selectedPath:null,workspaceDraft:!0});let e=await W.refreshSnapshot({...n,epoch:a});return a===c&&t({notice:In.t(`sessionLinkUnavailable`)}),e}t({connection:`unavailable`}),i(e);let u=r().notice;return h=typeof u==`string`?u:null,!1}},async chooseWorkspace(){let t=c;try{let n=await e.chooseWorkspace();if(t!==c||n.cancelled||!n.path)return;W.setWorkspace(n.path),await W.refreshSnapshot()}catch(e){t===c&&i(e)}},setWorkspace(e){let n=r();e===n.selectedWorkspace&&!n.sessionSwitching||(++c,b=null,ue(),B(),_=null,v=null,t({...H(),...re(),selectedWorkspace:e,createdSession:null,workspaceDraft:!0,sessionSwitching:!1,modelSelectionPending:!1,promptAdmissionPending:!1,promptAdmissionRecovery:null,notice:null}))},async renameWorkspace(t,n){try{await e.renameWorkspace(t,n),await W.refreshSnapshot()}catch(e){throw i(e),e}},async removeWorkspace(n){try{return await e.removeWorkspace(n),r().selectedWorkspace===n&&B(),r().workspaceDraft&&r().selectedWorkspace===n&&t({selectedWorkspace:null}),await W.refreshSnapshot(),!0}catch(e){return i(e),!1}},async prepareSession(){if(r().sessionSwitching||r().modelSelectionPending)return null;r().selectedWorkspace||await W.chooseWorkspace();let e=r(),t=e.selectedWorkspace;if(!t||e.sessionSwitching||e.modelSelectionPending)return null;let n=e.snapshot?.selectedSession;if(!e.workspaceDraft&&n){if(e.selectedPath!==n.path||n.cwd!==t)return null;let r={epoch:c,sessionId:n.id,sessionPath:n.path,workspacePath:t};return!rj(e.snapshot)&&!await W.selectSession(n.path,n.id)?null:a(r)?r:null}return W.createSession(t)},async createSession(n){if(!n||r().modelSelectionPending)return null;let o=++c;ue(),B();let s=(b?.workspacePath===n?b.commandId:void 0)??globalThis.crypto?.randomUUID?.()??`web-create-${Date.now()}-${o}`;b={workspacePath:n,commandId:s},_=null,v=null,t({...H(),...re(),mobileSidebarOpen:!1,promptAdmissionPending:!1,promptAdmissionRecovery:null,selectedPath:null,selectedWorkspace:n,createdSession:null,workspaceDraft:!0,sessionSwitching:!0});let l=null,u=x.then(async()=>{if(o===c){y={commandId:s,epoch:o,expectedPath:null,kind:`create`};try{let u=await e.createSession(n,s);if(o!==c)return;if(u.cancelled||u.commandId!==s||typeof u.sessionId!=`string`||!u.sessionId||u.sessionId.length>128||u.sessionPath!==void 0&&!u.sessionPath)throw Error(`Session creation did not return a valid target identity.`);let d={epoch:o,sessionId:u.sessionId,sessionPath:u.sessionPath??null,workspacePath:n};y?.epoch===o&&(y.expectedSessionId=d.sessionId,y.expectedPath=d.sessionPath),t({selectedPath:d.sessionPath});let f=await W.refreshSnapshot({epoch:o});if(!f&&o===c&&(f=await W.refreshSnapshot({epoch:o})),o!==c)return;if(!f)throw Error(`The created Session could not be confirmed. Please try again.`);if(!a(d)){b=null,i(Error(`The created Session is no longer active in the selected workspace. Please try again.`));return}let p=r().selectedPath;if(!p)return;d.sessionPath=p,t({workspaceDraft:!1,createdSession:d,notice:null});let m=r().draftModel;if(m&&!await U(m,o,d.sessionId,p))return;if(r().workspaceDraft||!a(d)){b=null,i(Error(`The created Session is no longer active in the selected workspace. Please try again.`));return}l=d,b=null}catch(e){if(o!==c)return;t({selectedPath:null}),i(e),await W.refreshSnapshot({epoch:o})}finally{V(z,s),y?.epoch===o&&(y=null),o===c&&t({sessionSwitching:!1})}}});return x=u.catch(()=>void 0),await u,o===c?l:null},async selectSession(n,a){if(!n)return!1;let o=r();if(S?.path===n&&S.epoch===c){let e=S;t({mobileSidebarOpen:!1});let i=await e.promise,o=r();return i&&e.epoch===c&&o.selectedPath===n&&o.snapshot?.selectedSession?.path===n&&(!a||o.snapshot.selectedSession.id===a)&&!o.workspaceDraft&&rj(o.snapshot)}if(!o.workspaceDraft&&!o.sessionSwitching&&o.selectedPath===n&&o.snapshot?.selectedSession?.path===n&&(!a||o.snapshot.selectedSession.id===a)&&rj(o.snapshot))return t({mobileSidebarOpen:!1}),!0;b=null;let s=!o.workspaceDraft&&o.selectedPath===n&&o.snapshot?.selectedSession?.path===n;B(),t({...re(),workspaceDraft:!1,...s?{}:{draftModel:null,createdSession:null},modelSelectionPending:!1});let l=s?c:++c;ue(),s||(_=null,v=null),t({...H(),liveMessages:s?IJ(o.liveMessages,o.snapshot?.selectedSession):[],mobileSidebarOpen:!1,promptAdmissionPending:s?o.promptAdmissionPending:!1,promptAdmissionRecovery:s?o.promptAdmissionRecovery:null,selectedPath:n,sessionSwitching:!0});let u=x.then(async()=>{if(l!==c)return!1;y={epoch:l,expectedPath:n,kind:`select`};try{let i=await(a?e.selectSession(n,a):e.selectSession(n));if(l!==c)return!1;if(i.cancelled)return s||t({selectedPath:null}),await W.refreshSnapshot({epoch:l}),!1;let o=await W.refreshSnapshot({epoch:l});return l===c&&(!o&&!s&&t({selectedPath:null}),o&&r().selectedPath===n&&r().snapshot?.selectedSession?.path===n&&(!a||r().snapshot?.selectedSession?.id===a)&&!r().workspaceDraft&&rj(r().snapshot))}catch(e){return l===c&&(s||t({selectedPath:null}),i(e),await W.refreshSnapshot({epoch:l}),!1)}finally{y?.epoch===l&&(y=null),l===c&&t({sessionSwitching:!1})}});x=u.then(()=>void 0,()=>void 0),S={path:n,epoch:l,promise:u};try{return await u}finally{S?.promise===u&&(S=null)}},async navigateToMessage(n,i){let a=++l;try{if(i?.aborted||await W.selectSession(n.sessionPath)===!1)return!1;let o=c,s=r().snapshot?.selectedSession;if(i?.aborted||a!==l||r().sessionSwitching||s?.id!==n.sessionId||s.path!==n.sessionPath)return!1;let u=await e.sessionMessageWindow(n,i);if(i?.aborted||a!==l||o!==c)return!1;let d=r().snapshot?.selectedSession;return d?.id!==n.sessionId||d.path!==n.sessionPath||u.id!==n.sessionId||u.path!==n.sessionPath||u.history?.anchorEntryId!==n.entryId||u.history.anchorOnBranch!==!0||!u.entries.some(e=>e.id===n.entryId)?!1:(t({historyNavigation:{...n,session:u,revision:(r().historyNavigation?.revision??0)+1}}),!0)}catch{return!1}},async editMessage(e,t){return W.forkMessage(e,{mode:`edit`,content:t})},async regenerateMessage(e){return W.forkMessage(e,{mode:`regenerate`})},acknowledgeRestoredPromptDraft(e){r().restoredPromptDraft?.commandId===e&&t({restoredPromptDraft:null})},async cancelSessionFork(){let n=u;if(!n||n.scope!==`conversation`||!r().sessionForkPending||r().sessionForkCancellation)return;let a=c;t({sessionForkCancellation:`requesting`});try{let i=await e.cancelSessionFork({commandId:n.commandId,sessionId:n.sessionId,sessionPath:n.sessionPath});u===n&&r().sessionForkPending&&(t({sessionForkCancellation:i.state===`not-found`?null:i.state}),i.state===`not-found`&&t({notice:In.t(`sidebarForkCancelUnconfirmed`)}))}catch(e){a===c&&r().sessionForkPending&&(t({sessionForkCancellation:null}),i(e))}},async forkConversation(e,t,n=`local`){return r().sessionForkPending||r().sessionSwitching||d||!await W.selectSession(e,t)?!1:W.forkMessage({scope:`conversation`,sessionPath:e,sessionId:t,environment:n})},async forkMessage(n,i){let a=`scope`in n&&n.scope===`conversation`;if(a&&i||i?.mode===`edit`&&(!i.content.trim()||i.content.length>12e3))return!1;let o=r(),s=o.snapshot?.selectedSession;if(o.sessionForkPending||d)return!1;if(!s||o.workspaceDraft||o.sessionSwitching||o.promptAdmissionPending||o.promptAdmissionRecovery||!a&&(o.liveRunning||o.activeTurn||o.snapshot?.runtime.status!==`idle`)||o.modelSelectionPending||!rj(o.snapshot)||s.id!==n.sessionId||s.path!==n.sessionPath||o.selectedPath!==n.sessionPath||s.path.startsWith(`current:`))return t({notice:In.t(`forkSessionUnavailable`)}),!1;let f=`entryId`in n?n.entryId:void 0,p=u?.sessionId===n.sessionId&&u.sessionPath===n.sessionPath&&u.entryId===f&&u.scope===`conversation`===a&&(!a||u.scope===`conversation`&&(u.environment??`local`)===(n.environment??`local`))&&JSON.stringify(u.rerun)===JSON.stringify(i)?u:{sessionId:n.sessionId,sessionPath:n.sessionPath,...a?{scope:`conversation`,...n.environment===`worktree`?{environment:`worktree`}:{}}:{entryId:f,...i?{rerun:i}:{}},commandId:globalThis.crypto?.randomUUID?.()??`web-fork-${Date.now()}-${++l}`};u=p;let m=c,h=m;t({sessionForkPending:!0,sessionForkCancellation:null,sessionForkEnvironment:a?n.environment??`local`:void 0,notice:null});try{let o=await e.forkSession(p);if(m!==c||r().selectedPath!==n.sessionPath)return!1;if(o.commandId!==p.commandId||o.source.sessionId!==n.sessionId||o.source.sessionPath!==n.sessionPath||!a&&o.source.entryId!==f||!o.source.entryId)throw Error(In.t(`forkSessionUncertain`));if(o.state!==`forked`)return t({notice:[In.t(o.state===`cancelled`?`forkSessionCancelled`:`forkSessionUncertain`),o.reason,o.preservedWorktreePath?In.t(`sidebarForkWorktreePreserved`,{path:o.preservedWorktreePath}):void 0].filter(Boolean).join(` `)}),o.state===`cancelled`?u=null:await W.refreshSnapshot({epoch:m}),!1;if(!o.sessionId||!o.sessionPath||o.sessionId===n.sessionId||o.sessionPath===n.sessionPath)throw Error(In.t(`forkSessionUncertain`));let s=++c;h=s,v=null,_=null,ue(),B(),t({...H(),...re(),selectedPath:o.sessionPath,historyAnchor:null,historyNavigation:null,createdSession:null,draftModel:null,sessionSwitching:!0});let l=await W.refreshSnapshot({epoch:s});if(!l&&s===c&&r().selectedPath===o.sessionPath&&(l=await W.refreshSnapshot({epoch:s})),s!==c)return!1;let d=r().snapshot;if(o.replayed&&l&&d?.selectedSession?.id===o.sessionId&&d.selectedSession.path===o.sessionPath&&!rj(d)){if(l=await W.selectSession(o.sessionPath,o.sessionId)===!0,s!==c)return!1;d=r().snapshot}if(!l||r().selectedPath!==o.sessionPath||d?.selectedSession?.id!==o.sessionId||d.selectedSession.path!==o.sessionPath||!rj(d))return t({notice:In.t(`forkSessionUncertain`)}),!1;if(u=null,i){let e=o.prompt;if(!e||typeof e.content!=`string`||!Array.isArray(e.images))throw Error(In.t(`forkSessionUncertain`));t({sessionForkPending:!1,sessionSwitching:!1});let n=W.sendPrompt(e.content,e.images,void 0,void 0,{epoch:s,sessionId:o.sessionId,sessionPath:o.sessionPath,workspacePath:d.selectedSession.cwd}),i=[...r().liveMessages].reverse().find(e=>e.optimistic?.sessionId===o.sessionId&&e.optimistic?.sessionPath===o.sessionPath)?.optimistic?.commandId??p.commandId,a=await n;return s!==c||r().selectedPath!==o.sessionPath?!1:a?(t({notice:{kind:`success`,message:In.t(`messageRerunStarted`)}}),!0):(r().promptAdmissionRecovery||t({restoredPromptDraft:{sessionId:o.sessionId,sessionPath:o.sessionPath,commandId:i,content:e.content,images:e.images}}),!1)}return t({notice:{kind:`success`,message:In.t(`forkSessionCreated`)}}),!0}catch(e){return h===c&&(e instanceof tf&&[`SESSION_CONFLICT`,`SESSION_FORK_UNAVAILABLE`,`SESSION_FORK_CAPACITY`].includes(e.code??``)?(u=null,t({notice:a?e.message:In.t(`forkSessionUnavailable`)})):t({notice:In.t(`forkSessionUncertain`)})),!1}finally{t({sessionForkPending:!1,sessionForkCancellation:null,sessionForkEnvironment:void 0}),c===h&&h!==m&&r().sessionSwitching&&t({sessionSwitching:!1})}},async savePreferences(t){try{await e.savePreferences(t),await W.refreshSnapshot()}catch(e){throw i(e),e}},async renameSession(t,n){try{await e.renameSession(t,n),await W.refreshSnapshot()}catch(e){throw i(e),e}},async releaseSessionWorktree(t){let n=JSON.stringify([t.sessionId,t.sessionPath,t.worktreePath]),r=f.get(n);if(r?.pending)return r.pending;if(!r&&f.size>=128){let e=[...f].find(([,e])=>e.state===`preserved`&&!e.pending);if(e)f.delete(e[0]);else throw Error(In.t(`managedWorktreeRecoveryFull`))}let i={commandId:r?.state===`uncertain`?r.commandId:crypto.randomUUID(),state:`uncertain`,pending:void 0};return f.set(n,i),i.pending=(async()=>{try{let r=await e.releaseSessionWorktree({...t,commandId:i.commandId});if(r.commandId!==i.commandId||r.sessionId!==t.sessionId||r.sessionPath!==t.sessionPath||r.worktreePath!==t.worktreePath||![`removed`,`preserved`,`uncertain`].includes(r.state))throw Error(In.t(`managedWorktreeUncertain`));return r.state===`removed`?f.delete(n):i.state=r.state,r}finally{i.pending=void 0}})(),i.pending},async deleteSession(n,a,o){if(d||r().sessionForkPending||r().sessionSwitching)return!1;d=!0;let s=c;try{let i=await e.deleteSession({sessionPath:n,sessionId:a,commandId:o});if(i.commandId!==o||i.sessionId!==a||i.sessionPath!==n)throw Error(In.t(`sessionDeleteUncertain`));return i.state===`deleted`?(s===c&&r().selectedPath===n&&(++c,ue(),B(),_=null,v=null,t({...H(),...re(),selectedPath:null,historyAnchor:null,historyNavigation:null,workspaceDraft:!0,createdSession:null})),await W.refreshSnapshot(),t({notice:i.worktreeReleaseTarget?{kind:`success`,message:In.t(`managedWorktreeRetainedAfterDelete`,{path:i.worktreeReleaseTarget.worktreePath})}:i.metadataCleanupPending?In.t(`sessionDeleteMetadataPending`):{kind:`success`,message:In.t(`sessionDeleted`)}}),!0):(s===c&&(await W.refreshSnapshot({epoch:s}),t({notice:In.t(i.state===`cancelled`?`sessionDeleteCancelled`:`sessionDeleteUncertain`)})),!1)}catch(e){return s===c&&i(e),!1}finally{d=!1}},async setSessionPin(t,n,r,a){try{await e.setSessionPin(t,n,r,a),await W.refreshSnapshot()}catch(e){throw i(e),e}},async archiveSession(n){let a=r().snapshot?.sessions.find(e=>e.path===n);try{await e.archiveSession(n);let r={key:crypto.randomUUID(),path:n,sessionId:a?.id,title:ZA(a??{},In.t(`untitledSession`))};t(e=>({archiveNotices:[r,...e.archiveNotices.filter(e=>e.path!==n)].slice(0,3)})),await W.refreshSnapshot()}catch(e){i(e)}},dismissArchiveNotice(e){t(t=>({archiveNotices:t.archiveNotices.filter(t=>t.key!==e)}))},async setSidebarPin(t,n,r){try{await e.setSidebarPin(t,n,r),await W.refreshSnapshot()}catch(e){throw i(e),e}},async setWorkspaceOrder(t,n){try{await e.setWorkspaceOrder(t,n),await W.refreshSnapshot()}catch(e){throw e instanceof tf&&e.code===`WORKSPACE_ORDER_CHANGED`&&await W.refreshSnapshot(),i(e),e}},async setSessionOrder(t,n,r){try{await e.setSessionOrder(t,n,r),await W.refreshSnapshot()}catch(e){throw i(e),e}},async setSessionRead(t,n,r,a){try{await e.setSessionRead(t,n,r,a),await W.refreshSnapshot()}catch(e){throw e instanceof tf&&e.code===`SESSION_READ_STATE_CHANGED`?await W.refreshSnapshot():i(e),e}},async unarchiveSession(n){let r=c;try{if(await e.unarchiveSession(n),t(e=>({archiveNotices:e.archiveNotices.filter(e=>e.path!==n)})),r!==c)return!0;let i=p,a=await W.refreshSnapshot({epoch:r});return!a&&r===c&&p>i+1&&(a=await W.refreshSnapshot({epoch:r})),r!==c||a}catch(e){return r===c&&i(e),!1}},async selectModel(e){let[n,...i]=e.split(`/`),a=i.join(`/`),o=r();if(!n||!a||o.sessionSwitching||o.modelSelectionPending||o.promptAdmissionPending||!o.workspaceDraft&&(o.liveRunning||o.snapshot?.runtime.status===`running`))return!1;let s=o.snapshot?.selectedSession?.id;if(o.workspaceDraft||!s&&!o.snapshot?.currentSessionId){let e=[...o.snapshot?.models??[],...o.modelSearch.models].find(e=>e.provider===n&&e.id===a);return e&&t({draftModel:e,notice:null}),!!e}return!s||!o.selectedPath||!rj(o.snapshot)||s!==o.snapshot?.currentSessionId||o.selectedPath!==o.snapshot?.selectedSession?.path?!1:(ue(),U({provider:n,id:a},c,s,o.selectedPath))},async searchModels(n){let i=n.trim();if(!i){t(re());return}D?.abort();let a=new AbortController;D=a;let o=++O,s=c,l=r().snapshot?.currentSessionId;t({modelSearch:{query:i,status:`loading`,models:[],totalMatches:0,matchesOmitted:0,error:null}});try{let n=await e.searchModels(i,l,a.signal);if(a.signal.aborted||s!==c||o!==O)return;t({modelSearch:{query:i,status:`ready`,models:n.models,totalMatches:n.totalMatches,matchesOmitted:n.truncation.matchesOmitted,error:null}})}catch(e){if(a.signal.aborted||s!==c||o!==O)return;t({modelSearch:{query:i,status:`error`,models:[],totalMatches:0,matchesOmitted:0,error:e instanceof Error?e.message:String(e)}})}finally{D===a&&(D=null)}},clearModelSearch(){t(re())},selectThinking(e){let n=r(),i=n.snapshot?.thinking,a=n.snapshot?.selectedSession?.id;!e||!i?.supported||n.sessionSwitching||n.modelSelectionPending||n.workspaceDraft||!a||!rj(n.snapshot)||a!==n.snapshot?.currentSessionId||n.selectedPath!==n.snapshot?.selectedSession?.path||n.liveRunning||n.snapshot?.runtime.status===`running`||e!==(n.thinkingPendingLevel??i.level)&&(k=e,A++,t({thinkingPendingLevel:e}),fe())},async selectPlanMode(n){let a=r(),o=a.snapshot,s=o?.selectedSession;if(!o||!s||!rj(o,s)||a.workspaceDraft||a.sessionSwitching||a.planSelectionPending||a.promptAdmissionPending||a.promptAdmissionRecovery||a.liveRunning||o.runtime.status!==`idle`||o.runtime.planRevision===void 0)return;let l=c,u=++R;t({planSelectionPending:!0});try{if(await e.setPlanMode(s.id,s.path,n,o.runtime.planRevision),l===c&&u===R&&!await W.refreshSnapshot({epoch:l}))throw Error(In.t(`planModeUnconfirmed`))}catch(e){l===c&&u===R&&(await W.refreshSnapshot({epoch:l}),l===c&&u===R&&i(e))}finally{l===c&&u===R&&t({planSelectionPending:!1})}},async preparePlanImplementation(){let n=r(),a=n.snapshot,o=a?.selectedSession,s=o?.id;if(!s||!rj(a,o)||s!==a?.currentSessionId||!o?.path||n.selectedPath!==o.path||n.workspaceDraft||n.sessionSwitching||n.planSelectionPending||n.promptAdmissionPending||n.promptAdmissionRecovery||n.liveRunning||a.runtime.status!==`idle`||a.runtime.plan!==`ready`||typeof a.runtime.planRevision!=`string`)return null;let l=c,u=++R,d=o.path,f=a.runtime.planRevision;t({planSelectionPending:!0});try{let t;try{t=await e.preparePlanImplementation(s,d,f)}catch(e){if(l===c&&u===R){try{await W.refreshSnapshot({epoch:l})}catch{}l===c&&u===R&&i(e)}return null}let n=r();return l!==c||u!==R||!rj(n.snapshot)||n.snapshot?.currentSessionId!==s||n.snapshot.selectedSession?.path!==d||n.selectedPath!==d?null:t.sessionId!==s||t.status!==`ready`||t.revision!==f||n.snapshot?.runtime.plan!==`ready`||n.snapshot.runtime.planRevision!==f?(i(Error(In.t(`planModeUnconfirmed`))),null):{prompt:t.prompt,sessionId:s,sessionPath:d,planRevision:f}}finally{l===c&&u===R&&t({planSelectionPending:!1})}},async cancelActiveTurn(){let n=r().activeTurn??r().snapshot?.runtime.activeTurn;if(!n||!rj(r().snapshot)||r().turnCancellationPending||r().sessionSwitching)return;let a=c;t({turnCancellationPending:!0});try{await e.cancelActiveTurn(n)}catch(e){if(a!==c)return;await W.refreshSnapshot({epoch:a}),a===c&&i(e)}finally{a===c&&t({turnCancellationPending:!1})}},async sendPrompt(n,o=[],s,l,u){if(r().sessionForkPending||r().planSelectionPending)return!1;let d=n.trim();if(d.length>12e3)return t({notice:In.t(`promptTooLong`,{count:d.length,limit:Hd})}),!1;let f=o.map(({data:e,mimeType:t,name:n})=>({data:e,mimeType:t,...n===void 0?{}:{name:n}})),p=JSON.stringify(f.map(({data:e,mimeType:t,name:n})=>[t,n??``,e])),m=r();if(u&&(u.epoch!==c||!a(u)||m.workspaceDraft))return!1;let h=m.promptAdmissionRecovery,y=h?.phase===`submitting`?h:null,b=m.activeTurn??m.snapshot?.runtime.activeTurn;if(l?.streamingBehavior===`steer`&&!y&&(s||m.turnCancellationPending||!b||b.commandId!==l.expectedTurnCommandId||m.workspaceDraft))return t({notice:In.t(`steerStaleTurn`)}),!1;let x=m.selectedWorkspace;if(!x||!d&&f.length===0&&!l?.retryEntryId||m.sessionSwitching||m.promptAdmissionPending||h&&!y||m.promptAdmissionResolution||m.modelSelectionPending||m.thinkingPendingLevel!==null)return!1;let S=r().workspaceDraft||!r().snapshot?.selectedSession?.id;if(s&&S)return!1;let C=S?await W.createSession(x):null;if(S&&!C)return r().notice||t({notice:`The active Session changed before the first message was sent. Your message was not sent.`}),!1;if(S&&r().draftModel)return!1;let w=r().snapshot?.selectedSession,T=C??(w?{epoch:c,sessionId:w.id,sessionPath:w.path,workspacePath:x}:null);if(!T||r().workspaceDraft||!a(T)||r().sessionSwitching||r().promptAdmissionPending||y&&(r().promptAdmissionRecovery?.commandId!==y.commandId||r().promptAdmissionRecovery?.phase!==`submitting`))return!1;let{epoch:E,sessionId:D,sessionPath:O}=T;if(!O||s&&(s.sessionId!==D||s.sessionPath!==O||!s.planRevision))return!1;let k=r().draftModel;if(k&&!await U(k,E,D,O)||r().workspaceDraft||!a(T)||y&&(r().promptAdmissionRecovery?.commandId!==y.commandId||r().promptAdmissionRecovery?.phase!==`submitting`))return!1;let A=++g,j=v?.sessionId===D&&v.sessionPath===O&&v.content===d&&v.imageSignature===p&&v.planRevision===s?.planRevision&&(v.delivery?.streamingBehavior??`followUp`)===(l?.streamingBehavior??`followUp`)&&v.delivery?.expectedTurnCommandId===l?.expectedTurnCommandId&&v.delivery?.retryEntryId===l?.retryEntryId,M=j?v.commandId:globalThis.crypto?.randomUUID?.()??`web-prompt-${Date.now()}-${A}`,N=j?v.optimisticKey:`optimistic-${M}`,P=j?v.timestamp:new Date().toISOString(),F=j?v.afterEntryId:r().snapshot?.selectedSession?.history?.leafEntryId??r().snapshot?.selectedSession?.entries.at(-1)?.id??null;v={sessionId:D,sessionPath:O,content:d,imageSignature:p,images:f,commandId:M,optimisticKey:N,timestamp:P,afterEntryId:F,...s?{planRevision:s.planRevision}:{},...l?{delivery:l}:{}},_=A,t({liveMessages:j||l?.retryEntryId?r().liveMessages:DJ([...r().liveMessages,{key:N,timestamp:P,optimistic:{sessionId:D,sessionPath:O,commandId:M,afterEntryId:F,admitted:!1},message:{role:`user`,content:d,...f.length>0?{parts:f.map(e=>({type:`image`,mimeType:e.mimeType,...e.name?{name:e.name}:{},previewUrl:`data:${e.mimeType};base64,${e.data}`}))}:{}}}]),notice:null,pendingFollowUpsReceipt:null,pendingSteeringReceipt:null,turnTerminalStatus:null,promptAdmissionPending:!0,scrollToBottom:r().scrollToBottom+1});try{let n=l?await e.prompt(D,d,M,O,j,f,s?.planRevision,l):s?await e.prompt(D,d,M,O,j,f,s.planRevision):await e.prompt(D,d,M,O,j,f);if(E!==c||O!==r().selectedPath||D!==r().snapshot?.selectedSession?.id||_!==A)return!1;let i=ee.has(n.id);return v?.commandId===M&&(v=null),t({liveMessages:n.accepted&&n.id===M?LJ(r().liveMessages,D,O,M):r().liveMessages,...rj(r().snapshot)?ae(i,r().livePhase):{},pendingFollowUpsReceipt:rj(r().snapshot)?n.pendingFollowUps??null:null,pendingSteeringReceipt:rj(r().snapshot)?n.pendingSteering??null:null,...y&&r().promptAdmissionRecovery?.commandId===y.commandId?{promptAdmissionRecovery:null,...j?{promptAdmissionResolution:{sessionId:y.sessionId,sessionPath:y.sessionPath,commandId:y.commandId,content:y.content,images:y.images}}:{}}:{}}),oe(120),!0}catch(e){if(E!==c||O!==r().selectedPath||D!==r().snapshot?.selectedSession?.id||_!==A)return!1;let n=e instanceof tf&&[`PLAN_BUSY`,`PLAN_CONFLICT`,`PLAN_CONTROL_UNAVAILABLE`].includes(e.code??``),a=n||e instanceof tf&&[`WORKSPACE_REQUIRED`,`SESSION_CONFLICT`,`TURN_CONFLICT`,`PROMPT_REJECTED`,`COMMAND_CONFLICT`,`PROMPT_ADMISSION_CAPACITY`,`INVALID_PROMPT`,`INVALID_PROMPT_IMAGES`].includes(e.code??``),o=ee.has(M)||r().liveMessages.some(e=>e.optimistic?.sessionId===D&&e.optimistic.sessionPath===O&&e.optimistic.commandId===M&&e.optimistic.admitted)||r().activeTurn?.sessionId===D&&r().activeTurn?.commandId===M;if(!a&&o)return v?.commandId===M&&(v=null),y&&r().promptAdmissionRecovery?.commandId===y.commandId&&t({promptAdmissionRecovery:null,...j?{promptAdmissionResolution:{sessionId:y.sessionId,sessionPath:y.sessionPath,commandId:y.commandId,content:y.content,images:y.images}}:{}}),!0;if(!a&&v?.commandId===M){let n=v;v=null,t({notice:null,promptAdmissionPending:!1,promptAdmissionRecovery:{...n,retryable:!(e instanceof tf)||e.code!==`COMMAND_ADMISSION_UNKNOWN`,phase:`checking`}});let i=await W.refreshSnapshot({resetCursor:!0,epoch:E}),a=r().promptAdmissionRecovery;if(a?.commandId===M){if(r().activeTurn?.sessionId===D&&r().activeTurn?.commandId===M&&r().selectedPath===O&&r().snapshot?.selectedSession?.path===O&&rj(r().snapshot))return t({promptAdmissionRecovery:null,promptAdmissionResolution:{sessionId:a.sessionId,sessionPath:a.sessionPath,commandId:a.commandId,content:a.content,images:a.images}}),!0;t({promptAdmissionRecovery:{...a,phase:i?`ready`:`verification-failed`}})}return!1}return a?(v?.commandId===M&&(v=null),t({liveMessages:r().liveMessages.filter(e=>e.key!==N),...j&&y&&e instanceof tf&&e.code===`PROMPT_REJECTED`?{promptAdmissionRecovery:null}:{}}),n&&(await W.refreshSnapshot({epoch:E}),E!==c||O!==r().selectedPath||_!==A)||i(e),!1):(i(e),!1)}finally{E===c&&_===A&&(_=null,t({promptAdmissionPending:!1}))}},async checkPromptAdmissionRecovery(){let e=r().promptAdmissionRecovery;if(!e||e.phase!==`verification-failed`)return;let n=c;t({notice:null,promptAdmissionRecovery:{...e,phase:`checking`}});let i=await W.refreshSnapshot({resetCursor:!0,epoch:n}),a=r().promptAdmissionRecovery;a?.commandId===e.commandId&&a.phase===`checking`&&t({promptAdmissionRecovery:{...a,phase:i?`ready`:`verification-failed`}})},async retryPromptAdmission(){let e=r().promptAdmissionRecovery;if(!e?.retryable||e.phase!==`ready`||e.sessionPath!==r().selectedPath||e.sessionPath!==r().snapshot?.selectedSession?.path||e.sessionId!==r().snapshot?.selectedSession?.id)return!1;let n=e.images??[];v={...e,images:n,imageSignature:JSON.stringify(n.map(({data:e,mimeType:t,name:n})=>[t,n??``,e])),afterEntryId:e.afterEntryId??null,timestamp:e.timestamp??new Date().toISOString()},t({promptAdmissionRecovery:{...e,phase:`submitting`},notice:null});try{return await W.sendPrompt(e.content,n,e.planRevision?{sessionId:e.sessionId,sessionPath:e.sessionPath,planRevision:e.planRevision}:void 0,e.delivery)}finally{let n=r().promptAdmissionRecovery;n?.commandId===e.commandId&&n.phase===`submitting`&&t({promptAdmissionRecovery:{...n,phase:`ready`}})}},async sendPromptAsNew(e,n,i,a,o){let s=r().promptAdmissionRecovery;if(!s||s.phase!==`ready`||s.sessionPath!==r().selectedPath||s.sessionPath!==r().snapshot?.selectedSession?.path||s.sessionId!==r().snapshot?.selectedSession?.id)return!1;let c=e.trim(),l=n??s.images??[];if(!c&&l.length===0)return!1;v=null,t({promptAdmissionRecovery:{...s,phase:`submitting`},notice:null});let u=!1;try{let e=s.planRevision?{sessionId:s.sessionId,sessionPath:s.sessionPath,planRevision:s.planRevision}:i;return u=e?await W.sendPrompt(c,l,e,void 0,o):await W.sendPrompt(c,l,void 0,void 0,o),u}finally{let e=r().promptAdmissionRecovery;e?.commandId===s.commandId&&e.phase===`submitting`&&t({promptAdmissionRecovery:u?null:{...e,phase:`ready`}})}},abandonPromptAdmission(){let e=r().promptAdmissionRecovery;!e||e.phase===`submitting`||(v?.commandId===e.commandId&&(v=null),t({liveMessages:r().liveMessages.filter(t=>t.key!==e.optimisticKey),notice:null,promptAdmissionRecovery:null}))},acknowledgePromptAdmissionResolution(e){r().promptAdmissionResolution?.commandId===e&&t({promptAdmissionResolution:null})},async discoverCommands(){let n=r(),i=n.snapshot?.selectedSession?.id;if(n.workspaceDraft||!i||!rj(n.snapshot)||i!==n.snapshot?.currentSessionId||n.selectedPath!==n.snapshot?.selectedSession?.path||n.sessionSwitching){B();return}if(n.commandDiscovery.sessionId===i&&(n.commandDiscovery.status===`loading`||n.commandDiscovery.status===`ready`))return;let a=c,o=++L;I?.abort();let s=new AbortController;I=s,t({commandDiscovery:{sessionId:i,status:`loading`,commands:[],totalAvailable:0,commandsOmitted:0,error:null}});try{let n=await e.commands(i,s.signal);if(s.signal.aborted||a!==c||o!==L||i!==r().snapshot?.currentSessionId)return;t({commandDiscovery:{sessionId:i,status:`ready`,commands:n.commands,totalAvailable:n.totalAvailable,commandsOmitted:n.truncation.commandsOmitted,error:null}})}catch(e){if(s.signal.aborted||a!==c||o!==L)return;t({commandDiscovery:{sessionId:i,status:`error`,commands:[],totalAvailable:0,commandsOmitted:0,error:e instanceof Error?e.message:String(e)}})}finally{I===s&&(I=null)}},clearCommandDiscovery:B,setQuery(e){t({query:e})},setSearchOpen(e){t({searchOpen:e,...e?{}:{query:``}})},toggleWorkspace(e){let n=new Set(r().collapsed);n.has(e)?n.delete(e):n.add(e),EJ(xJ,[...n]),t({collapsed:n})},toggleSidebar(e){if(e){t({mobileSidebarOpen:!r().mobileSidebarOpen});return}let n=!r().sidebarCollapsed;try{window.sessionStorage.setItem(SJ,String(n))}catch{}t({sidebarCollapsed:n})},closeMobileSidebar(){t({mobileSidebarOpen:!1})},clearNotice(){t({notice:null})}};return{planSelectionPending:!1,activeTurn:null,turnCancellationPending:!1,turnTerminalStatus:null,pendingFollowUpsReceipt:null,pendingSteeringReceipt:null,snapshot:null,historyAnchor:null,historyNavigation:null,sessionForkPending:!1,sessionForkCancellation:null,cursor:null,selectedPath:s?.path??null,selectedWorkspace:null,workspaceDraft:o&&!s,draftModel:null,createdSession:null,modelSelectionPending:!1,modelSearch:{query:``,status:`idle`,models:[],totalMatches:0,matchesOmitted:0,error:null},collapsed:wJ(xJ),sidebarCollapsed:TJ(SJ),mobileSidebarOpen:!1,query:``,searchOpen:!1,connection:`connecting`,archiveNotices:[],notice:o&&!s?In.t(`sessionLinkUnavailable`):null,liveMessages:[],liveRunning:!1,livePhase:`idle`,liveRetry:null,thinkingStarts:{},thinkingDurations:{},promptAdmissionPending:!1,promptAdmissionRecovery:null,promptAdmissionResolution:null,restoredPromptDraft:null,sessionSwitching:!1,scrollToBottom:0,thinkingPendingLevel:null,commandDiscovery:ie(),actions:W}})}var VJ=BJ(),HJ=340,UJ=220,WJ=520,GJ=190,KJ=520,qJ=360,JJ=720,YJ=320,XJ=440,ZJ=1100;function QJ(e,t,n){return Math.min(n,Math.max(t,e))}function $J(){UR();let e=pr(VJ),{t}=cr(),{actions:n}=e,r=(0,_.useRef)(null),i=(0,_.useRef)(null),a=(0,_.useRef)(!1),o=(0,_.useRef)(null),s=(0,_.useRef)(null),c=(0,_.useRef)(null),l=(0,_.useRef)(null),u=(0,_.useRef)(void 0),d=(0,_.useCallback)(e=>{u.current=e},[]),f=(0,_.useMemo)(gL,[]),p=(0,_.useRef)(new Set),[,m]=(0,_.useState)(0),[h,g]=(0,_.useState)(null),v=(0,_.useMemo)(()=>new Map,[]),[y,b]=(0,_.useState)(!1),[x,S]=(0,_.useState)(),[C,w]=(0,_.useState)(!1),[T,E]=(0,_.useState)(!1),[D,O]=(0,_.useState)(()=>window.innerWidth),[k,A]=(0,_.useState)({sidebar:HJ,auxiliary:KJ}),[j,M]=(0,_.useState)(!1),N=!!e.snapshot,P=e.snapshot?.preferences.sidebarWidth,F=e.snapshot?.preferences.auxiliaryWidth;(0,_.useEffect)(()=>{!N||j||C||A({sidebar:P??HJ,auxiliary:F??KJ})},[P,F,N,j,C]),(0,_.useEffect)(()=>{if(!j||C)return;let e=window.setTimeout(()=>{n.savePreferences({sidebarWidth:k.sidebar,auxiliaryWidth:k.auxiliary}).catch(()=>void 0)},200);return()=>window.clearTimeout(e)},[n,k,j,C]);let I=(e,t)=>{M(!0),A(n=>({...n,[e]:t}))},[L,R]=(0,_.useState)(()=>window.matchMedia?.(`(max-width: 760px)`).matches??!1),ee=L&&e.mobileSidebarOpen;(0,_.useEffect)(()=>{let e=window.matchMedia?.(`(max-width: 760px)`);if(!e)return;let t=()=>{R(e.matches),e.matches||n.closeMobileSidebar()};return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[n]),(0,_.useEffect)(()=>{let e=()=>O(window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let[z,B]=(0,_.useState)(`chat`),[V,H]=(0,_.useState)(null),[te,ne]=(0,_.useState)(null),[re,ie]=(0,_.useState)(aJ);(0,_.useEffect)(()=>{let e=()=>oJ(re);e(),window.addEventListener(`pagehide`,e);let t=()=>{document.visibilityState===`hidden`&&e()};return document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`pagehide`,e),document.removeEventListener(`visibilitychange`,t),e()}},[re]);let ae=e.workspaceDraft?void 0:e.snapshot?.selectedSession,U=re.find(e=>e.sessionId===ae?.id&&e.sessionPath===ae?.path),oe=U?.open??!1,se=U?.reviewTurn,ce=(0,_.useCallback)(e=>{let t=VJ.getState().snapshot?.selectedSession;t&&ie(n=>n.map(n=>n.sessionId===t.id&&n.sessionPath===t.path?e(n):n))},[]),le=(0,_.useCallback)(e=>ce(t=>({...t,open:e})),[ce]),ue=e=>ce(t=>({...t,reviewTurn:e??void 0})),[de,fe]=(0,_.useState)(null),[pe,me]=(0,_.useState)(ZI),W=(0,_.useCallback)((e,t)=>{let n=VJ.getState(),r=n.snapshot?.selectedSession;n.workspaceDraft||n.sessionSwitching||!r||!r.id||(a.current||(i.current=document.activeElement instanceof HTMLElement?document.activeElement:null),a.current=!0,c.current=null,le(!1),me(n=>({sessionId:r.id,sessionPath:r.path,id:e,kind:t,navigation:(n?.navigation??0)+1})))},[le]),he=pe&&!e.workspaceDraft&&!e.sessionSwitching&&pe.sessionId===e.snapshot?.selectedSession?.id&&pe.sessionPath===e.snapshot?.selectedSession?.path;(0,_.useEffect)(()=>{e.snapshot&&!e.sessionSwitching&&pe&&!he&&me(null)},[e.snapshot,e.sessionSwitching,pe,he]),(0,_.useEffect)(()=>QI(pe),[pe]),(0,_.useEffect)(()=>{if(he||!a.current)return;a.current=!1;let e=i.current;i.current=null,queueMicrotask(()=>{e?.isConnected&&e.checkVisibility()&&e.focus()})},[he]);let ge=e.snapshot?.models.find(e=>e.current),_e=JSON.stringify([ge?.provider,ge?.id]),ve=t=>{let n=e.snapshot,r=n?.selectedSession;e.workspaceDraft||!n||!r||e.sessionSwitching||!rj(n,r)||(c.current=null,le(!1),H({sessionId:r.id,sessionPath:r.path,cwd:r.cwd,model:ge?.label??``,modelKey:_e,terminalId:t}))},ye=V&&!e.workspaceDraft&&!e.sessionSwitching&&rj(e.snapshot,{id:V.sessionId,path:V.sessionPath})&&V.sessionPath===e.snapshot?.selectedSession?.path&&V.modelKey===_e;(0,_.useEffect)(()=>{V&&!ye&&H(null)},[V,ye]);let be=(0,_.useCallback)(()=>{H(null);let e=o.current;o.current=null,e&&requestAnimationFrame(()=>{e.isConnected&&e.checkVisibility()&&e.focus()})},[]),xe=te&&!e.workspaceDraft&&!e.sessionSwitching&&rj(e.snapshot,{id:te.sessionId,path:te.sessionPath})&&te.sessionPath===e.snapshot?.selectedSession?.path;(0,_.useEffect)(()=>{te&&!xe&&ne(null)},[te,xe]);let Se=async(e=`general`)=>{s.current=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=await n.prepareSession();if(!t)return;let r=VJ.getState(),i=r.snapshot,a=i?.selectedSession;r.workspaceDraft||!a||r.sessionSwitching||!rj(i,a)||a.id!==t.sessionId||a.path!==t.sessionPath||(n.closeMobileSidebar(),H(null),me(null),c.current=null,le(!1),ne({sessionId:a.id,sessionPath:a.path,cwd:a.cwd,entry:e}))},Ce=(0,_.useCallback)(()=>{ne(null);let e=new URL(window.location.href);e.searchParams.delete(`settings`),window.history.replaceState(window.history.state,``,e),requestAnimationFrame(()=>{let e=s.current;s.current=null,e?.isConnected&&e.checkVisibility()?e.focus():document.querySelector(`[data-provider-settings-trigger]`)?.focus()})},[]),we=()=>{o.current=s.current??document.querySelector(`[data-provider-settings-trigger]`),ne(null),ve()},Te=async e=>{if(await n.sendPrompt(`/openpi-setup ${e}`))return!0;let r=VJ.getState();throw Error((typeof r.notice==`string`?r.notice:null)||t(r.promptAdmissionRecovery?`setupResolveAdmission`:r.liveRunning||r.activeTurn?`settingsSetupBusyHint`:`setupRequestFailed`))};(0,_.useEffect)(()=>(n.start(),n.stop),[n]);let G=e.workspaceDraft?void 0:e.snapshot?.selectedSession,Ee=_L(G),De=G?.id,Oe=G?.path,ke=!!(G&&!p.current.has(Ee)&&f.get(Ee)?.position?.key&&f.get(Ee)?.position?.pinned===!1);(0,_.useEffect)(()=>{let t=VJ.getState(),n=t.workspaceDraft?void 0:t.snapshot?.selectedSession;if(!n||n.id!==De||n.path!==Oe||e.sessionSwitching||p.current.has(Ee))return;let r=f.get(Ee)?.position,i=()=>{p.current.add(Ee),m(e=>e+1)};if(!r?.key||r.pinned||f.get(Ee)?.window||e.historyNavigation?.sessionId===n.id&&e.historyNavigation.sessionPath===n.path){i();return}let a={sessionId:n.id,sessionPath:n.path,entryId:r.entryId??r.key},o=new AbortController,s,c=e=>{let t=e.target;!(t instanceof Element)||!t.closest(`.conversation, .turn-rail, .jump-to-latest`)||e instanceof KeyboardEvent&&![`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `].includes(e.key)||(o.abort(),i(),g(e=>e?.sessionId===a.sessionId&&e.sessionPath===a.sessionPath?null:e))};for(let e of[`wheel`,`touchstart`,`pointerdown`,`keydown`])document.addEventListener(e,c,!0);let l=e=>{let t=VJ.getState();o.signal.aborted||p.current.has(Ee)||t.historyNavigation||t.sessionSwitching||t.workspaceDraft||t.selectedPath!==a.sessionPath||t.snapshot?.selectedSession?.id!==a.sessionId||t.snapshot.selectedSession.path!==a.sessionPath||f.get(Ee)?.position!==r||e.id!==a.sessionId||e.path!==a.sessionPath||e.history?.anchorEntryId!==a.entryId||e.history.anchorOnBranch!==!0||!e.entries.some(e=>e.id===a.entryId)||(g({...a,session:e,restorePosition:r,revision:-1}),i())};if(e.connection===`connected`)if(n.entries.some(e=>e.id===a.entryId))l({...n,history:{leafEntryId:n.history?.leafEntryId??null,beforeEntryId:n.history?.beforeEntryId??null,anchorEntryId:a.entryId,anchorOnBranch:!0}});else{let e=t=>{new rf().sessionMessageWindow(a,o.signal).then(l,()=>{!o.signal.aborted&&t===0&&(s=window.setTimeout(()=>e(1),500))})};e(0)}return()=>{o.abort(),window.clearTimeout(s);for(let e of[`wheel`,`touchstart`,`pointerdown`,`keydown`])document.removeEventListener(e,c,!0)}},[De,Oe,e.connection,e.sessionSwitching,e.historyNavigation,Ee,f]);let Ae=rj(e.snapshot,G),je=(0,_.useMemo)(()=>aj((G?.entries??[]).flatMap(e=>e.message?[e.message]:[])),[G?.entries]),Me=Ae?e.snapshot?.runtime.capabilities.subagents:void 0,Ne=(0,_.useMemo)(()=>oj(Me?.items??[],je,Ae?e.snapshot?.runtime.capabilities.workflows?.items:void 0,e.connection===`connected`),[Me?.items,je,Ae,e.snapshot?.runtime.capabilities.workflows?.items,e.connection]),Pe=e.snapshot?.selectedExecution,Fe=Pe?.sessionId===G?.id&&Pe?.sessionPath===G?.path?Pe:void 0,Ie=Ae&&(e.liveRunning||!!e.activeTurn||e.snapshot?.runtime.status===`running`)||Fe?.status===`running`,Le=qN(G,e.snapshot?.cursor,{active:oe&&de===`review`,running:Ie,initialSource:U?.reading.review?.scope.startsWith(`workspace:`)?U.reading.review.source:`unstaged`,initialBaseRef:U?.reading.review?.baseRef}),Re=!!(U&&G&&e.selectedPath===G.path&&U.sessionId===G.id&&U.sessionPath===G.path),ze=oe&&Re&&!e.sessionSwitching;(0,_.useEffect)(()=>{G?.id,G?.path,c.current=null},[G?.id,G?.path]),(0,_.useEffect)(()=>{!U||e.sessionSwitching||ie(e=>e.at(-1)===U?e:[...e.filter(e=>e!==U),U])},[U,e.sessionSwitching]);let Be=(t=`launcher`)=>{!G||e.sessionSwitching||(y&&l.current?.close({restoreFocus:!1}),ze||(c.current=document.activeElement instanceof HTMLElement?document.activeElement:null),H(null),me(null),ie(e=>{let n=e.find(e=>e.sessionId===G.id&&e.sessionPath===G.path),r={sessionId:G.id,sessionPath:G.path,tool:t,requestRevision:(n?.requestRevision??0)+1,open:!0,reading:n?.reading??{},reviewTurn:t===`review`?void 0:n?.reviewTurn};return[...e.filter(e=>e!==n),r].slice(-32)}))},Ve=()=>{E(!1),le(!1);let e=c.current;c.current=null,requestAnimationFrame(()=>{e?.isConnected&&e.checkVisibility()&&e.focus()})},He=!e.sessionSwitching&&!e.workspaceDraft&&rj(e.snapshot,G)?G:void 0;KR(He?.id,He?.path,async(e,t)=>{Be(`browser`);let n=Date.now()+5e3;for(;!u.current&&!t.aborted&&Date.now()setTimeout(e,40));return t.aborted?void 0:u.current?.(e)});let Ue=(0,_.useRef)(AI(new URLSearchParams(location.search).get(`settings`))),We=(0,_.useEffectEvent)(e=>{Se(e)});(0,_.useEffect)(()=>{if(!Ue.current||!e.snapshot||e.sessionSwitching)return;let t=Ue.current;Ue.current=void 0,We(t)},[e.snapshot,e.sessionSwitching]);let Ge=!!(he||ze||y);(0,_.useEffect)(()=>{(!Ge||D<=ZJ)&&E(!1)},[Ge,D]);let qe=Math.max(UJ,Math.min(WJ,D-XJ-(Ge&&!T?k.auxiliary:0))),Je=QJ(k.sidebar,UJ,qe),Ye=Math.max(qJ,Math.min(JJ,D-(e.sidebarCollapsed?56:Je)-XJ)),Xe=QJ(k.auxiliary,qJ,Ye),Ze={"--sidebar-width":`${Je}px`,"--auxiliary-width":`${Xe}px`},Qe=()=>{y?l.current?.close():ze?Ve():he&&me(null)},$e=!e.snapshot,et=e.sessionSwitching?e.snapshot?.sessions.find(t=>t.path===e.selectedPath)?.cwd:e.workspaceDraft?e.selectedWorkspace:G?.cwd??e.selectedWorkspace,rt=e.snapshot?.workspaces.find(e=>e.path===et),at=e.snapshot?.sessions.find(e=>e.path===G?.path&&e.id===G?.id),ot=e.sessionSwitching?e.snapshot?.sessions.find(t=>t.path===e.selectedPath):void 0,st=e.sessionSwitching?ot?ZA(ot,t(`untitledSession`)):t(`switchingSession`):G?ZA(at??{},t(`untitledSession`)):e.selectedWorkspace?t(`newSession`):`OpenPI`,ct=!!G?.rerun||G?.entries.some(e=>e.type===`message`&&e.message||e.type===`compaction`)||!!G?.history?.beforeEntryId||e.liveMessages.length>0,lt=!$e&&!e.sessionSwitching&&(!G||!ct&&!(e.snapshot?.selectedExecution?.sessionId===G.id&&e.snapshot.selectedExecution?.sessionPath===G.path&&e.snapshot.selectedExecution.compaction)),ut=(0,_.useCallback)((e,t)=>t?n.sendPrompt(``,[],void 0,{streamingBehavior:`followUp`,retryEntryId:t}):n.sendPrompt(e),[n]);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{inert:xe?!0:void 0,"aria-hidden":xe?!0:void 0,className:`app-shell ${e.sidebarCollapsed?`sidebar-collapsed`:``} ${e.mobileSidebarOpen?`sidebar-open`:``} ${he?`with-subagent-panel`:``} ${ze?`with-workbar-panel`:``} ${y?`with-artifact-panel`:``} ${T?`center-collapsed`:``} ${C?`is-resizing`:``} ${$e?`shell-loading`:``}`,style:Ze,children:(0,K.jsxs)(Bk,{ref:l,sessionId:G?.id,sessionPath:G?.path,disabled:!!(e.workspaceDraft||e.sessionSwitching||he||xe),onOpen:()=>{b(!0),me(null),le(!1),H(null)},onClose:()=>{b(!1)},children:[(0,K.jsx)(dP,{sessionViewVisible:z===`chat`&&!T&&!xe&&!e.sessionSwitching&&!e.workspaceDraft,connected:e.connection===`connected`,snapshot:e.snapshot,selectedPath:e.workspaceDraft?null:e.selectedPath,selectedWorkspace:e.selectedWorkspace,collapsed:e.collapsed,query:e.query,searchOpen:e.searchOpen,mobileOpen:ee,settingsDisabled:!!(e.sessionSwitching||e.modelSelectionPending||!e.snapshot),returnFocusRef:r,onOpenSettings:()=>void Se(`general`),actions:n}),e.sidebarCollapsed&&(0,K.jsx)(`button`,{className:`sidebar-expand`,type:`button`,"aria-label":t(`expandSidebar`),title:t(`expandSidebar`),onClick:()=>n.toggleSidebar(!1),children:(0,K.jsx)(nt,{})}),(0,K.jsxs)(`main`,{inert:ee,className:`conversation-shell ${G?`has-view`:``} ${lt&&(!G||z===`chat`)?`landing`:``}`,children:[(0,K.jsxs)(`header`,{className:`task-header`,children:[(0,K.jsx)(`button`,{className:`task-header-menu sidebar-shell-toggle`,ref:r,type:`button`,"aria-label":t(L?`openSidebar`:e.sidebarCollapsed?`expandSidebar`:`collapseSidebar`),"aria-controls":`session-sidebar`,"aria-expanded":L?ee:!e.sidebarCollapsed,onClick:()=>n.toggleSidebar(L),children:L?(0,K.jsx)(Ke,{}):(0,K.jsx)(tt,{})}),(0,K.jsxs)(`div`,{className:`task-identity`,children:[et&&(0,K.jsxs)(`span`,{className:`task-workspace`,title:et,children:[rt?.name||QA(et),(0,K.jsxs)(`span`,{className:`sr-only`,children:[` `,et]})]}),(0,K.jsx)(`h1`,{title:st,children:st})]}),(0,K.jsx)(qR,{usage:G&&!e.sessionSwitching?e.snapshot?.usage:void 0,workspace:rt?.name||G&&QA(G.cwd),sessionId:G?.id},G?`usage:${G.id}:${G.path}`:`usage:no-session`),G&&!e.sessionSwitching&&(0,K.jsx)(LI,{sessionId:G.id,workspace:rt?.name||QA(G.cwd),agents:Ne,omitted:(Me?.omitted??0)+(Ae?(e.snapshot?.runtime.capabilities.workflows?.items??[]).reduce((e,t)=>e+(t.children?.omitted??0),0):0),review:Le.result,reviewLoading:Le.loading,reviewError:Le.error,sessionPath:G.path,revision:G.history?.leafEntryId??void 0,onAddSources:Ae?()=>S(e=>({sessionId:G.id,path:G.path,revision:(e?.revision??0)+1})):void 0,onSubagents:()=>W(),onReview:()=>Be(`review`)},`overview:${G.id}:${G.path}`),(0,K.jsx)(`button`,{type:`button`,className:`task-tools-trigger`,"aria-label":t(`openTools`),title:t(`openTools`),disabled:!G||e.sessionSwitching,onClick:e=>{y&&l.current?.close({restoreFocus:!1}),c.current=e.currentTarget,Re&&!ze?le(!0):Be(`launcher`)},children:(0,K.jsx)(it,{"aria-hidden":`true`})}),(0,K.jsx)(`span`,{className:`connection-state ${e.connection}`,children:t(e.connection)})]}),G&&!e.sessionSwitching&&(0,K.jsx)(`div`,{className:`conversation-view-row`,children:(0,K.jsxs)(`fieldset`,{className:`conversation-view-switch`,"aria-label":t(`conversationView`),children:[(0,K.jsx)(`button`,{type:`button`,"aria-pressed":z===`chat`,onClick:()=>B(`chat`),children:t(`chatView`)}),(0,K.jsx)(`button`,{type:`button`,"aria-pressed":z===`trajectory`,onClick:()=>B(`trajectory`),children:t(`trajectory`)})]})}),$e?(0,K.jsxs)(`section`,{className:`shell-state`,role:`status`,"aria-live":`polite`,children:[(0,K.jsx)(hr,{compact:!0}),(0,K.jsx)(`p`,{children:t(e.connection===`unavailable`?`unavailable`:`connecting`)}),e.connection===`unavailable`&&(0,K.jsxs)(`button`,{type:`button`,onClick:()=>void n.refreshSnapshot({resetCursor:!0}),children:[(0,K.jsx)(dt,{"aria-hidden":`true`}),` `,t(`retryAdmissionCheck`)]})]}):e.sessionSwitching?(0,K.jsx)(`div`,{className:`conversation switching`,role:`status`,children:(0,K.jsxs)(`div`,{className:`conversation-running`,children:[(0,K.jsx)(`span`,{className:`conversation-running-dot`}),(0,K.jsx)(`span`,{children:t(`switchingSession`)})]})}):z===`trajectory`&&G&&e.snapshot?(0,K.jsx)(mL,{snapshot:e.snapshot,running:Ie},G.path):lt?(0,K.jsx)(`section`,{className:`conversation landing-conversation`,"aria-label":`Conversation`,children:(0,K.jsxs)(`div`,{className:`landing-welcome`,children:[(0,K.jsx)(hr,{animated:!0}),(0,K.jsx)(`p`,{className:`landing-tagline`,children:t(`landingTagline`)})]})}):e.snapshot?(0,K.jsx)(HR,{resultExposureEnabled:!T&&!xe&&!e.sessionSwitching&&!e.workspaceDraft&&z===`chat`,readingCache:f,readingRestorePending:ke,snapshot:e.snapshot,liveMessages:e.liveMessages,liveRunning:e.liveRunning,liveActiveTurn:e.activeTurn,livePhase:e.livePhase,activityObserved:e.connection===`connected`,liveRetry:e.liveRetry,thinkingStarts:e.thinkingStarts,thinkingDurations:e.thinkingDurations,scrollToBottom:e.scrollToBottom,onResend:ut,onEdit:n.editMessage,onRegenerate:n.regenerateMessage,onOpenOriginal:n.navigateToMessage,onFork:n.forkMessage,forkPending:e.sessionForkPending,forkAvailable:Ae&&!Ie&&e.snapshot.runtime.status===`idle`&&!e.promptAdmissionPending&&!e.promptAdmissionRecovery&&!e.activeTurn&&!e.modelSelectionPending&&!e.sessionSwitching&&!G?.path.startsWith(`current:`)&&!(Fe?.pendingFollowUps||Fe?.pendingSteering||Fe?.compaction?.state===`running`),onInspectSubagent:W,onReviewTurn:(e,t)=>{Be(`review`),c.current=document.activeElement instanceof HTMLElement?document.activeElement:null,ue({promptEntryId:e,filePath:t,revision:(se?.revision??0)+1})},onHistoryAnchorChange:n.setHistoryAnchor,historyNavigation:e.historyNavigation??(h?.sessionId===G?.id&&h?.sessionPath===G?.path?h:null),onNavigateToMessage:n.navigateToMessage,onRefreshHistory:n.refreshSnapshot,onPromptProjection:n.rememberPromptProjection},`transcript:${JSON.stringify([G?.id,G?.path])}`):null,!xe&&G&&e.snapshot&&!e.sessionSwitching&&rj(e.snapshot,G)&&(0,K.jsx)(KN,{sessionId:G.id,sessionPath:G.path,workingCache:v,revision:e.snapshot.cursor,connected:e.connection===`connected`},JSON.stringify([G.id,G.path])),e.snapshot&&(0,K.jsxs)(`div`,{className:`workbar-chat-context`,hidden:!ze,children:[(0,K.jsx)(`span`,{className:`workbar-chat-title`,title:st,children:st}),(0,K.jsx)(`span`,{className:`workbar-chat-status`,role:`status`,children:t(Ie?`turnState_running`:e.connection)}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{Ve(),requestAnimationFrame(()=>document.querySelector(`.composer textarea`)?.focus({preventScroll:!0}))},children:t(`workbarContinueInChat`)})]}),e.snapshot&&(0,K.jsx)(RN,{addSourcesRequest:x,planSelectionPending:e.planSelectionPending,workspaceDraft:e.workspaceDraft,draftModel:e.draftModel,createdSession:e.createdSession,modelSelectionPending:e.modelSelectionPending,modelSearch:e.modelSearch,thinkingPendingLevel:e.thinkingPendingLevel,onInspect:ve,onOpenProviders:()=>void Se(`credentials`),onCommandAction:e=>{let t=VJ.getState();return t.sessionSwitching||t.workspaceDraft||!G||t.snapshot?.selectedSession?.path!==G.path||t.snapshot.selectedSession.id!==G.id?!1:(e===`terminal`||e===`review`||e===`side-conversation`?Be(e):e===`subagents`?W():ve(),!0)},onInspectSubagent:W,activeTurn:e.activeTurn,activityObserved:e.connection===`connected`,turnCancellationPending:e.turnCancellationPending,turnTerminalStatus:e.turnTerminalStatus,pendingFollowUpsReceipt:e.pendingFollowUpsReceipt,pendingSteeringReceipt:e.pendingSteeringReceipt,commandDiscovery:e.commandDiscovery,snapshot:e.snapshot,selectedPath:e.selectedPath,selectedWorkspace:G?.cwd??e.selectedWorkspace,sessionSwitching:e.sessionSwitching||e.sessionForkPending,promptAdmissionPending:e.promptAdmissionPending,promptAdmissionRecovery:e.promptAdmissionRecovery,promptAdmissionResolution:e.promptAdmissionResolution,restoredPromptDraft:e.restoredPromptDraft,liveRunning:e.liveRunning,landing:lt,actions:n}),e.sessionForkPending&&(0,K.jsxs)(`div`,{className:`session-fork-progress`,role:`status`,children:[(0,K.jsx)(`span`,{className:`session-fork-progress-spinner`,"aria-hidden":`true`}),t(e.sessionForkCancellation===`too-late`?`sidebarForkFinishing`:e.sessionForkCancellation?`sidebarForkCancelling`:e.sessionForkEnvironment===`worktree`?`sidebarForkWorktreePending`:`forkSessionPending`),e.sessionForkEnvironment&&(0,K.jsx)(`button`,{type:`button`,disabled:e.sessionForkCancellation!==null,onClick:()=>void n.cancelSessionFork(),children:t(`cancel`)})]}),(0,K.jsx)(YN,{notices:e.archiveNotices,actions:n}),e.notice&&(0,K.jsxs)(`div`,{className:typeof e.notice==`string`?`notice`:`notice notice-success`,role:typeof e.notice==`string`?`alert`:`status`,children:[(0,K.jsx)(`span`,{children:typeof e.notice==`string`?e.notice:e.notice.message}),(0,K.jsx)(`button`,{type:`button`,"aria-label":t(`close`),onClick:n.clearNotice,children:(0,K.jsx)(Lt,{})})]})]}),ye&&(0,K.jsx)(zN,{target:V,onClose:be,onOpenProviders:()=>void Se(`credentials`)},`${V.sessionId}:${V.sessionPath}:${V.terminalId??`status`}`),he&&(0,K.jsx)(YI,{sessionId:pe.sessionId,initialId:pe.id,initialKind:pe.kind,observed:e.connection===`connected`,activity:rj(e.snapshot,{id:pe.sessionId,path:pe.sessionPath})?e.snapshot?.runtime.capabilities.subagents:void 0,records:je,workflows:Ae?e.snapshot?.runtime.capabilities.workflows:void 0,liveAvailable:rj(e.snapshot,{id:pe.sessionId,path:pe.sessionPath}),onClose:()=>me(null)},`${pe.sessionId}:${pe.navigation}`),ze&&G&&U&&(0,K.jsx)(Jq,{visible:ze,requestedTool:U.tool,requestRevision:U.requestRevision,sessionId:G.id,sessionPath:G.path,onBrowserReady:d,canControl:!e.sessionSwitching&&rj(e.snapshot,G),onActivateSession:()=>void n.selectSession(G.path),cwd:G.cwd,snapshot:e.snapshot??void 0,capabilities:rj(e.snapshot,G)?e.snapshot?.runtime.capabilities??{}:{},readingState:U.reading,onActiveToolChange:fe,review:Le,reviewTurn:se??void 0,onWorkspaceReview:()=>ue(null),onReferenceLine:e=>{let t=VJ.getState(),n=t.snapshot?.selectedSession;t.workspaceDraft||t.sessionSwitching||t.selectedPath!==G.path||n?.id!==G.id||n.path!==G.path||!rj(t.snapshot,n)||(B(`chat`),S(t=>({sessionId:G.id,path:G.path,revision:(t?.revision??0)+1,feedback:e})))},conversationCollapsed:T,onRestoreConversation:()=>E(!1),onExpandReview:()=>E(!0),onClose:Ve},`${G.id}:${G.path}`),(0,K.jsxs)(`section`,{"aria-label":t(`resizePanes`),style:{display:`contents`},children:[!e.sidebarCollapsed&&!L&&(!Ge||D>ZJ)&&(0,K.jsx)(_r,{side:`left`,value:Je,min:UJ,max:qe,defaultValue:HJ,collapseThreshold:GJ,onCollapse:()=>n.toggleSidebar(!1),onChange:e=>I(`sidebar`,e),onDraggingChange:w}),Ge&&!T&&D>ZJ&&(0,K.jsx)(_r,{side:`right`,value:Xe,min:qJ,max:Ye,defaultValue:KJ,collapseThreshold:YJ,onCollapse:Qe,onExpandPastMax:ze?()=>E(!0):void 0,onChange:e=>I(`auxiliary`,e),onDraggingChange:w})]}),(0,K.jsx)(`button`,{className:`sidebar-scrim`,type:`button`,tabIndex:-1,"aria-hidden":`true`,"aria-label":t(`close`),onClick:n.closeMobileSidebar})]})}),xe&&(0,K.jsx)(jI,{sessionId:te.sessionId,cwd:te.cwd,entry:te.entry,models:e.snapshot?.models??[],currentModel:ge,thinkingLevel:e.thinkingPendingLevel??e.snapshot?.thinking?.level??t(`unknownState`),theme:e.snapshot?.preferences.theme??`system`,preferences:e.snapshot?.preferences,workspaces:e.snapshot?.workspaces??[],onRestoreSession:e=>n.unarchiveSession(e),plan:e.snapshot?.runtime.plan,planSelectionPending:e.planSelectionPending,onExitPlan:()=>n.selectPlanMode(!1),setupOutcome:e.snapshot?.runtime.setup,capabilities:e.snapshot?.runtime.capabilities,setupBusy:e.liveRunning||e.promptAdmissionPending||!!e.activeTurn||e.modelSelectionPending||e.thinkingPendingLevel!==null||e.sessionSwitching,setupBlockedReason:e.promptAdmissionRecovery?t(`setupResolveAdmission`):void 0,modelSelectionPending:e.modelSelectionPending,sessionPath:te.sessionPath,onSelectModel:e=>n.selectModel(e),onConfigureOpenPi:Te,interaction:e.snapshot&&!e.sessionSwitching&&te.sessionId===e.snapshot.currentSessionId?(0,K.jsxs)(`div`,{className:`settings-interaction`,children:[(0,K.jsx)(KN,{sessionId:te.sessionId,sessionPath:te.sessionPath,workingCache:v,revision:e.snapshot.cursor,connected:e.connection===`connected`},JSON.stringify([te.sessionId,te.sessionPath])),(e.activeTurn||e.liveRunning)&&(0,K.jsx)(`button`,{type:`button`,disabled:e.turnCancellationPending,onClick:()=>void n.cancelActiveTurn(),children:t(`stopTurn`)})]}):void 0,onPreferencesChanged:()=>n.refreshSnapshot(),onOpenRuntimeStatus:we,onClose:Ce},`${te.sessionId}:${te.sessionPath}`)]})}var eY={size:`1em`,"aria-hidden":!0},tY={name:`neutral`,__built:!0,tokens:{"--font-size-4xs":`0.375rem`,"--font-size-3xs":`0.4375rem`,"--font-size-2xs":`0.5rem`,"--font-size-xs":`0.625rem`,"--font-size-sm":`0.75rem`,"--font-size-base":`0.875rem`,"--font-size-lg":`1.0625rem`,"--font-size-xl":`1.25rem`,"--font-size-2xl":`1.5rem`,"--font-size-3xl":`1.8125rem`,"--font-size-4xl":`2.1875rem`,"--font-size-5xl":`2.625rem`,"--text-heading-1-size":`var(--font-size-2xl)`,"--text-heading-1-weight":`var(--font-weight-semibold)`,"--text-heading-1-leading":`1.3333`,"--text-heading-2-size":`var(--font-size-xl)`,"--text-heading-2-weight":`var(--font-weight-semibold)`,"--text-heading-2-leading":`1.4`,"--text-heading-3-size":`var(--font-size-lg)`,"--text-heading-3-weight":`var(--font-weight-bold)`,"--text-heading-3-leading":`1.4118`,"--text-heading-4-size":`var(--font-size-base)`,"--text-heading-4-weight":`var(--font-weight-bold)`,"--text-heading-4-leading":`1.4286`,"--text-heading-5-size":`var(--font-size-sm)`,"--text-heading-5-weight":`var(--font-weight-semibold)`,"--text-heading-5-leading":`1.6667`,"--text-heading-6-size":`var(--font-size-xs)`,"--text-heading-6-weight":`var(--font-weight-semibold)`,"--text-heading-6-leading":`1.6`,"--text-body-size":`var(--font-size-base)`,"--text-body-weight":`var(--font-weight-normal)`,"--text-body-leading":`1.4286`,"--text-large-size":`var(--font-size-lg)`,"--text-large-weight":`var(--font-weight-semibold)`,"--text-large-leading":`1.4118`,"--text-label-size":`var(--font-size-base)`,"--text-label-weight":`var(--font-weight-medium)`,"--text-label-leading":`1.4286`,"--text-code-size":`var(--font-size-base)`,"--text-code-weight":`var(--font-weight-normal)`,"--text-code-leading":`1.4286`,"--text-supporting-size":`var(--font-size-sm)`,"--text-supporting-weight":`var(--font-weight-normal)`,"--text-supporting-leading":`1.6667`,"--text-display-1-size":`var(--font-size-5xl)`,"--text-display-1-weight":`var(--font-weight-normal)`,"--text-display-1-leading":`1.2381`,"--text-display-2-size":`var(--font-size-4xl)`,"--text-display-2-weight":`var(--font-weight-normal)`,"--text-display-2-leading":`1.2571`,"--text-display-3-size":`var(--font-size-3xl)`,"--text-display-3-weight":`var(--font-weight-normal)`,"--text-display-3-leading":`1.3793`,"--duration-fast-min":`95ms`,"--duration-fast":`125ms`,"--duration-fast-max":`165ms`,"--duration-medium-min":`225ms`,"--duration-medium":`300ms`,"--duration-medium-max":`400ms`,"--duration-slow-min":`525ms`,"--duration-slow":`700ms`,"--duration-slow-max":`935ms`,"--font-family-body":`Figtree, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif`,"--font-family-heading":`Figtree, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif`,"--font-family-code":`ui-monospace, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace`,"--color-syntax-keyword":`light-dark(#700084, #efa8ff)`,"--color-syntax-string":`light-dark(#005600, #a6d2a2)`,"--color-syntax-comment":`light-dark(#737373, #a3a3a3)`,"--color-syntax-number":`light-dark(#6e3500, #ffb37f)`,"--color-syntax-function":`light-dark(#00458c, #a0caff)`,"--color-syntax-type":`light-dark(#700084, #efa8ff)`,"--color-syntax-variable":`light-dark(#171717, #e5e5e5)`,"--color-syntax-operator":`light-dark(#737373, #a3a3a3)`,"--color-syntax-constant":`light-dark(#6e3500, #ffb37f)`,"--color-syntax-tag":`light-dark(#89001a, #ffaeaa)`,"--color-syntax-attribute":`light-dark(#584400, #eec12f)`,"--color-syntax-property":`light-dark(#005348, #83dac9)`,"--color-syntax-punctuation":`light-dark(#6e6e6e, #a0a0a0)`,"--color-syntax-background":`light-dark(#fafafa, #0a0a0a)`,"--color-background-surface":`light-dark(#ffffff, #262626)`,"--color-background-body":`light-dark(#f1f1f1, #1b1b1b)`,"--color-background-card":`light-dark(#ffffff, #1b1b1b)`,"--color-background-popover":`light-dark(#ffffff, #1b1b1b)`,"--color-background-muted":`light-dark(#f1f1f1, #1b1b1b)`,"--color-accent":`light-dark(#262626, #ebebeb)`,"--color-accent-muted":`light-dark(#f1f1f1, #262626)`,"--color-neutral":`light-dark(#0000000F, #FFFFFF1A)`,"--color-overlay":`light-dark(#00000080, #000000CC)`,"--color-overlay-hover":`light-dark(#0000000D, #FFFFFF0D)`,"--color-overlay-pressed":`light-dark(#0000001A, #FFFFFF1A)`,"--color-text-primary":`light-dark(#171717, #fafafa)`,"--color-text-secondary":`light-dark(#525252, #a3a3a3)`,"--color-text-disabled":`light-dark(#a3a3a3, #525252)`,"--color-text-accent":`light-dark(#262626, #ebebeb)`,"--color-on-dark":`#ffffff`,"--color-on-light":`#171717`,"--color-on-accent":`light-dark(#ffffff, #171717)`,"--color-on-success":`light-dark(#ffffff, #171717)`,"--color-on-error":`light-dark(#ffffff, #171717)`,"--color-on-warning":`#171717`,"--color-icon-accent":`light-dark(#262626, #ebebeb)`,"--color-icon-primary":`light-dark(#171717, #fafafa)`,"--color-icon-secondary":`light-dark(#737373, #a3a3a3)`,"--color-icon-disabled":`light-dark(#a3a3a3, #525252)`,"--color-success":`light-dark(#007004, #9fe59b)`,"--color-error":`light-dark(#a50c25, #ffc6c1)`,"--color-warning":`light-dark(#745b00, #fdcf4f)`,"--color-success-muted":`light-dark(#c5e5c0, #84c9803D)`,"--color-error-muted":`light-dark(#facecb, #ff9e973D)`,"--color-warning-muted":`light-dark(#f8da9d, #deb4333D)`,"--color-border":`light-dark(#00000014, #FFFFFF1A)`,"--color-border-emphasized":`light-dark(#d4d4d4, #525252)`,"--color-skeleton":`light-dark(#ebebeb, #525252)`,"--color-shadow":`light-dark(#0000001A, #0000004D)`,"--color-tint-hover":`light-dark(black, white)`,"--color-background-red":`light-dark(#facecb, #ff9e973D)`,"--color-border-red":`light-dark(#e6bab8, #ff6f6c)`,"--color-icon-red":`light-dark(#89001a, #ff9e97)`,"--color-text-red":`light-dark(#89001a, #ffc6c1)`,"--color-background-orange":`light-dark(#fad0b5, #ffa2583D)`,"--color-border-orange":`light-dark(#e6bda2, #e2883e)`,"--color-icon-orange":`light-dark(#6e3500, #ffa258)`,"--color-text-orange":`light-dark(#6e3500, #ffc9a2)`,"--color-background-yellow":`light-dark(#f8da9d, #deb4333D)`,"--color-border-yellow":`light-dark(#e4c279, #c0990e)`,"--color-icon-yellow":`light-dark(#584400, #deb433)`,"--color-text-yellow":`light-dark(#584400, #fdcf4f)`,"--color-background-green":`light-dark(#c5e5c0, #84c9803D)`,"--color-border-green":`light-dark(#b2d1ac, #69ad67)`,"--color-icon-green":`light-dark(#0c5700, #84c980)`,"--color-text-green":`light-dark(#0c5700, #9fe59b)`,"--color-background-teal":`light-dark(#a5e3d6, #7ec6b83D)`,"--color-border-teal":`light-dark(#94d6c8, #63ab9d)`,"--color-icon-teal":`light-dark(#005348, #7ec6b8)`,"--color-text-teal":`light-dark(#005348, #99e2d3)`,"--color-background-cyan":`light-dark(#a3e0ef, #83c2d43D)`,"--color-border-cyan":`light-dark(#91d3e3, #67a7b8)`,"--color-icon-cyan":`light-dark(#00505f, #83c2d4)`,"--color-text-cyan":`light-dark(#00505f, #9edef0)`,"--color-background-blue":`light-dark(#c4ddfb, #9eb7ff3D)`,"--color-border-blue":`light-dark(#b1c9e7, #6d9cfe)`,"--color-icon-blue":`light-dark(#00458c, #9eb7ff)`,"--color-text-blue":`light-dark(#00458c, #c7d3ff)`,"--color-background-purple":`light-dark(#eccef3, #f297ff3D)`,"--color-border-purple":`light-dark(#d8bbdf, #dd74f0)`,"--color-icon-purple":`light-dark(#700084, #f297ff)`,"--color-text-purple":`light-dark(#700084, #fac1ff)`,"--color-background-pink":`light-dark(#fccadc, #ff99c33D)`,"--color-border-pink":`light-dark(#e7b7c8, #f273aa)`,"--color-icon-pink":`light-dark(#83004b, #ff99c3)`,"--color-text-pink":`light-dark(#83004b, #ffc3da)`,"--color-background-gray":`light-dark(#e5e5e5, var(--color-neutral))`,"--color-border-gray":`light-dark(#d4d4d4, #262626)`,"--color-icon-gray":`light-dark(#525252, #a3a3a3)`,"--color-text-gray":`light-dark(#262626, #e5e5e5)`,"--radius-none":`0px`,"--radius-inner":`0.375rem`,"--radius-element":`0.625rem`,"--radius-container":`0.75rem`,"--radius-page":`1.75rem`,"--radius-full":`9999px`,"--shadow-low":`0 2px 4px light-dark(oklch(0 0 0 / 5%), oklch(0 0 0 / 25%)), 0 4px 8px light-dark(oklch(0 0 0 / 10%), oklch(0 0 0 / 40%)), inset 0 0 0 1px light-dark(transparent, oklch(1 0 0 / 8%))`,"--shadow-med":`0 2px 4px light-dark(oklch(0 0 0 / 5%), oklch(0 0 0 / 35%)), 0 4px 12px light-dark(oklch(0 0 0 / 10%), oklch(0 0 0 / 50%)), inset 0 0 0 1px light-dark(transparent, oklch(1 0 0 / 12%))`,"--shadow-high":`0 4px 6px light-dark(oklch(0 0 0 / 10%), oklch(0 0 0 / 50%)), 0 12px 24px light-dark(oklch(0 0 0 / 15%), oklch(0 0 0 / 70%)), inset 0 0 0 1px light-dark(transparent, oklch(1 0 0 / 15%))`,"--shadow-inset-hover":`inset 0px 0px 0px 2px #0074e24D`,"--shadow-inset-selected":`inset 0px 0px 0px 2px #0074e280`,"--shadow-inset-success":`inset 0px 0px 0px 2px #1981004D`,"--shadow-inset-warning":`inset 0px 0px 0px 2px #ffce2f4D`,"--shadow-inset-error":`inset 0px 0px 0px 2px #e33f4a4D`},components:{heading:{"level:1":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-heading-1-size)`,fontWeight:`var(--text-heading-1-weight)`,lineHeight:`var(--text-heading-1-leading)`},"level:2":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-heading-2-size)`,fontWeight:`var(--text-heading-2-weight)`,lineHeight:`var(--text-heading-2-leading)`},"level:3":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-heading-3-size)`,fontWeight:`var(--text-heading-3-weight)`,lineHeight:`var(--text-heading-3-leading)`},"level:4":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-heading-4-size)`,fontWeight:`var(--text-heading-4-weight)`,lineHeight:`var(--text-heading-4-leading)`},"level:5":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-heading-5-size)`,fontWeight:`var(--text-heading-5-weight)`,lineHeight:`var(--text-heading-5-leading)`},"level:6":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-heading-6-size)`,fontWeight:`var(--text-heading-6-weight)`,lineHeight:`var(--text-heading-6-leading)`},"type:display-1":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-display-1-size)`,lineHeight:`var(--text-display-1-leading)`},"type:display-2":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-display-2-size)`,lineHeight:`var(--text-display-2-leading)`},"type:display-3":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-display-3-size)`,lineHeight:`var(--text-display-3-leading)`}},text:{"type:body":{fontFamily:`var(--font-family-body)`,fontSize:`var(--text-body-size)`,lineHeight:`var(--text-body-leading)`},"type:large":{fontFamily:`var(--font-family-body)`,fontSize:`var(--text-large-size)`,lineHeight:`var(--text-large-leading)`},"type:label":{fontFamily:`var(--font-family-body)`,fontSize:`var(--text-label-size)`,lineHeight:`var(--text-label-leading)`},"type:code":{fontFamily:`var(--font-family-code)`,fontSize:`var(--text-code-size)`,lineHeight:`var(--text-code-leading)`},"type:supporting":{fontFamily:`var(--font-family-body)`,fontSize:`var(--text-supporting-size)`,lineHeight:`var(--text-supporting-leading)`},"type:display-1":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-display-1-size)`,lineHeight:`var(--text-display-1-leading)`},"type:display-2":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-display-2-size)`,lineHeight:`var(--text-display-2-leading)`},"type:display-3":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-display-3-size)`,lineHeight:`var(--text-display-3-leading)`}},button:{"variant:destructive":{backgroundColor:`var(--color-error-muted)`,color:`var(--color-error)`}},badge:{"variant:info":{backgroundColor:`light-dark(#0074e2, #6d9cfe)`,color:`light-dark(#ffffff, #171717)`},"variant:neutral":{backgroundColor:`var(--color-background-gray)`,color:`var(--color-text-gray)`},"variant:success":{backgroundColor:`light-dark(#198100, #64af4c)`,color:`light-dark(#ffffff, #171717)`},"variant:warning":{backgroundColor:`#ffce2f`,color:`#171717`},"variant:error":{backgroundColor:`light-dark(#c9303a, #ff705d)`,color:`light-dark(#ffffff, #171717)`},"variant:red":{backgroundColor:`var(--color-background-red)`,color:`var(--color-text-red)`},"variant:orange":{backgroundColor:`var(--color-background-orange)`,color:`var(--color-text-orange)`},"variant:yellow":{backgroundColor:`var(--color-background-yellow)`,color:`var(--color-text-yellow)`},"variant:green":{backgroundColor:`var(--color-background-green)`,color:`var(--color-text-green)`},"variant:teal":{backgroundColor:`var(--color-background-teal)`,color:`var(--color-text-teal)`},"variant:cyan":{backgroundColor:`var(--color-background-cyan)`,color:`var(--color-text-cyan)`},"variant:blue":{backgroundColor:`var(--color-background-blue)`,color:`var(--color-text-blue)`},"variant:purple":{backgroundColor:`var(--color-background-purple)`,color:`var(--color-text-purple)`},"variant:pink":{backgroundColor:`var(--color-background-pink)`,color:`var(--color-text-pink)`},"variant:gray":{backgroundColor:`var(--color-background-gray)`,color:`var(--color-text-gray)`}},statusdot:{"variant:success":{backgroundColor:`light-dark(#198100, #64af4c)`},"variant:warning":{backgroundColor:`#ffce2f`},"variant:error":{backgroundColor:`light-dark(#c9303a, #ff705d)`},"variant:accent":{backgroundColor:`light-dark(#0074e2, #6d9cfe)`}},banner:{"status:info":{"--color-accent-muted":`var(--color-background-blue)`,"--color-text-primary":`var(--color-text-blue)`,"--color-text-secondary":`var(--color-text-blue)`,"--color-accent":`var(--color-text-blue)`},"status:success":{"--color-text-primary":`var(--color-text-green)`,"--color-text-secondary":`var(--color-text-green)`,"--color-success":`var(--color-text-green)`},"status:warning":{"--color-text-primary":`var(--color-text-yellow)`,"--color-text-secondary":`var(--color-text-yellow)`,"--color-warning":`var(--color-text-yellow)`},"status:error":{"--color-text-primary":`var(--color-text-red)`,"--color-text-secondary":`var(--color-text-red)`,"--color-error":`var(--color-text-red)`}},switch:{base:{"--color-background-gray":`var(--color-border-emphasized)`}},progressbar:{base:{"--color-background-muted":`var(--color-border-emphasized)`},"variant:accent":{"--color-accent":`#0074e2`},"variant:success":{"--color-success":`#198100`},"variant:warning":{"--color-warning":`#ffce2f`},"variant:error":{"--color-error":`#c9303a`}},card:{base:{padding:`var(--spacing-3)`}},section:{base:{padding:`var(--spacing-3)`}}},__onDark:{tokens:{"color-scheme":`dark`,"--color-text-primary":`var(--color-on-dark)`,"--color-icon-primary":`var(--color-on-dark)`,"--color-accent":`var(--color-on-dark)`}},__onLight:{tokens:{"color-scheme":`light`,"--color-text-primary":`var(--color-on-light)`,"--color-icon-primary":`var(--color-on-light)`,"--color-accent":`var(--color-on-light)`}},icons:{close:(0,K.jsx)(Lt,{...eY}),chevronDown:(0,K.jsx)(L,{...eY}),chevronLeft:(0,K.jsx)(R,{...eY}),chevronRight:(0,K.jsx)(ee,{...eY}),chevronsLeft:(0,K.jsx)(z,{...eY}),chevronsRight:(0,K.jsx)(B,{...eY}),check:(0,K.jsx)(I,{...eY}),success:(0,K.jsx)(H,{...eY}),error:(0,K.jsx)(ie,{...eY}),warning:(0,K.jsx)(At,{...eY}),info:(0,K.jsx)(Pe,{...eY}),calendar:(0,K.jsx)(P,{...eY}),clock:(0,K.jsx)(se,{...eY}),externalLink:(0,K.jsx)(he,{...eY}),menu:(0,K.jsx)(Ke,{...eY}),moreHorizontal:(0,K.jsx)(W,{...eY}),search:(0,K.jsx)(ht,{...eY}),arrowUp:(0,K.jsx)(k,{...eY}),arrowDown:(0,K.jsx)(w,{...eY}),arrowsUpDown:(0,K.jsx)(D,{...eY}),funnel:(0,K.jsx)(Oe,{...eY}),eyeSlash:(0,K.jsx)(ge,{...eY}),viewColumns:(0,K.jsx)(le,{...eY}),copy:(0,K.jsx)(ue,{...eY}),checkDouble:(0,K.jsx)(F,{...eY}),wrench:(0,K.jsx)(It,{...eY}),stop:(0,K.jsx)(Et,{...eY}),microphone:(0,K.jsx)(Ze,{...eY})}};function nY({children:e}){let t=pr(VJ,e=>e.snapshot?.preferences),n=t?.theme??`system`,r=t?.appearance??yI,i=xI(n,r),a=t?.chatWidth??820,o=t?.chatFontSize??14,[s,c]=(0,_.useState)(()=>window.matchMedia?.(`(prefers-color-scheme: dark)`).matches??!1);(0,_.useEffect)(()=>{let e=window.matchMedia?.(`(prefers-color-scheme: dark)`);if(!e)return;let t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let l=n===`system`?s?`dark`:`light`:n,u=l===`dark`||l===`pine`?`dark`:`light`;return(0,_.useEffect)(()=>{let e=document.documentElement;e.dataset.theme=l,e.dataset.palette=i,e.style.setProperty(`--conversation-content-width`,`${a}px`),e.style.setProperty(`--conversation-font-size`,`${o}px`);let t={};if(r.background&&(t[`--page`]=r.background),r.foreground&&(t[`--text`]=r.foreground),r.background||r.foreground)for(let[e,n]of Object.entries({sidebar:3,"sidebar-hover":7,"sidebar-active":10,border:12,"border-strong":22,muted:65,subtle:52,"settings-secondary-text":75}))t[`--${e}`]=`color-mix(in srgb, var(--text) ${n}%, var(--page))`;r.accent&&(t[`--accent`]=r.accent,t[`--focus`]=r.accent),e.style.setProperty(`--openpi-interface-font`,{codex:`var(--openpi-default-font)`,system:`var(--openpi-default-font)`,sans:`Arial, Helvetica, sans-serif`,serif:`Georgia, 'Times New Roman', serif`,mono:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`}[r.font]);for(let n of[`page`,`text`,`sidebar`,`sidebar-hover`,`sidebar-active`,`border`,`border-strong`,`muted`,`subtle`,`settings-secondary-text`,`accent`,`focus`]){let r=t[`--${n}`];r?e.style.setProperty(`--${n}`,r):e.style.removeProperty(`--${n}`)}},[r,o,a,i,l]),(0,K.jsx)(lr,{i18n:In,children:(0,K.jsx)(ju,{theme:tY,mode:u,children:e})})}var rY=document.getElementById(`root`);if(!rY)throw Error(`OpenPI Web root is missing`);(0,zt.createRoot)(rY).render((0,K.jsx)(_.StrictMode,{children:(0,K.jsx)(nY,{children:(0,K.jsx)($J,{})})}));export{lt as a,Lt as i,Po as n,$e as o,cr as r,x as s,Lp as t}; \ No newline at end of file +`,t),i=-1;if(n!==-1&&r!==-1?i=n20?`${e.slice(0,20)}…`:e}"`,{type:`unknown-field`,field:e,value:t,line:n}))}}function T(){u!==void 0&&a?.(u),f>0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0}function E(e={}){if(e.consume&&s.length>0){let e=s.join(``);C(e,0,e.length)}l=!0,u=void 0,d=``,f=0,p=void 0,s.length=0,c=0,m=!1,h=!1,g=!1}return{feed:_,reset:E}}function xJ(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function SJ(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}function CJ(e,t){let n=1;for(;nt.abort();e.signal.addEventListener(`abort`,n,{once:!0}),e.signal.aborted&&n();let r=window.setTimeout(n,45e3),i=await fetch(`/events?cursor=${e.cursor}`,{headers:await e.client.headers(),signal:t.signal}).finally(()=>{window.clearTimeout(r),e.signal.removeEventListener(`abort`,n)});if(i.status===409)throw new wJ(`event replay expired`);if(!i.ok||!i.body)throw Error(`event connection failed`);e.onConnected();let a=e.cursor,o=0,s=bJ({onComment(t){t.trim()===`heartbeat`&&++o>=4&&(o=0,e.onHeartbeat?.())},onEvent(t){let n=JSON.parse(t.data);if(!Number.isSafeInteger(n.sequence))throw new wJ(`invalid event cursor`);if(!(n.sequence<=a)){if(n.sequence!==a+1)throw new wJ(`event cursor gap`);if(a=n.sequence,n.type===`state_invalidated`)throw new wJ(`state invalidated`);e.onEvent(n)}}}),c=i.body.getReader(),l=new TextDecoder;try{for(;!e.signal.aborted;){let t,n,r=c.read(),i=new Promise((r,i)=>{n=()=>i(Error(`event stream aborted`)),e.signal.addEventListener(`abort`,n,{once:!0}),window.addEventListener(`offline`,n,{once:!0}),(e.signal.aborted||navigator.onLine===!1)&&n(),t=window.setTimeout(()=>i(Error(`event stream stalled`)),45e3)}),{done:a,value:o}=await Promise.race([r,i]).finally(()=>{window.clearTimeout(t),n&&(e.signal.removeEventListener(`abort`,n),window.removeEventListener(`offline`,n))});if(a)throw Error(`event connection closed`);s.feed(l.decode(o,{stream:!0}))}}finally{await c.cancel().catch(()=>void 0)}}var EJ=`openpi.collapsed-workspaces`,DJ=`openpi.sidebar-collapsed`,OJ=new Set(`agent_start.turn_started.turn_settled.agent_settled.prompt_settled.message_end.tool_execution_end.session_start.session_switched.session_progress.queue_update.prompt_failed.prompt_discarded.model_select.settings_changed.workspace_imported.workspace_removed.workspace_renamed.session_renamed.session_archived.session_unarchived.session_pins_changed.sidebar_pins_changed.workspace_order_changed.session_order_changed.session_read_state_changed.session_created.session_forked.session_deleted.prompt_accepted.runtime_changed.questions_changed.command_feedback.command_submitted.plan_mode_changed`.split(`.`));function kJ(e){try{let t=JSON.parse(window.sessionStorage.getItem(e)||`[]`);return new Set(Array.isArray(t)?t.filter(e=>typeof e==`string`):[])}catch{return new Set}}function AJ(e){try{return window.sessionStorage.getItem(e)===`true`}catch{return!1}}function jJ(e,t){try{window.sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function MJ(e){let t=8,n=[];for(let r=e.length-1;r>=0;r--){let i=e[r];(i.optimistic||t-->0)&&n.push(i)}return n.reverse()}var NJ=1e3,PJ=new Set,FJ=new WeakMap;function IJ(e){if(e){if(e.role===`toolResult`&&e.toolCallId)return`tool-result-${e.toolCallId}`;if(e.timestamp!==void 0)return`message-${e.role}-${e.timestamp}`}}function LJ(e){return e?.parts?.some(e=>e.type===`thinking`)===!0}function RJ(e){if(!e)return PJ;let t=FJ.get(e);if(t)return t;let n=new Set;for(let t of e){if(!LJ(t.message))continue;n.add(t.id);let e=IJ(t.message);e&&n.add(e)}return FJ.set(e,n),n}function zJ(e,t){for(let n of Object.keys(e))if(!t.has(n)){let n={};for(let r of Object.keys(e))t.has(r)&&(n[r]=e[r]);return n}return e}function BJ(e,t){if(e.length!==t.length)return!1;for(let n=0;ne.optimistic?.sessionId===t?.id&&e.optimistic?.sessionPath===t?.path&&e.optimistic!==void 0)}function HJ(e,t,n,r){return e.map(e=>e.optimistic?.sessionId===t&&e.optimistic.sessionPath===n&&e.optimistic.commandId===r&&!e.optimistic.admitted?{...e,optimistic:{...e.optimistic,admitted:!0}}:e)}function UJ(e,t){return t.aborted?Promise.resolve():new Promise(n=>{let r=()=>{window.clearTimeout(i),t.removeEventListener(`abort`,r),n()},i=window.setTimeout(r,e);t.addEventListener(`abort`,r,{once:!0})})}function WJ(e){return/^\/(?![\\/])/u.test(e)||/^[a-z]:[\\/]/iu.test(e)||/^\\\\(?![?.]\\)[^\\/]+\\[^\\/]+\\/u.test(e)||/^\/\/[^\\/]+\/[^\\/]+\//u.test(e)}function GJ(e=new rf,t={}){let n=t.consumeEvents??TJ,r=new URLSearchParams(window.location.search),i=r.get(`sessionPath`),a=r.get(`sessionId`),o=i!==null||a!==null,s=i&&WJ(i)&&i.length<=4096&&a&&a.length<=128&&!/[\u0000-\u001f\u007f]/u.test(i+a)&&r.getAll(`sessionPath`).length===1&&r.getAll(`sessionId`).length===1?{path:i,id:a}:null,c=0,l=0,u=null,d=!1,f=new Map,p=0,m=0,h=null,g=0,_=null,v=null,y=null,b=null,x=Promise.resolve(),S=null,C=null,w=!1,T=!1,E=null,D=null,O=0,k=null,A=0,j=!1,M=0,N=0,P=null,F=-1,I=null,L=0,R=0,ee=new Set,z=new Set,B=[],V=(e,t)=>{if(typeof t==`string`)for(e.add(t);e.size>32;){let t=e.values().next().value;t&&e.delete(t)}},H=()=>(R++,B=[],{planSelectionPending:!1,activeTurn:null,turnCancellationPending:!1,turnTerminalStatus:null,pendingFollowUpsReceipt:null,pendingSteeringReceipt:null,liveMessages:[],liveRunning:!1,livePhase:`idle`,liveRetry:null,thinkingStarts:{},thinkingDurations:{}}),te=e=>{let t=B.indexOf(e);for(t>=0&&B.splice(t,1),B.push(e);B.length>NJ;)B.shift()},ne=(e,t,n,r)=>{let i=RJ(t);B.some(e=>i.has(e))&&(B=B.filter(e=>!i.has(e)));let a=new Set(i);for(let t of e){a.add(t.key);let e=IJ(t.message);e&&a.add(e)}for(let e of B)a.add(e);let o=zJ(n,a),s=zJ(r,a);return o===n&&s===r?null:{thinkingStarts:o,thinkingDurations:s}},re=()=>(O++,D?.abort(),D=null,{modelSearch:{query:``,status:`idle`,models:[],totalMatches:0,matchesOmitted:0,error:null}}),ie=()=>({sessionId:null,status:`idle`,commands:[],totalAvailable:0,commandsOmitted:0,error:null}),ae=(e,t)=>({liveRunning:t===`running`||!e,livePhase:t===`running`?`running`:e?`idle`:`preparing`});return dr((t,r)=>{let i=e=>{h=null,t({notice:e instanceof Error?e.message:String(e)})},a=e=>{let t=r().snapshot;return e.epoch===c&&r().selectedWorkspace===e.workspacePath&&t?.currentSessionId===e.sessionId&&rj(t)&&t.selectedSession?.id===e.sessionId&&r().selectedPath===t.selectedSession.path&&t.selectedSession.cwd===e.workspacePath&&(!e.sessionPath||t.selectedSession.path===e.sessionPath)},B=()=>{L++,I?.abort(),I=null,t({commandDiscovery:ie()})},U=async(n,a,o,s)=>{if(r().modelSelectionPending)return!1;t({modelSelectionPending:!0});try{let i=await e.selectModel(n.provider,n.id,o,s);if(a!==c||s!==r().selectedPath||o!==r().snapshot?.selectedSession?.id)return!1;if(i.provider!==n.provider||i.id!==n.id||!i.current)throw Error(`Model selection was not confirmed. Please select a model again.`);if(!await r().actions.refreshSnapshot({epoch:a})||a!==c||s!==r().selectedPath||o!==r().snapshot?.selectedSession?.id)return!1;let l=r().snapshot?.models.find(e=>e.current);if(l?.provider!==n.provider||l.id!==n.id)throw Error(`The Session model changed. Please select a model again.`);return t({draftModel:null,notice:null}),!0}catch(e){return a===c&&s===r().selectedPath&&o===r().snapshot?.selectedSession?.id&&i(e),!1}finally{a===c&&t({modelSelectionPending:!1})}},oe=(e=160)=>{if(w){T=!0;return}C===null&&(C=window.setTimeout(async()=>{C=null,w=!0;try{await r().actions.refreshSnapshot()}finally{w=!1,T&&(T=!1,oe())}},e))},se=()=>{P=null,N=0,F=-1},ce=()=>{let e=r().snapshot;if(!e)return;P&&F!==c&&se();let n=e.thinking;if(n){if(!P||n.revision>=N){P=n,N=n.revision,F=c;return}n!==P&&t({snapshot:{...e,thinking:P}})}},le=e=>{P&&F!==c&&se(),e&&e.revision>=N&&(P=e,N=e.revision,F=c),ce()},ue=()=>{k=null,A++,j=!1,t({thinkingPendingLevel:null})},de=async()=>{let t=c,n=r().snapshot?.selectedSession?.id,i=r().selectedPath;if(n)try{let a=await e.thinking(n,new AbortController().signal);if(t!==c||i!==r().selectedPath||n!==r().snapshot?.selectedSession?.id)return;le(a)}catch{}},fe=async()=>{if(j)return;j=!0;let n=++M;try{for(;k!==null;){let n=k,a=A,o=c,s=r().snapshot?.selectedSession?.id,l=r().selectedPath;if(!s||!l||s!==r().snapshot?.currentSessionId||l!==r().snapshot?.selectedSession?.path||r().modelSelectionPending){ue();return}if(r().snapshot?.thinking?.level===n){a===A&&(k=null,t({thinkingPendingLevel:null}));continue}let u;try{u=await e.setThinkingLevel(s,n,l)}catch(e){if(o!==c||l!==r().selectedPath)return;if(a!==A)continue;ue(),i(e),de();return}if(o!==c||l!==r().selectedPath||s!==r().snapshot?.selectedSession?.id)return;if(a===A){if(u.level!==n){ue(),i(Error(In.t(`thinkingNotConfirmed`)));return}le(u),k=null,t({thinkingPendingLevel:null}),oe();return}}}finally{n===M&&(j=!1)}},pe=e=>{let n=r(),i=e.detail??{},a=i.sessionId,o=[`session_start`,`session_switched`,`session_created`].includes(e.type);if(n.cursor!==null&&e.sequence<=n.cursor)return;t({cursor:e.sequence});let s=n.promptAdmissionRecovery,l=s?.commandId,u=n.snapshot?.selectedSession,d=u?.id===a&&u?.path===n.selectedPath&&(i.sessionPath===void 0||i.sessionPath===u?.path);if(d&&s?.sessionId===u?.id&&s?.sessionPath===u?.path&&typeof i.commandId==`string`&&i.commandId===l&&[`prompt_accepted`,`prompt_failed`,`prompt_settled`,`turn_started`,`turn_settled`].includes(e.type)){let r=e.type!==`prompt_failed`;t({promptAdmissionRecovery:null,promptAdmissionResolution:s?{sessionId:s.sessionId,sessionPath:s.sessionPath,commandId:s.commandId,content:s.content,images:s.images}:n.promptAdmissionResolution,liveMessages:r&&s&&!s.delivery?.retryEntryId&&!n.liveMessages.some(e=>e.key===s.optimisticKey)?MJ([...n.liveMessages,{key:s.optimisticKey,timestamp:s.timestamp??e.timestamp,optimistic:{sessionId:s.sessionId,sessionPath:s.sessionPath,commandId:s.commandId,afterEntryId:s.afterEntryId??null,admitted:e.type===`prompt_accepted`},message:{role:`user`,content:s.content}}]):n.liveMessages})}if(e.type===`prompt_accepted`&&d&&u&&typeof i.commandId==`string`&&t({liveMessages:HJ(r().liveMessages,u.id,u.path,i.commandId)}),n=r(),(e.type===`runtime_changed`||e.type===`settings_changed`)&&t(re()),e.type===`runtime_changed`&&B(),n.sessionSwitching&&!o){oe();return}if(typeof a==`string`&&a!==n.snapshot?.currentSessionId&&!o){oe();return}if([`auto_retry_start`,`auto_retry_end`].includes(e.type)&&typeof i.sessionPath==`string`&&i.sessionPath!==(n.snapshot?.currentSessionPath??n.snapshot?.selectedSession?.path)){oe();return}if(!o&&(i.message||e.type.startsWith(`tool_execution_`))&&!rj(n.snapshot)){OJ.has(e.type)&&oe();return}if(n.snapshot){let r=n.snapshot.runtime.liveTools??[],a=fJ(r,e.type,i);a!==r&&t({snapshot:{...n.snapshot,runtime:{...n.snapshot.runtime,liveTools:a}}})}if(o){let o=i.commandId;if(typeof o==`string`&&z.has(o)){oe();return}let s=i.sessionPath,l=n.snapshot?.sessions.some(e=>e.path===s),u=!1;if(y?.kind===`select`?u=y.expectedPath===s:(y?.kind===`create`&&y.commandId===o&&e.type===`session_switched`&&typeof a==`string`&&(!y.expectedSessionId||y.expectedSessionId===a)&&(typeof s!=`string`||!l)||y?.kind===`create`&&y.commandId===o&&e.type===`session_created`&&typeof a==`string`&&(!y.expectedSessionId||a===y.expectedSessionId))&&(u=!0),u&&y?.epoch!==c)return;if(u)t({...H(),liveMessages:VJ(n.liveMessages,n.snapshot?.selectedSession)});else{if(!y&&n.selectedPath&&n.snapshot?.selectedSession?.path===n.selectedPath){B(),ue(),t({...H(),liveMessages:VJ(n.liveMessages,n.snapshot.selectedSession),snapshot:{...n.snapshot,currentSessionId:void 0,currentSessionPath:void 0},modelSelectionPending:!1});let e=c;r().actions.refreshSnapshot({epoch:e});return}B();let e=++c;ue(),_=null,v=null,t({...H(),promptAdmissionPending:!1,promptAdmissionRecovery:null,selectedPath:typeof s==`string`?s:null,draftModel:n.workspaceDraft?n.draftModel:null,modelSelectionPending:!1,sessionSwitching:!0}),r().actions.refreshSnapshot({epoch:e}).then(n=>{e===c&&t({selectedPath:n?r().selectedPath:null,sessionSwitching:!1})})}}else if(e.type===`prompt_accepted`){let e=ee.has(String(i.commandId??``));t({...ae(e,n.livePhase),liveRetry:null,pendingFollowUpsReceipt:Number.isInteger(i.pendingFollowUps)?Number(i.pendingFollowUps):n.pendingFollowUpsReceipt,pendingSteeringReceipt:Number.isInteger(i.pendingSteering)?Number(i.pendingSteering):n.pendingSteeringReceipt})}else if(e.type===`turn_started`)m=e.sequence,t({activeTurn:{sessionId:String(i.sessionId),commandId:String(i.commandId),epoch:Number(i.epoch),...typeof i.sessionPath==`string`?{sessionPath:i.sessionPath}:{},...typeof i.promptEntryId==`string`?{promptEntryId:i.promptEntryId}:{},...typeof i.startedAt==`number`?{startedAt:i.startedAt}:{},...typeof i.elapsedMs==`number`?{elapsedMs:i.elapsedMs}:{}},liveRunning:!0,livePhase:`running`,liveRetry:null,turnTerminalStatus:null});else if(e.type===`agent_start`)m=e.sequence,t({...i.activeTurn?{activeTurn:i.activeTurn}:{},liveRunning:!0,livePhase:`running`,liveRetry:null});else if(e.type===`turn_settled`){V(ee,i.commandId);let r=n.activeTurn;r?.sessionId===i.sessionId&&r?.commandId===i.commandId&&r?.epoch===i.epoch&&(m=e.sequence,t({activeTurn:null,liveRunning:!1,livePhase:`idle`,liveRetry:null,turnTerminalStatus:typeof i.outcome==`string`?i.outcome:null}))}else if(e.type===`agent_settled`)n.activeTurn||(m=e.sequence),t({pendingFollowUpsReceipt:null,pendingSteeringReceipt:null,...n.activeTurn?{}:{liveRunning:!1,livePhase:`idle`,liveRetry:null}});else if(e.type===`prompt_settled`)V(ee,i.commandId),n.livePhase!==`running`&&t({liveRunning:!1,livePhase:`idle`,liveRetry:null});else if(i.message&&typeof i.message==`object`){let r=i.message,a=n.liveMessages,o=typeof i.messageKey==`string`?i.messageKey:`${r.role||`message`}-${e.sequence}`,s={key:o,message:r},c=a.findIndex(e=>e.key===o);a=c>=0?a.map((e,t)=>t===c?s:e):MJ([...a,s]);let l=!BJ(n.liveMessages,a),u=n.thinkingStarts,d=n.thinkingDurations,f=!1;if(r.parts?.some(e=>e.type===`thinking`)&&(u[o]===void 0&&(u={...u,[o]:Date.now()},f=!0),e.type===`message_end`)){let e=IJ(r),t=Date.now()-u[o];d={...d,[o]:t},e&&(d[e]=t),te(e??o),f=!0}if(f||l){let e=ne(a,n.snapshot?.selectedSession?.entries,u,d);e&&(u=e.thinkingStarts,d=e.thinkingDurations,f=!0)}t({liveMessages:a,...f?{thinkingStarts:u,thinkingDurations:d}:{}})}if(e.type===`prompt_discarded`&&typeof i.commandId==`string`&&(V(ee,i.commandId),t({liveMessages:r().liveMessages.filter(e=>e.optimistic?.commandId!==i.commandId)})),e.type===`prompt_failed`){V(ee,i.commandId);let e=typeof i.commandId==`string`&&n.activeTurn?.commandId===i.commandId;t({liveMessages:r().liveMessages.filter(e=>!e.optimistic||e.optimistic.commandId!==i.commandId),...e||n.livePhase!==`running`?{liveRunning:!1,livePhase:`idle`,liveRetry:null}:{},notice:typeof i.error==`string`?i.error:`Prompt failed`})}if(e.type===`auto_retry_start`&&t({liveRunning:!0,livePhase:`running`,liveRetry:{attempt:Number(i.attempt)||0,maxAttempts:Number(i.maxAttempts)||0}}),e.type===`auto_retry_end`&&t({liveRetry:null}),e.type===`thinking_level_changed`){let t=r().snapshot?.thinking;t&&typeof i.level==`string`&&le({...t,level:i.level,revision:e.sequence})}OJ.has(e.type)&&oe()},me=async i=>{let a=500,o=!1;for(;!i.aborted;){let s=!1;try{if(r().cursor===null){if(s=!0,!await r().actions.refreshSnapshot({resetCursor:!0}))throw Error(`snapshot unavailable`);s=!1}if(i.aborted)return;await n({client:e,cursor:r().cursor??0,onConnected:()=>{a=500,t({connection:`connected`}),o&&(o=!1,oe(0))},onEvent:pe,onHeartbeat:()=>oe(0),signal:i})}catch(e){if(i.aborted)return;t({connection:`reconnecting`});let n=!s&&await r().actions.refreshSnapshot({resetCursor:!0});o=!n,n||t(H()),await UJ(a,i),a=Math.min(a*2,5e3),e instanceof SyntaxError&&t({notice:`Invalid event data`})}}},W={rememberPromptProjection(e,n,i){let a=r(),o=a.snapshot?.selectedSession;if(a.selectedPath!==n||o?.id!==e||o.path!==n)return;let s=new Set(o.entries.map(e=>e.id)),c=new Set(a.liveMessages.flatMap(t=>t.optimistic?.sessionId===e&&t.optimistic.sessionPath===n&&t.optimistic.projectedEntryId?[t.optimistic.projectedEntryId]:[])),l=new Map(i.map(e=>[e.key,e.entryId])),u=!1,d=a.liveMessages.map(t=>{let r=l.get(t.key);return!r||!s.has(r)||c.has(r)||t.optimistic?.sessionId!==e||t.optimistic.sessionPath!==n||!t.optimistic.admitted||t.optimistic.projectedEntryId?t:(u=!0,c.add(r),{...t,optimistic:{...t.optimistic,projectedEntryId:r},message:{role:`user`,content:``}})});u&&t({liveMessages:d})},setHistoryAnchor(e){let n=r().snapshot?.selectedSession;if(e&&(n?.id!==e.sessionId||n.path!==e.sessionPath))return;let i=r().historyAnchor;(i?.entryId!==e?.entryId||i?.sessionId!==e?.sessionId||i?.sessionPath!==e?.sessionPath)&&t({historyAnchor:e})},start(){E||(E=new AbortController,me(E.signal))},stop(){E?.abort(),E=null,C!==null&&window.clearTimeout(C),C=null,ue(),B()},async refreshSnapshot(n={}){let a=n.epoch??c,o=++p,l=r().selectedPath;try{let i=r().historyAnchor,u=s?.path===l?s:null,d=u?await e.snapshot(l,void 0,u.id):i&&i.sessionPath===l?await e.snapshot(l,i):await e.snapshot(l);if(a!==c||o!==p)return!1;if(u&&(d.selectedSession?.id!==u.id||d.selectedSession.path!==u.path))throw new tf(In.t(`sessionLinkUnavailable`),409,`SESSION_CONFLICT`);u&&(s=null);let f=typeof d.currentSessionId==`string`,g=f?d.sessions.find(e=>rj(d,e)):void 0,_=f?rj(d):d.selectedSession===void 0,y=d.selectedSession?d.sessions.some(e=>e.id===d.selectedSession.id&&e.path===d.selectedSession.path):!f,b=!l||d.sessions.some(e=>e.path===l),x=!l||d.selectedSession?.path===l;if(!b||!x||!y||!l&&!_)return t({selectedPath:null}),!n.canonicalRetry&&W.refreshSnapshot({...n,canonicalRetry:!0,epoch:a});let S=d.selectedSession?.cwd,C=d.workspaces.find(e=>e.current)?.path,w=d.workspaces.some(e=>e.path===r().selectedWorkspace)?r().selectedWorkspace:void 0,T=r().workspaceDraft?r().selectedWorkspace:S??C??w??null,E=n.resetCursor;r().snapshot?.selectedSession?.path!==d.selectedSession?.path&&(ue(),se()),E&&se();let D=r().snapshot?.currentSessionId,O=r().snapshot?.sessions.find(e=>rj(r().snapshot,e)),k=D!==d.currentSessionId||O?.path!==g?.path,A=r().snapshot?.selectedSession?.id!==d.selectedSession?.id||r().snapshot?.selectedSession?.path!==d.selectedSession?.path,j=r().collapsed;if(A&&!r().workspaceDraft&&d.selectedSession){let e=d.sessions.find(e=>e.id===d.selectedSession.id&&e.path===d.selectedSession.path),t=e?.workspacePath??d.selectedSession.cwd;!e?.archived&&!e?.ungrouped&&j.has(t)&&(j=new Set(j),j.delete(t),jJ(EJ,[...j]))}let M=r().snapshot,N=E||k||A||M?.currentSessionPath!==d.currentSessionPath||JSON.stringify(M?.models)!==JSON.stringify(d.models)||M?.truncation.modelsOmitted!==d.truncation.modelsOmitted;k&&(B(),ue(),se());let P=h!==null&&r().notice===h;h=null,(E||k||A)&&(m=0);let F=m>d.cursor;if(t({...P?{notice:null}:{},...E||k||A?{...H(),liveMessages:VJ(r().liveMessages,d.selectedSession)}:{},connection:r().connection===`connecting`?`connecting`:r().connection,cursor:E||r().cursor===null?d.cursor:Math.max(r().cursor??0,d.cursor),activeTurn:F?r().activeTurn:d.runtime.activeTurn??null,livePhase:F?r().livePhase:d.runtime.status===`running`?`running`:!r().promptAdmissionPending&&!v?`idle`:r().livePhase,liveRetry:!F&&d.runtime.status!==`running`&&!r().promptAdmissionPending&&!v?null:r().liveRetry,liveRunning:F?r().liveRunning:d.runtime.status===`running`?!0:!r().promptAdmissionPending&&!v?!1:r().liveRunning,selectedPath:d.selectedSession?.path??null,selectedWorkspace:T,collapsed:j,snapshot:d,...N?re():{}}),!(E||k||A)){let e=ne(r().liveMessages,d.selectedSession?.entries,r().thinkingStarts,r().thinkingDurations);e&&t(e)}return le(),!0}catch(e){if(a!==c||o!==p)return!1;if(s?.path===l&&e instanceof tf&&[400,404,409].includes(e.status)){s=null,t({selectedPath:null,workspaceDraft:!0});let e=await W.refreshSnapshot({...n,epoch:a});return a===c&&t({notice:In.t(`sessionLinkUnavailable`)}),e}t({connection:`unavailable`}),i(e);let u=r().notice;return h=typeof u==`string`?u:null,!1}},async chooseWorkspace(){let t=c;try{let n=await e.chooseWorkspace();if(t!==c||n.cancelled||!n.path)return;W.setWorkspace(n.path),await W.refreshSnapshot()}catch(e){t===c&&i(e)}},setWorkspace(e){let n=r();e===n.selectedWorkspace&&!n.sessionSwitching||(++c,b=null,ue(),B(),_=null,v=null,t({...H(),...re(),selectedWorkspace:e,createdSession:null,workspaceDraft:!0,sessionSwitching:!1,modelSelectionPending:!1,promptAdmissionPending:!1,promptAdmissionRecovery:null,notice:null}))},async renameWorkspace(t,n){try{await e.renameWorkspace(t,n),await W.refreshSnapshot()}catch(e){throw i(e),e}},async removeWorkspace(n){try{return await e.removeWorkspace(n),r().selectedWorkspace===n&&B(),r().workspaceDraft&&r().selectedWorkspace===n&&t({selectedWorkspace:null}),await W.refreshSnapshot(),!0}catch(e){return i(e),!1}},async prepareSession(){if(r().sessionSwitching||r().modelSelectionPending)return null;r().selectedWorkspace||await W.chooseWorkspace();let e=r(),t=e.selectedWorkspace;if(!t||e.sessionSwitching||e.modelSelectionPending)return null;let n=e.snapshot?.selectedSession;if(!e.workspaceDraft&&n){if(e.selectedPath!==n.path||n.cwd!==t)return null;let r={epoch:c,sessionId:n.id,sessionPath:n.path,workspacePath:t};return!rj(e.snapshot)&&!await W.selectSession(n.path,n.id)?null:a(r)?r:null}return W.createSession(t)},async createSession(n){if(!n||r().modelSelectionPending)return null;let o=++c;ue(),B();let s=(b?.workspacePath===n?b.commandId:void 0)??globalThis.crypto?.randomUUID?.()??`web-create-${Date.now()}-${o}`;b={workspacePath:n,commandId:s},_=null,v=null,t({...H(),...re(),mobileSidebarOpen:!1,promptAdmissionPending:!1,promptAdmissionRecovery:null,selectedPath:null,selectedWorkspace:n,createdSession:null,workspaceDraft:!0,sessionSwitching:!0});let l=null,u=x.then(async()=>{if(o===c){y={commandId:s,epoch:o,expectedPath:null,kind:`create`};try{let u=await e.createSession(n,s);if(o!==c)return;if(u.cancelled||u.commandId!==s||typeof u.sessionId!=`string`||!u.sessionId||u.sessionId.length>128||u.sessionPath!==void 0&&!u.sessionPath)throw Error(`Session creation did not return a valid target identity.`);let d={epoch:o,sessionId:u.sessionId,sessionPath:u.sessionPath??null,workspacePath:n};y?.epoch===o&&(y.expectedSessionId=d.sessionId,y.expectedPath=d.sessionPath),t({selectedPath:d.sessionPath});let f=await W.refreshSnapshot({epoch:o});if(!f&&o===c&&(f=await W.refreshSnapshot({epoch:o})),o!==c)return;if(!f)throw Error(`The created Session could not be confirmed. Please try again.`);if(!a(d)){b=null,i(Error(`The created Session is no longer active in the selected workspace. Please try again.`));return}let p=r().selectedPath;if(!p)return;d.sessionPath=p,t({workspaceDraft:!1,createdSession:d,notice:null});let m=r().draftModel;if(m&&!await U(m,o,d.sessionId,p))return;if(r().workspaceDraft||!a(d)){b=null,i(Error(`The created Session is no longer active in the selected workspace. Please try again.`));return}l=d,b=null}catch(e){if(o!==c)return;t({selectedPath:null}),i(e),await W.refreshSnapshot({epoch:o})}finally{V(z,s),y?.epoch===o&&(y=null),o===c&&t({sessionSwitching:!1})}}});return x=u.catch(()=>void 0),await u,o===c?l:null},async selectSession(n,a){if(!n)return!1;let o=r();if(S?.path===n&&S.epoch===c){let e=S;t({mobileSidebarOpen:!1});let i=await e.promise,o=r();return i&&e.epoch===c&&o.selectedPath===n&&o.snapshot?.selectedSession?.path===n&&(!a||o.snapshot.selectedSession.id===a)&&!o.workspaceDraft&&rj(o.snapshot)}if(!o.workspaceDraft&&!o.sessionSwitching&&o.selectedPath===n&&o.snapshot?.selectedSession?.path===n&&(!a||o.snapshot.selectedSession.id===a)&&rj(o.snapshot))return t({mobileSidebarOpen:!1}),!0;b=null;let s=!o.workspaceDraft&&o.selectedPath===n&&o.snapshot?.selectedSession?.path===n;B(),t({...re(),workspaceDraft:!1,...s?{}:{draftModel:null,createdSession:null},modelSelectionPending:!1});let l=s?c:++c;ue(),s||(_=null,v=null),t({...H(),liveMessages:s?VJ(o.liveMessages,o.snapshot?.selectedSession):[],mobileSidebarOpen:!1,promptAdmissionPending:s?o.promptAdmissionPending:!1,promptAdmissionRecovery:s?o.promptAdmissionRecovery:null,selectedPath:n,sessionSwitching:!0});let u=x.then(async()=>{if(l!==c)return!1;y={epoch:l,expectedPath:n,kind:`select`};try{let i=await(a?e.selectSession(n,a):e.selectSession(n));if(l!==c)return!1;if(i.cancelled)return s||t({selectedPath:null}),await W.refreshSnapshot({epoch:l}),!1;let o=await W.refreshSnapshot({epoch:l});return l===c&&(!o&&!s&&t({selectedPath:null}),o&&r().selectedPath===n&&r().snapshot?.selectedSession?.path===n&&(!a||r().snapshot?.selectedSession?.id===a)&&!r().workspaceDraft&&rj(r().snapshot))}catch(e){return l===c&&(s||t({selectedPath:null}),i(e),await W.refreshSnapshot({epoch:l}),!1)}finally{y?.epoch===l&&(y=null),l===c&&t({sessionSwitching:!1})}});x=u.then(()=>void 0,()=>void 0),S={path:n,epoch:l,promise:u};try{return await u}finally{S?.promise===u&&(S=null)}},async navigateToMessage(n,i){let a=++l;try{if(i?.aborted||await W.selectSession(n.sessionPath)===!1)return!1;let o=c,s=r().snapshot?.selectedSession;if(i?.aborted||a!==l||r().sessionSwitching||s?.id!==n.sessionId||s.path!==n.sessionPath)return!1;let u=await e.sessionMessageWindow(n,i);if(i?.aborted||a!==l||o!==c)return!1;let d=r().snapshot?.selectedSession;return d?.id!==n.sessionId||d.path!==n.sessionPath||u.id!==n.sessionId||u.path!==n.sessionPath||u.history?.anchorEntryId!==n.entryId||u.history.anchorOnBranch!==!0||!u.entries.some(e=>e.id===n.entryId)?!1:(t({historyNavigation:{...n,session:u,revision:(r().historyNavigation?.revision??0)+1}}),!0)}catch{return!1}},async editMessage(e,t){return W.forkMessage(e,{mode:`edit`,content:t})},async regenerateMessage(e){return W.forkMessage(e,{mode:`regenerate`})},acknowledgeRestoredPromptDraft(e){r().restoredPromptDraft?.commandId===e&&t({restoredPromptDraft:null})},async cancelSessionFork(){let n=u;if(!n||n.scope!==`conversation`||!r().sessionForkPending||r().sessionForkCancellation)return;let a=c;t({sessionForkCancellation:`requesting`});try{let i=await e.cancelSessionFork({commandId:n.commandId,sessionId:n.sessionId,sessionPath:n.sessionPath});u===n&&r().sessionForkPending&&(t({sessionForkCancellation:i.state===`not-found`?null:i.state}),i.state===`not-found`&&t({notice:In.t(`sidebarForkCancelUnconfirmed`)}))}catch(e){a===c&&r().sessionForkPending&&(t({sessionForkCancellation:null}),i(e))}},async forkConversation(e,t,n=`local`){return r().sessionForkPending||r().sessionSwitching||d||!await W.selectSession(e,t)?!1:W.forkMessage({scope:`conversation`,sessionPath:e,sessionId:t,environment:n})},async forkMessage(n,i){let a=`scope`in n&&n.scope===`conversation`;if(a&&i||i?.mode===`edit`&&(!i.content.trim()||i.content.length>12e3))return!1;let o=r(),s=o.snapshot?.selectedSession;if(o.sessionForkPending||d)return!1;if(!s||o.workspaceDraft||o.sessionSwitching||o.promptAdmissionPending||o.promptAdmissionRecovery||!a&&(o.liveRunning||o.activeTurn||o.snapshot?.runtime.status!==`idle`)||o.modelSelectionPending||!rj(o.snapshot)||s.id!==n.sessionId||s.path!==n.sessionPath||o.selectedPath!==n.sessionPath||s.path.startsWith(`current:`))return t({notice:In.t(`forkSessionUnavailable`)}),!1;let f=`entryId`in n?n.entryId:void 0,p=u?.sessionId===n.sessionId&&u.sessionPath===n.sessionPath&&u.entryId===f&&u.scope===`conversation`===a&&(!a||u.scope===`conversation`&&(u.environment??`local`)===(n.environment??`local`))&&JSON.stringify(u.rerun)===JSON.stringify(i)?u:{sessionId:n.sessionId,sessionPath:n.sessionPath,...a?{scope:`conversation`,...n.environment===`worktree`?{environment:`worktree`}:{}}:{entryId:f,...i?{rerun:i}:{}},commandId:globalThis.crypto?.randomUUID?.()??`web-fork-${Date.now()}-${++l}`};u=p;let m=c,h=m;t({sessionForkPending:!0,sessionForkCancellation:null,sessionForkEnvironment:a?n.environment??`local`:void 0,notice:null});try{let o=await e.forkSession(p);if(m!==c||r().selectedPath!==n.sessionPath)return!1;if(o.commandId!==p.commandId||o.source.sessionId!==n.sessionId||o.source.sessionPath!==n.sessionPath||!a&&o.source.entryId!==f||!o.source.entryId)throw Error(In.t(`forkSessionUncertain`));if(o.state!==`forked`)return t({notice:[In.t(o.state===`cancelled`?`forkSessionCancelled`:`forkSessionUncertain`),o.reason,o.preservedWorktreePath?In.t(`sidebarForkWorktreePreserved`,{path:o.preservedWorktreePath}):void 0].filter(Boolean).join(` `)}),o.state===`cancelled`?u=null:await W.refreshSnapshot({epoch:m}),!1;if(!o.sessionId||!o.sessionPath||o.sessionId===n.sessionId||o.sessionPath===n.sessionPath)throw Error(In.t(`forkSessionUncertain`));let s=++c;h=s,v=null,_=null,ue(),B(),t({...H(),...re(),selectedPath:o.sessionPath,historyAnchor:null,historyNavigation:null,createdSession:null,draftModel:null,sessionSwitching:!0});let l=await W.refreshSnapshot({epoch:s});if(!l&&s===c&&r().selectedPath===o.sessionPath&&(l=await W.refreshSnapshot({epoch:s})),s!==c)return!1;let d=r().snapshot;if(o.replayed&&l&&d?.selectedSession?.id===o.sessionId&&d.selectedSession.path===o.sessionPath&&!rj(d)){if(l=await W.selectSession(o.sessionPath,o.sessionId)===!0,s!==c)return!1;d=r().snapshot}if(!l||r().selectedPath!==o.sessionPath||d?.selectedSession?.id!==o.sessionId||d.selectedSession.path!==o.sessionPath||!rj(d))return t({notice:In.t(`forkSessionUncertain`)}),!1;if(u=null,i){let e=o.prompt;if(!e||typeof e.content!=`string`||!Array.isArray(e.images))throw Error(In.t(`forkSessionUncertain`));t({sessionForkPending:!1,sessionSwitching:!1});let n=W.sendPrompt(e.content,e.images,void 0,void 0,{epoch:s,sessionId:o.sessionId,sessionPath:o.sessionPath,workspacePath:d.selectedSession.cwd}),i=[...r().liveMessages].reverse().find(e=>e.optimistic?.sessionId===o.sessionId&&e.optimistic?.sessionPath===o.sessionPath)?.optimistic?.commandId??p.commandId,a=await n;return s!==c||r().selectedPath!==o.sessionPath?!1:a?(t({notice:{kind:`success`,message:In.t(`messageRerunStarted`)}}),!0):(r().promptAdmissionRecovery||t({restoredPromptDraft:{sessionId:o.sessionId,sessionPath:o.sessionPath,commandId:i,content:e.content,images:e.images}}),!1)}return t({notice:{kind:`success`,message:In.t(`forkSessionCreated`)}}),!0}catch(e){return h===c&&(e instanceof tf&&[`SESSION_CONFLICT`,`SESSION_FORK_UNAVAILABLE`,`SESSION_FORK_CAPACITY`].includes(e.code??``)?(u=null,t({notice:a?e.message:In.t(`forkSessionUnavailable`)})):t({notice:In.t(`forkSessionUncertain`)})),!1}finally{t({sessionForkPending:!1,sessionForkCancellation:null,sessionForkEnvironment:void 0}),c===h&&h!==m&&r().sessionSwitching&&t({sessionSwitching:!1})}},async savePreferences(t){try{await e.savePreferences(t),await W.refreshSnapshot()}catch(e){throw i(e),e}},async renameSession(t,n){try{await e.renameSession(t,n),await W.refreshSnapshot()}catch(e){throw i(e),e}},async releaseSessionWorktree(t){let n=JSON.stringify([t.sessionId,t.sessionPath,t.worktreePath]),r=f.get(n);if(r?.pending)return r.pending;if(!r&&f.size>=128){let e=[...f].find(([,e])=>e.state===`preserved`&&!e.pending);if(e)f.delete(e[0]);else throw Error(In.t(`managedWorktreeRecoveryFull`))}let i={commandId:r?.state===`uncertain`?r.commandId:crypto.randomUUID(),state:`uncertain`,pending:void 0};return f.set(n,i),i.pending=(async()=>{try{let r=await e.releaseSessionWorktree({...t,commandId:i.commandId});if(r.commandId!==i.commandId||r.sessionId!==t.sessionId||r.sessionPath!==t.sessionPath||r.worktreePath!==t.worktreePath||![`removed`,`preserved`,`uncertain`].includes(r.state))throw Error(In.t(`managedWorktreeUncertain`));return r.state===`removed`?f.delete(n):i.state=r.state,r}finally{i.pending=void 0}})(),i.pending},async deleteSession(n,a,o){if(d||r().sessionForkPending||r().sessionSwitching)return!1;d=!0;let s=c;try{let i=await e.deleteSession({sessionPath:n,sessionId:a,commandId:o});if(i.commandId!==o||i.sessionId!==a||i.sessionPath!==n)throw Error(In.t(`sessionDeleteUncertain`));return i.state===`deleted`?(s===c&&r().selectedPath===n&&(++c,ue(),B(),_=null,v=null,t({...H(),...re(),selectedPath:null,historyAnchor:null,historyNavigation:null,workspaceDraft:!0,createdSession:null})),await W.refreshSnapshot(),t({notice:i.worktreeReleaseTarget?{kind:`success`,message:In.t(`managedWorktreeRetainedAfterDelete`,{path:i.worktreeReleaseTarget.worktreePath})}:i.metadataCleanupPending?In.t(`sessionDeleteMetadataPending`):{kind:`success`,message:In.t(`sessionDeleted`)}}),!0):(s===c&&(await W.refreshSnapshot({epoch:s}),t({notice:In.t(i.state===`cancelled`?`sessionDeleteCancelled`:`sessionDeleteUncertain`)})),!1)}catch(e){return s===c&&i(e),!1}finally{d=!1}},async setSessionPin(t,n,r,a){try{await e.setSessionPin(t,n,r,a),await W.refreshSnapshot()}catch(e){throw i(e),e}},async archiveSession(n){let a=r().snapshot?.sessions.find(e=>e.path===n);try{await e.archiveSession(n);let r={key:crypto.randomUUID(),path:n,sessionId:a?.id,title:ZA(a??{},In.t(`untitledSession`))};t(e=>({archiveNotices:[r,...e.archiveNotices.filter(e=>e.path!==n)].slice(0,3)})),await W.refreshSnapshot()}catch(e){i(e)}},dismissArchiveNotice(e){t(t=>({archiveNotices:t.archiveNotices.filter(t=>t.key!==e)}))},async setSidebarPin(t,n,r){try{await e.setSidebarPin(t,n,r),await W.refreshSnapshot()}catch(e){throw i(e),e}},async setWorkspaceOrder(t,n){try{await e.setWorkspaceOrder(t,n),await W.refreshSnapshot()}catch(e){throw e instanceof tf&&e.code===`WORKSPACE_ORDER_CHANGED`&&await W.refreshSnapshot(),i(e),e}},async setSessionOrder(t,n,r){try{await e.setSessionOrder(t,n,r),await W.refreshSnapshot()}catch(e){throw i(e),e}},async setSessionRead(t,n,r,a){try{await e.setSessionRead(t,n,r,a),await W.refreshSnapshot()}catch(e){throw e instanceof tf&&e.code===`SESSION_READ_STATE_CHANGED`?await W.refreshSnapshot():i(e),e}},async unarchiveSession(n){let r=c;try{if(await e.unarchiveSession(n),t(e=>({archiveNotices:e.archiveNotices.filter(e=>e.path!==n)})),r!==c)return!0;let i=p,a=await W.refreshSnapshot({epoch:r});return!a&&r===c&&p>i+1&&(a=await W.refreshSnapshot({epoch:r})),r!==c||a}catch(e){return r===c&&i(e),!1}},async selectModel(e){let[n,...i]=e.split(`/`),a=i.join(`/`),o=r();if(!n||!a||o.sessionSwitching||o.modelSelectionPending||o.promptAdmissionPending||!o.workspaceDraft&&(o.liveRunning||o.snapshot?.runtime.status===`running`))return!1;let s=o.snapshot?.selectedSession?.id;if(o.workspaceDraft||!s&&!o.snapshot?.currentSessionId){let e=[...o.snapshot?.models??[],...o.modelSearch.models].find(e=>e.provider===n&&e.id===a);return e&&t({draftModel:e,notice:null}),!!e}return!s||!o.selectedPath||!rj(o.snapshot)||s!==o.snapshot?.currentSessionId||o.selectedPath!==o.snapshot?.selectedSession?.path?!1:(ue(),U({provider:n,id:a},c,s,o.selectedPath))},async searchModels(n){let i=n.trim();if(!i){t(re());return}D?.abort();let a=new AbortController;D=a;let o=++O,s=c,l=r().snapshot?.currentSessionId;t({modelSearch:{query:i,status:`loading`,models:[],totalMatches:0,matchesOmitted:0,error:null}});try{let n=await e.searchModels(i,l,a.signal);if(a.signal.aborted||s!==c||o!==O)return;t({modelSearch:{query:i,status:`ready`,models:n.models,totalMatches:n.totalMatches,matchesOmitted:n.truncation.matchesOmitted,error:null}})}catch(e){if(a.signal.aborted||s!==c||o!==O)return;t({modelSearch:{query:i,status:`error`,models:[],totalMatches:0,matchesOmitted:0,error:e instanceof Error?e.message:String(e)}})}finally{D===a&&(D=null)}},clearModelSearch(){t(re())},selectThinking(e){let n=r(),i=n.snapshot?.thinking,a=n.snapshot?.selectedSession?.id;!e||!i?.supported||n.sessionSwitching||n.modelSelectionPending||n.workspaceDraft||!a||!rj(n.snapshot)||a!==n.snapshot?.currentSessionId||n.selectedPath!==n.snapshot?.selectedSession?.path||n.liveRunning||n.snapshot?.runtime.status===`running`||e!==(n.thinkingPendingLevel??i.level)&&(k=e,A++,t({thinkingPendingLevel:e}),fe())},async selectPlanMode(n){let a=r(),o=a.snapshot,s=o?.selectedSession;if(!o||!s||!rj(o,s)||a.workspaceDraft||a.sessionSwitching||a.planSelectionPending||a.promptAdmissionPending||a.promptAdmissionRecovery||a.liveRunning||o.runtime.status!==`idle`||o.runtime.planRevision===void 0)return;let l=c,u=++R;t({planSelectionPending:!0});try{if(await e.setPlanMode(s.id,s.path,n,o.runtime.planRevision),l===c&&u===R&&!await W.refreshSnapshot({epoch:l}))throw Error(In.t(`planModeUnconfirmed`))}catch(e){l===c&&u===R&&(await W.refreshSnapshot({epoch:l}),l===c&&u===R&&i(e))}finally{l===c&&u===R&&t({planSelectionPending:!1})}},async preparePlanImplementation(){let n=r(),a=n.snapshot,o=a?.selectedSession,s=o?.id;if(!s||!rj(a,o)||s!==a?.currentSessionId||!o?.path||n.selectedPath!==o.path||n.workspaceDraft||n.sessionSwitching||n.planSelectionPending||n.promptAdmissionPending||n.promptAdmissionRecovery||n.liveRunning||a.runtime.status!==`idle`||a.runtime.plan!==`ready`||typeof a.runtime.planRevision!=`string`)return null;let l=c,u=++R,d=o.path,f=a.runtime.planRevision;t({planSelectionPending:!0});try{let t;try{t=await e.preparePlanImplementation(s,d,f)}catch(e){if(l===c&&u===R){try{await W.refreshSnapshot({epoch:l})}catch{}l===c&&u===R&&i(e)}return null}let n=r();return l!==c||u!==R||!rj(n.snapshot)||n.snapshot?.currentSessionId!==s||n.snapshot.selectedSession?.path!==d||n.selectedPath!==d?null:t.sessionId!==s||t.status!==`ready`||t.revision!==f||n.snapshot?.runtime.plan!==`ready`||n.snapshot.runtime.planRevision!==f?(i(Error(In.t(`planModeUnconfirmed`))),null):{prompt:t.prompt,sessionId:s,sessionPath:d,planRevision:f}}finally{l===c&&u===R&&t({planSelectionPending:!1})}},async cancelActiveTurn(){let n=r().activeTurn??r().snapshot?.runtime.activeTurn;if(!n||!rj(r().snapshot)||r().turnCancellationPending||r().sessionSwitching)return;let a=c;t({turnCancellationPending:!0});try{await e.cancelActiveTurn(n)}catch(e){if(a!==c)return;await W.refreshSnapshot({epoch:a}),a===c&&i(e)}finally{a===c&&t({turnCancellationPending:!1})}},async sendPrompt(n,o=[],s,l,u){if(r().sessionForkPending||r().planSelectionPending)return!1;let d=n.trim();if(d.length>12e3)return t({notice:In.t(`promptTooLong`,{count:d.length,limit:Hd})}),!1;let f=o.map(({data:e,mimeType:t,name:n})=>({data:e,mimeType:t,...n===void 0?{}:{name:n}})),p=JSON.stringify(f.map(({data:e,mimeType:t,name:n})=>[t,n??``,e])),m=r();if(u&&(u.epoch!==c||!a(u)||m.workspaceDraft))return!1;let h=m.promptAdmissionRecovery,y=h?.phase===`submitting`?h:null,b=m.activeTurn??m.snapshot?.runtime.activeTurn;if(l?.streamingBehavior===`steer`&&!y&&(s||m.turnCancellationPending||!b||b.commandId!==l.expectedTurnCommandId||m.workspaceDraft))return t({notice:In.t(`steerStaleTurn`)}),!1;let x=m.selectedWorkspace;if(!x||!d&&f.length===0&&!l?.retryEntryId||m.sessionSwitching||m.promptAdmissionPending||h&&!y||m.promptAdmissionResolution||m.modelSelectionPending||m.thinkingPendingLevel!==null)return!1;let S=r().workspaceDraft||!r().snapshot?.selectedSession?.id;if(s&&S)return!1;let C=S?await W.createSession(x):null;if(S&&!C)return r().notice||t({notice:`The active Session changed before the first message was sent. Your message was not sent.`}),!1;if(S&&r().draftModel)return!1;let w=r().snapshot?.selectedSession,T=C??(w?{epoch:c,sessionId:w.id,sessionPath:w.path,workspacePath:x}:null);if(!T||r().workspaceDraft||!a(T)||r().sessionSwitching||r().promptAdmissionPending||y&&(r().promptAdmissionRecovery?.commandId!==y.commandId||r().promptAdmissionRecovery?.phase!==`submitting`))return!1;let{epoch:E,sessionId:D,sessionPath:O}=T;if(!O||s&&(s.sessionId!==D||s.sessionPath!==O||!s.planRevision))return!1;let k=r().draftModel;if(k&&!await U(k,E,D,O)||r().workspaceDraft||!a(T)||y&&(r().promptAdmissionRecovery?.commandId!==y.commandId||r().promptAdmissionRecovery?.phase!==`submitting`))return!1;let A=++g,j=v?.sessionId===D&&v.sessionPath===O&&v.content===d&&v.imageSignature===p&&v.planRevision===s?.planRevision&&(v.delivery?.streamingBehavior??`followUp`)===(l?.streamingBehavior??`followUp`)&&v.delivery?.expectedTurnCommandId===l?.expectedTurnCommandId&&v.delivery?.retryEntryId===l?.retryEntryId,M=j?v.commandId:globalThis.crypto?.randomUUID?.()??`web-prompt-${Date.now()}-${A}`,N=j?v.optimisticKey:`optimistic-${M}`,P=j?v.timestamp:new Date().toISOString(),F=j?v.afterEntryId:r().snapshot?.selectedSession?.history?.leafEntryId??r().snapshot?.selectedSession?.entries.at(-1)?.id??null;v={sessionId:D,sessionPath:O,content:d,imageSignature:p,images:f,commandId:M,optimisticKey:N,timestamp:P,afterEntryId:F,...s?{planRevision:s.planRevision}:{},...l?{delivery:l}:{}},_=A,t({liveMessages:j||l?.retryEntryId?r().liveMessages:MJ([...r().liveMessages,{key:N,timestamp:P,optimistic:{sessionId:D,sessionPath:O,commandId:M,afterEntryId:F,admitted:!1},message:{role:`user`,content:d,...f.length>0?{parts:f.map(e=>({type:`image`,mimeType:e.mimeType,...e.name?{name:e.name}:{},previewUrl:`data:${e.mimeType};base64,${e.data}`}))}:{}}}]),notice:null,pendingFollowUpsReceipt:null,pendingSteeringReceipt:null,turnTerminalStatus:null,promptAdmissionPending:!0,scrollToBottom:r().scrollToBottom+1});try{let n=l?await e.prompt(D,d,M,O,j,f,s?.planRevision,l):s?await e.prompt(D,d,M,O,j,f,s.planRevision):await e.prompt(D,d,M,O,j,f);if(E!==c||O!==r().selectedPath||D!==r().snapshot?.selectedSession?.id||_!==A)return!1;let i=ee.has(n.id);return v?.commandId===M&&(v=null),t({liveMessages:n.accepted&&n.id===M?HJ(r().liveMessages,D,O,M):r().liveMessages,...rj(r().snapshot)?ae(i,r().livePhase):{},pendingFollowUpsReceipt:rj(r().snapshot)?n.pendingFollowUps??null:null,pendingSteeringReceipt:rj(r().snapshot)?n.pendingSteering??null:null,...y&&r().promptAdmissionRecovery?.commandId===y.commandId?{promptAdmissionRecovery:null,...j?{promptAdmissionResolution:{sessionId:y.sessionId,sessionPath:y.sessionPath,commandId:y.commandId,content:y.content,images:y.images}}:{}}:{}}),oe(120),!0}catch(e){if(E!==c||O!==r().selectedPath||D!==r().snapshot?.selectedSession?.id||_!==A)return!1;let n=e instanceof tf&&[`PLAN_BUSY`,`PLAN_CONFLICT`,`PLAN_CONTROL_UNAVAILABLE`].includes(e.code??``),a=n||e instanceof tf&&[`WORKSPACE_REQUIRED`,`SESSION_CONFLICT`,`TURN_CONFLICT`,`PROMPT_REJECTED`,`COMMAND_CONFLICT`,`PROMPT_ADMISSION_CAPACITY`,`INVALID_PROMPT`,`INVALID_PROMPT_IMAGES`].includes(e.code??``),o=ee.has(M)||r().liveMessages.some(e=>e.optimistic?.sessionId===D&&e.optimistic.sessionPath===O&&e.optimistic.commandId===M&&e.optimistic.admitted)||r().activeTurn?.sessionId===D&&r().activeTurn?.commandId===M;if(!a&&o)return v?.commandId===M&&(v=null),y&&r().promptAdmissionRecovery?.commandId===y.commandId&&t({promptAdmissionRecovery:null,...j?{promptAdmissionResolution:{sessionId:y.sessionId,sessionPath:y.sessionPath,commandId:y.commandId,content:y.content,images:y.images}}:{}}),!0;if(!a&&v?.commandId===M){let n=v;v=null,t({notice:null,promptAdmissionPending:!1,promptAdmissionRecovery:{...n,retryable:!(e instanceof tf)||e.code!==`COMMAND_ADMISSION_UNKNOWN`,phase:`checking`}});let i=await W.refreshSnapshot({resetCursor:!0,epoch:E}),a=r().promptAdmissionRecovery;if(a?.commandId===M){if(r().activeTurn?.sessionId===D&&r().activeTurn?.commandId===M&&r().selectedPath===O&&r().snapshot?.selectedSession?.path===O&&rj(r().snapshot))return t({promptAdmissionRecovery:null,promptAdmissionResolution:{sessionId:a.sessionId,sessionPath:a.sessionPath,commandId:a.commandId,content:a.content,images:a.images}}),!0;t({promptAdmissionRecovery:{...a,phase:i?`ready`:`verification-failed`}})}return!1}return a?(v?.commandId===M&&(v=null),t({liveMessages:r().liveMessages.filter(e=>e.key!==N),...j&&y&&e instanceof tf&&e.code===`PROMPT_REJECTED`?{promptAdmissionRecovery:null}:{}}),n&&(await W.refreshSnapshot({epoch:E}),E!==c||O!==r().selectedPath||_!==A)||i(e),!1):(i(e),!1)}finally{E===c&&_===A&&(_=null,t({promptAdmissionPending:!1}))}},async checkPromptAdmissionRecovery(){let e=r().promptAdmissionRecovery;if(!e||e.phase!==`verification-failed`)return;let n=c;t({notice:null,promptAdmissionRecovery:{...e,phase:`checking`}});let i=await W.refreshSnapshot({resetCursor:!0,epoch:n}),a=r().promptAdmissionRecovery;a?.commandId===e.commandId&&a.phase===`checking`&&t({promptAdmissionRecovery:{...a,phase:i?`ready`:`verification-failed`}})},async retryPromptAdmission(){let e=r().promptAdmissionRecovery;if(!e?.retryable||e.phase!==`ready`||e.sessionPath!==r().selectedPath||e.sessionPath!==r().snapshot?.selectedSession?.path||e.sessionId!==r().snapshot?.selectedSession?.id)return!1;let n=e.images??[];v={...e,images:n,imageSignature:JSON.stringify(n.map(({data:e,mimeType:t,name:n})=>[t,n??``,e])),afterEntryId:e.afterEntryId??null,timestamp:e.timestamp??new Date().toISOString()},t({promptAdmissionRecovery:{...e,phase:`submitting`},notice:null});try{return await W.sendPrompt(e.content,n,e.planRevision?{sessionId:e.sessionId,sessionPath:e.sessionPath,planRevision:e.planRevision}:void 0,e.delivery)}finally{let n=r().promptAdmissionRecovery;n?.commandId===e.commandId&&n.phase===`submitting`&&t({promptAdmissionRecovery:{...n,phase:`ready`}})}},async sendPromptAsNew(e,n,i,a,o){let s=r().promptAdmissionRecovery;if(!s||s.phase!==`ready`||s.sessionPath!==r().selectedPath||s.sessionPath!==r().snapshot?.selectedSession?.path||s.sessionId!==r().snapshot?.selectedSession?.id)return!1;let c=e.trim(),l=n??s.images??[];if(!c&&l.length===0)return!1;v=null,t({promptAdmissionRecovery:{...s,phase:`submitting`},notice:null});let u=!1;try{let e=s.planRevision?{sessionId:s.sessionId,sessionPath:s.sessionPath,planRevision:s.planRevision}:i;return u=e?await W.sendPrompt(c,l,e,void 0,o):await W.sendPrompt(c,l,void 0,void 0,o),u}finally{let e=r().promptAdmissionRecovery;e?.commandId===s.commandId&&e.phase===`submitting`&&t({promptAdmissionRecovery:u?null:{...e,phase:`ready`}})}},abandonPromptAdmission(){let e=r().promptAdmissionRecovery;!e||e.phase===`submitting`||(v?.commandId===e.commandId&&(v=null),t({liveMessages:r().liveMessages.filter(t=>t.key!==e.optimisticKey),notice:null,promptAdmissionRecovery:null}))},acknowledgePromptAdmissionResolution(e){r().promptAdmissionResolution?.commandId===e&&t({promptAdmissionResolution:null})},async discoverCommands(){let n=r(),i=n.snapshot?.selectedSession?.id;if(n.workspaceDraft||!i||!rj(n.snapshot)||i!==n.snapshot?.currentSessionId||n.selectedPath!==n.snapshot?.selectedSession?.path||n.sessionSwitching){B();return}if(n.commandDiscovery.sessionId===i&&(n.commandDiscovery.status===`loading`||n.commandDiscovery.status===`ready`))return;let a=c,o=++L;I?.abort();let s=new AbortController;I=s,t({commandDiscovery:{sessionId:i,status:`loading`,commands:[],totalAvailable:0,commandsOmitted:0,error:null}});try{let n=await e.commands(i,s.signal);if(s.signal.aborted||a!==c||o!==L||i!==r().snapshot?.currentSessionId)return;t({commandDiscovery:{sessionId:i,status:`ready`,commands:n.commands,totalAvailable:n.totalAvailable,commandsOmitted:n.truncation.commandsOmitted,error:null}})}catch(e){if(s.signal.aborted||a!==c||o!==L)return;t({commandDiscovery:{sessionId:i,status:`error`,commands:[],totalAvailable:0,commandsOmitted:0,error:e instanceof Error?e.message:String(e)}})}finally{I===s&&(I=null)}},clearCommandDiscovery:B,setQuery(e){t({query:e})},setSearchOpen(e){t({searchOpen:e,...e?{}:{query:``}})},toggleWorkspace(e){let n=new Set(r().collapsed);n.has(e)?n.delete(e):n.add(e),jJ(EJ,[...n]),t({collapsed:n})},toggleSidebar(e){if(e){t({mobileSidebarOpen:!r().mobileSidebarOpen});return}let n=!r().sidebarCollapsed;try{window.sessionStorage.setItem(DJ,String(n))}catch{}t({sidebarCollapsed:n})},closeMobileSidebar(){t({mobileSidebarOpen:!1})},clearNotice(){t({notice:null})}};return{planSelectionPending:!1,activeTurn:null,turnCancellationPending:!1,turnTerminalStatus:null,pendingFollowUpsReceipt:null,pendingSteeringReceipt:null,snapshot:null,historyAnchor:null,historyNavigation:null,sessionForkPending:!1,sessionForkCancellation:null,cursor:null,selectedPath:s?.path??null,selectedWorkspace:null,workspaceDraft:o&&!s,draftModel:null,createdSession:null,modelSelectionPending:!1,modelSearch:{query:``,status:`idle`,models:[],totalMatches:0,matchesOmitted:0,error:null},collapsed:kJ(EJ),sidebarCollapsed:AJ(DJ),mobileSidebarOpen:!1,query:``,searchOpen:!1,connection:`connecting`,archiveNotices:[],notice:o&&!s?In.t(`sessionLinkUnavailable`):null,liveMessages:[],liveRunning:!1,livePhase:`idle`,liveRetry:null,thinkingStarts:{},thinkingDurations:{},promptAdmissionPending:!1,promptAdmissionRecovery:null,promptAdmissionResolution:null,restoredPromptDraft:null,sessionSwitching:!1,scrollToBottom:0,thinkingPendingLevel:null,commandDiscovery:ie(),actions:W}})}var KJ=GJ(),qJ=340,JJ=220,YJ=520,XJ=190,ZJ=520,QJ=360,$J=720,eY=320,tY=440,nY=1100;function rY(e,t,n){return Math.min(n,Math.max(t,e))}function iY(){JR();let e=pr(KJ),{t}=cr(),{actions:n}=e,r=(0,_.useRef)(null),i=(0,_.useRef)(null),a=(0,_.useRef)(!1),o=(0,_.useRef)(null),s=(0,_.useRef)(null),c=(0,_.useRef)(null),l=(0,_.useRef)(null),u=(0,_.useRef)(void 0),d=(0,_.useCallback)(e=>{u.current=e},[]),f=(0,_.useMemo)(gL,[]),p=(0,_.useRef)(new Set),[,m]=(0,_.useState)(0),[h,g]=(0,_.useState)(null),v=(0,_.useMemo)(()=>new Map,[]),[y,b]=(0,_.useState)(!1),[x,S]=(0,_.useState)(),[C,w]=(0,_.useState)(!1),[T,E]=(0,_.useState)(!1),[D,O]=(0,_.useState)(()=>window.innerWidth),[k,A]=(0,_.useState)({sidebar:qJ,auxiliary:ZJ}),[j,M]=(0,_.useState)(!1),N=!!e.snapshot,P=e.snapshot?.preferences.sidebarWidth,F=e.snapshot?.preferences.auxiliaryWidth;(0,_.useEffect)(()=>{!N||j||C||A({sidebar:P??qJ,auxiliary:F??ZJ})},[P,F,N,j,C]),(0,_.useEffect)(()=>{if(!j||C)return;let e=window.setTimeout(()=>{n.savePreferences({sidebarWidth:k.sidebar,auxiliaryWidth:k.auxiliary}).catch(()=>void 0)},200);return()=>window.clearTimeout(e)},[n,k,j,C]);let I=(e,t)=>{M(!0),A(n=>({...n,[e]:t}))},[L,R]=(0,_.useState)(()=>window.matchMedia?.(`(max-width: 760px)`).matches??!1),ee=L&&e.mobileSidebarOpen;(0,_.useEffect)(()=>{let e=window.matchMedia?.(`(max-width: 760px)`);if(!e)return;let t=()=>{R(e.matches),e.matches||n.closeMobileSidebar()};return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[n]),(0,_.useEffect)(()=>{let e=()=>O(window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let[z,B]=(0,_.useState)(`chat`),[V,H]=(0,_.useState)(null),[te,ne]=(0,_.useState)(null),[re,ie]=(0,_.useState)(uJ);(0,_.useEffect)(()=>{let e=()=>dJ(re);e(),window.addEventListener(`pagehide`,e);let t=()=>{document.visibilityState===`hidden`&&e()};return document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`pagehide`,e),document.removeEventListener(`visibilitychange`,t),e()}},[re]);let ae=e.workspaceDraft?void 0:e.snapshot?.selectedSession,U=re.find(e=>e.sessionId===ae?.id&&e.sessionPath===ae?.path),oe=U?.open??!1,se=U?.reviewTurn,ce=(0,_.useCallback)(e=>{let t=KJ.getState().snapshot?.selectedSession;t&&ie(n=>n.map(n=>n.sessionId===t.id&&n.sessionPath===t.path?e(n):n))},[]),le=(0,_.useCallback)(e=>ce(t=>({...t,open:e})),[ce]),ue=e=>ce(t=>({...t,reviewTurn:e??void 0})),[de,fe]=(0,_.useState)(null),[pe,me]=(0,_.useState)(ZI),W=(0,_.useCallback)((e,t)=>{let n=KJ.getState(),r=n.snapshot?.selectedSession;n.workspaceDraft||n.sessionSwitching||!r||!r.id||(a.current||(i.current=document.activeElement instanceof HTMLElement?document.activeElement:null),a.current=!0,c.current=null,le(!1),me(n=>({sessionId:r.id,sessionPath:r.path,id:e,kind:t,navigation:(n?.navigation??0)+1})))},[le]),he=pe&&!e.workspaceDraft&&!e.sessionSwitching&&pe.sessionId===e.snapshot?.selectedSession?.id&&pe.sessionPath===e.snapshot?.selectedSession?.path;(0,_.useEffect)(()=>{e.snapshot&&!e.sessionSwitching&&pe&&!he&&me(null)},[e.snapshot,e.sessionSwitching,pe,he]),(0,_.useEffect)(()=>QI(pe),[pe]),(0,_.useEffect)(()=>{if(he||!a.current)return;a.current=!1;let e=i.current;i.current=null,queueMicrotask(()=>{e?.isConnected&&e.checkVisibility()&&e.focus()})},[he]);let ge=e.snapshot?.models.find(e=>e.current),_e=JSON.stringify([ge?.provider,ge?.id]),ve=t=>{let n=e.snapshot,r=n?.selectedSession;e.workspaceDraft||!n||!r||e.sessionSwitching||!rj(n,r)||(c.current=null,le(!1),H({sessionId:r.id,sessionPath:r.path,cwd:r.cwd,model:ge?.label??``,modelKey:_e,terminalId:t}))},ye=V&&!e.workspaceDraft&&!e.sessionSwitching&&rj(e.snapshot,{id:V.sessionId,path:V.sessionPath})&&V.sessionPath===e.snapshot?.selectedSession?.path&&V.modelKey===_e;(0,_.useEffect)(()=>{V&&!ye&&H(null)},[V,ye]);let be=(0,_.useCallback)(()=>{H(null);let e=o.current;o.current=null,e&&requestAnimationFrame(()=>{e.isConnected&&e.checkVisibility()&&e.focus()})},[]),xe=te&&!e.workspaceDraft&&!e.sessionSwitching&&rj(e.snapshot,{id:te.sessionId,path:te.sessionPath})&&te.sessionPath===e.snapshot?.selectedSession?.path;(0,_.useEffect)(()=>{te&&!xe&&ne(null)},[te,xe]);let Se=async(e=`general`)=>{s.current=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=await n.prepareSession();if(!t)return;let r=KJ.getState(),i=r.snapshot,a=i?.selectedSession;r.workspaceDraft||!a||r.sessionSwitching||!rj(i,a)||a.id!==t.sessionId||a.path!==t.sessionPath||(n.closeMobileSidebar(),H(null),me(null),c.current=null,le(!1),ne({sessionId:a.id,sessionPath:a.path,cwd:a.cwd,entry:e}))},Ce=(0,_.useCallback)(()=>{ne(null);let e=new URL(window.location.href);e.searchParams.delete(`settings`),window.history.replaceState(window.history.state,``,e),requestAnimationFrame(()=>{let e=s.current;s.current=null,e?.isConnected&&e.checkVisibility()?e.focus():document.querySelector(`[data-provider-settings-trigger]`)?.focus()})},[]),we=()=>{o.current=s.current??document.querySelector(`[data-provider-settings-trigger]`),ne(null),ve()},Te=async e=>{if(await n.sendPrompt(`/openpi-setup ${e}`))return!0;let r=KJ.getState();throw Error((typeof r.notice==`string`?r.notice:null)||t(r.promptAdmissionRecovery?`setupResolveAdmission`:r.liveRunning||r.activeTurn?`settingsSetupBusyHint`:`setupRequestFailed`))};(0,_.useEffect)(()=>(n.start(),n.stop),[n]);let G=e.workspaceDraft?void 0:e.snapshot?.selectedSession,Ee=_L(G),De=G?.id,Oe=G?.path,ke=!!(G&&!p.current.has(Ee)&&f.get(Ee)?.position?.key&&f.get(Ee)?.position?.pinned===!1);(0,_.useEffect)(()=>{let t=KJ.getState(),n=t.workspaceDraft?void 0:t.snapshot?.selectedSession;if(!n||n.id!==De||n.path!==Oe||e.sessionSwitching||p.current.has(Ee))return;let r=f.get(Ee)?.position,i=()=>{p.current.add(Ee),m(e=>e+1)};if(!r?.key||r.pinned||f.get(Ee)?.window||e.historyNavigation?.sessionId===n.id&&e.historyNavigation.sessionPath===n.path){i();return}let a={sessionId:n.id,sessionPath:n.path,entryId:r.entryId??r.key},o=new AbortController,s,c=e=>{let t=e.target;!(t instanceof Element)||!t.closest(`.conversation, .turn-rail, .jump-to-latest`)||e instanceof KeyboardEvent&&![`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `].includes(e.key)||(o.abort(),i(),g(e=>e?.sessionId===a.sessionId&&e.sessionPath===a.sessionPath?null:e))};for(let e of[`wheel`,`touchstart`,`pointerdown`,`keydown`])document.addEventListener(e,c,!0);let l=e=>{let t=KJ.getState();o.signal.aborted||p.current.has(Ee)||t.historyNavigation||t.sessionSwitching||t.workspaceDraft||t.selectedPath!==a.sessionPath||t.snapshot?.selectedSession?.id!==a.sessionId||t.snapshot.selectedSession.path!==a.sessionPath||f.get(Ee)?.position!==r||e.id!==a.sessionId||e.path!==a.sessionPath||e.history?.anchorEntryId!==a.entryId||e.history.anchorOnBranch!==!0||!e.entries.some(e=>e.id===a.entryId)||(g({...a,session:e,restorePosition:r,revision:-1}),i())};if(e.connection===`connected`)if(n.entries.some(e=>e.id===a.entryId))l({...n,history:{leafEntryId:n.history?.leafEntryId??null,beforeEntryId:n.history?.beforeEntryId??null,anchorEntryId:a.entryId,anchorOnBranch:!0}});else{let e=t=>{new rf().sessionMessageWindow(a,o.signal).then(l,()=>{!o.signal.aborted&&t===0&&(s=window.setTimeout(()=>e(1),500))})};e(0)}return()=>{o.abort(),window.clearTimeout(s);for(let e of[`wheel`,`touchstart`,`pointerdown`,`keydown`])document.removeEventListener(e,c,!0)}},[De,Oe,e.connection,e.sessionSwitching,e.historyNavigation,Ee,f]);let Ae=rj(e.snapshot,G),je=(0,_.useMemo)(()=>aj((G?.entries??[]).flatMap(e=>e.message?[e.message]:[])),[G?.entries]),Me=Ae?e.snapshot?.runtime.capabilities.subagents:void 0,Ne=(0,_.useMemo)(()=>oj(Me?.items??[],je,Ae?e.snapshot?.runtime.capabilities.workflows?.items:void 0,e.connection===`connected`),[Me?.items,je,Ae,e.snapshot?.runtime.capabilities.workflows?.items,e.connection]),Pe=e.snapshot?.selectedExecution,Fe=Pe?.sessionId===G?.id&&Pe?.sessionPath===G?.path?Pe:void 0,Ie=Ae&&(e.liveRunning||!!e.activeTurn||e.snapshot?.runtime.status===`running`)||Fe?.status===`running`,Le=qN(G,e.snapshot?.cursor,{active:oe&&de===`review`,running:Ie,initialSource:U?.reading.review?.scope.startsWith(`workspace:`)?U.reading.review.source:`unstaged`,initialBaseRef:U?.reading.review?.baseRef}),Re=!!(U&&G&&e.selectedPath===G.path&&U.sessionId===G.id&&U.sessionPath===G.path),ze=oe&&Re&&!e.sessionSwitching;(0,_.useEffect)(()=>{G?.id,G?.path,c.current=null},[G?.id,G?.path]),(0,_.useEffect)(()=>{!U||e.sessionSwitching||ie(e=>e.at(-1)===U?e:[...e.filter(e=>e!==U),U])},[U,e.sessionSwitching]);let Be=(t=`launcher`)=>{!G||e.sessionSwitching||(y&&l.current?.close({restoreFocus:!1}),ze||(c.current=document.activeElement instanceof HTMLElement?document.activeElement:null),H(null),me(null),ie(e=>{let n=e.find(e=>e.sessionId===G.id&&e.sessionPath===G.path),r={sessionId:G.id,sessionPath:G.path,tool:t,requestRevision:(n?.requestRevision??0)+1,open:!0,reading:n?.reading??{},reviewTurn:t===`review`?void 0:n?.reviewTurn};return[...e.filter(e=>e!==n),r].slice(-32)}))},Ve=()=>{E(!1),le(!1);let e=c.current;c.current=null,requestAnimationFrame(()=>{e?.isConnected&&e.checkVisibility()&&e.focus()})},He=!e.sessionSwitching&&!e.workspaceDraft&&rj(e.snapshot,G)?G:void 0;ZR(He?.id,He?.path,async(e,t)=>{Be(`browser`);let n=Date.now()+5e3;for(;!u.current&&!t.aborted&&Date.now()setTimeout(e,40));return t.aborted?void 0:u.current?.(e)});let Ue=(0,_.useRef)(AI(new URLSearchParams(location.search).get(`settings`))),We=(0,_.useEffectEvent)(e=>{Se(e)});(0,_.useEffect)(()=>{if(!Ue.current||!e.snapshot||e.sessionSwitching)return;let t=Ue.current;Ue.current=void 0,We(t)},[e.snapshot,e.sessionSwitching]);let Ge=!!(he||ze||y);(0,_.useEffect)(()=>{(!Ge||D<=nY)&&E(!1)},[Ge,D]);let qe=Math.max(JJ,Math.min(YJ,D-tY-(Ge&&!T?k.auxiliary:0))),Je=rY(k.sidebar,JJ,qe),Ye=Math.max(QJ,Math.min($J,D-(e.sidebarCollapsed?56:Je)-tY)),Xe=rY(k.auxiliary,QJ,Ye),Ze={"--sidebar-width":`${Je}px`,"--auxiliary-width":`${Xe}px`},Qe=()=>{y?l.current?.close():ze?Ve():he&&me(null)},$e=!e.snapshot,et=e.sessionSwitching?e.snapshot?.sessions.find(t=>t.path===e.selectedPath)?.cwd:e.workspaceDraft?e.selectedWorkspace:G?.cwd??e.selectedWorkspace,rt=e.snapshot?.workspaces.find(e=>e.path===et),at=e.snapshot?.sessions.find(e=>e.path===G?.path&&e.id===G?.id),ot=e.sessionSwitching?e.snapshot?.sessions.find(t=>t.path===e.selectedPath):void 0,st=e.sessionSwitching?ot?ZA(ot,t(`untitledSession`)):t(`switchingSession`):G?ZA(at??{},t(`untitledSession`)):e.selectedWorkspace?t(`newSession`):`OpenPI`,ct=!!G?.rerun||G?.entries.some(e=>e.type===`message`&&e.message||e.type===`compaction`)||!!G?.history?.beforeEntryId||e.liveMessages.length>0,lt=!$e&&!e.sessionSwitching&&(!G||!ct&&!(e.snapshot?.selectedExecution?.sessionId===G.id&&e.snapshot.selectedExecution?.sessionPath===G.path&&e.snapshot.selectedExecution.compaction)),ut=(0,_.useCallback)((e,t)=>t?n.sendPrompt(``,[],void 0,{streamingBehavior:`followUp`,retryEntryId:t}):n.sendPrompt(e),[n]);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{inert:xe?!0:void 0,"aria-hidden":xe?!0:void 0,className:`app-shell ${e.sidebarCollapsed?`sidebar-collapsed`:``} ${e.mobileSidebarOpen?`sidebar-open`:``} ${he?`with-subagent-panel`:``} ${ze?`with-workbar-panel`:``} ${y?`with-artifact-panel`:``} ${T?`center-collapsed`:``} ${C?`is-resizing`:``} ${$e?`shell-loading`:``}`,style:Ze,children:(0,K.jsxs)(Bk,{ref:l,sessionId:G?.id,sessionPath:G?.path,disabled:!!(e.workspaceDraft||e.sessionSwitching||he||xe),onOpen:()=>{b(!0),me(null),le(!1),H(null)},onClose:()=>{b(!1)},children:[(0,K.jsx)(dP,{sessionViewVisible:z===`chat`&&!T&&!xe&&!e.sessionSwitching&&!e.workspaceDraft,connected:e.connection===`connected`,snapshot:e.snapshot,selectedPath:e.workspaceDraft?null:e.selectedPath,selectedWorkspace:e.selectedWorkspace,collapsed:e.collapsed,query:e.query,searchOpen:e.searchOpen,mobileOpen:ee,settingsDisabled:!!(e.sessionSwitching||e.modelSelectionPending||!e.snapshot),returnFocusRef:r,onOpenSettings:()=>void Se(`general`),actions:n}),e.sidebarCollapsed&&(0,K.jsx)(`button`,{className:`sidebar-expand`,type:`button`,"aria-label":t(`expandSidebar`),title:t(`expandSidebar`),onClick:()=>n.toggleSidebar(!1),children:(0,K.jsx)(nt,{})}),(0,K.jsxs)(`main`,{inert:ee,className:`conversation-shell ${G?`has-view`:``} ${lt&&(!G||z===`chat`)?`landing`:``}`,children:[(0,K.jsxs)(`header`,{className:`task-header`,children:[(0,K.jsx)(`button`,{className:`task-header-menu sidebar-shell-toggle`,ref:r,type:`button`,"aria-label":t(L?`openSidebar`:e.sidebarCollapsed?`expandSidebar`:`collapseSidebar`),"aria-controls":`session-sidebar`,"aria-expanded":L?ee:!e.sidebarCollapsed,onClick:()=>n.toggleSidebar(L),children:L?(0,K.jsx)(Ke,{}):(0,K.jsx)(tt,{})}),(0,K.jsxs)(`div`,{className:`task-identity`,children:[et&&(0,K.jsxs)(`span`,{className:`task-workspace`,title:et,children:[rt?.name||QA(et),(0,K.jsxs)(`span`,{className:`sr-only`,children:[` `,et]})]}),(0,K.jsx)(`h1`,{title:st,children:st})]}),(0,K.jsx)(QR,{usage:G&&!e.sessionSwitching?e.snapshot?.usage:void 0,workspace:rt?.name||G&&QA(G.cwd),sessionId:G?.id},G?`usage:${G.id}:${G.path}`:`usage:no-session`),G&&!e.sessionSwitching&&(0,K.jsx)(LI,{sessionId:G.id,workspace:rt?.name||QA(G.cwd),agents:Ne,omitted:(Me?.omitted??0)+(Ae?(e.snapshot?.runtime.capabilities.workflows?.items??[]).reduce((e,t)=>e+(t.children?.omitted??0),0):0),review:Le.result,reviewLoading:Le.loading,reviewError:Le.error,sessionPath:G.path,revision:G.history?.leafEntryId??void 0,onAddSources:Ae?()=>S(e=>({sessionId:G.id,path:G.path,revision:(e?.revision??0)+1})):void 0,onSubagents:()=>W(),onReview:()=>Be(`review`)},`overview:${G.id}:${G.path}`),(0,K.jsx)(`button`,{type:`button`,className:`task-tools-trigger`,"aria-label":t(`openTools`),title:t(`openTools`),disabled:!G||e.sessionSwitching,onClick:e=>{y&&l.current?.close({restoreFocus:!1}),c.current=e.currentTarget,Re&&!ze?le(!0):Be(`launcher`)},children:(0,K.jsx)(it,{"aria-hidden":`true`})}),(0,K.jsx)(`span`,{className:`connection-state ${e.connection}`,children:t(e.connection)})]}),G&&!e.sessionSwitching&&(0,K.jsx)(`div`,{className:`conversation-view-row`,children:(0,K.jsxs)(`fieldset`,{className:`conversation-view-switch`,"aria-label":t(`conversationView`),children:[(0,K.jsx)(`button`,{type:`button`,"aria-pressed":z===`chat`,onClick:()=>B(`chat`),children:t(`chatView`)}),(0,K.jsx)(`button`,{type:`button`,"aria-pressed":z===`trajectory`,onClick:()=>B(`trajectory`),children:t(`trajectory`)})]})}),$e?(0,K.jsxs)(`section`,{className:`shell-state`,role:`status`,"aria-live":`polite`,children:[(0,K.jsx)(hr,{compact:!0}),(0,K.jsx)(`p`,{children:t(e.connection===`unavailable`?`unavailable`:`connecting`)}),e.connection===`unavailable`&&(0,K.jsxs)(`button`,{type:`button`,onClick:()=>void n.refreshSnapshot({resetCursor:!0}),children:[(0,K.jsx)(dt,{"aria-hidden":`true`}),` `,t(`retryAdmissionCheck`)]})]}):e.sessionSwitching?(0,K.jsx)(`div`,{className:`conversation switching`,role:`status`,children:(0,K.jsxs)(`div`,{className:`conversation-running`,children:[(0,K.jsx)(`span`,{className:`conversation-running-dot`}),(0,K.jsx)(`span`,{children:t(`switchingSession`)})]})}):z===`trajectory`&&G&&e.snapshot?(0,K.jsx)(mL,{snapshot:e.snapshot,running:Ie},G.path):lt?(0,K.jsx)(`section`,{className:`conversation landing-conversation`,"aria-label":`Conversation`,children:(0,K.jsxs)(`div`,{className:`landing-welcome`,children:[(0,K.jsx)(hr,{animated:!0}),(0,K.jsx)(`p`,{className:`landing-tagline`,children:t(`landingTagline`)})]})}):e.snapshot?(0,K.jsx)(qR,{resultExposureEnabled:!T&&!xe&&!e.sessionSwitching&&!e.workspaceDraft&&z===`chat`,readingCache:f,readingRestorePending:ke,snapshot:e.snapshot,liveMessages:e.liveMessages,liveRunning:e.liveRunning,liveActiveTurn:e.activeTurn,livePhase:e.livePhase,activityObserved:e.connection===`connected`,liveRetry:e.liveRetry,thinkingStarts:e.thinkingStarts,thinkingDurations:e.thinkingDurations,scrollToBottom:e.scrollToBottom,onResend:ut,onEdit:n.editMessage,onRegenerate:n.regenerateMessage,onOpenOriginal:n.navigateToMessage,onFork:n.forkMessage,forkPending:e.sessionForkPending,forkAvailable:Ae&&!Ie&&e.snapshot.runtime.status===`idle`&&!e.promptAdmissionPending&&!e.promptAdmissionRecovery&&!e.activeTurn&&!e.modelSelectionPending&&!e.sessionSwitching&&!G?.path.startsWith(`current:`)&&!(Fe?.pendingFollowUps||Fe?.pendingSteering||Fe?.compaction?.state===`running`),onInspectSubagent:W,onReviewTurn:(e,t)=>{Be(`review`),c.current=document.activeElement instanceof HTMLElement?document.activeElement:null,ue({promptEntryId:e,filePath:t,revision:(se?.revision??0)+1})},onHistoryAnchorChange:n.setHistoryAnchor,historyNavigation:e.historyNavigation??(h?.sessionId===G?.id&&h?.sessionPath===G?.path?h:null),onNavigateToMessage:n.navigateToMessage,onRefreshHistory:n.refreshSnapshot,onPromptProjection:n.rememberPromptProjection},`transcript:${JSON.stringify([G?.id,G?.path])}`):null,!xe&&G&&e.snapshot&&!e.sessionSwitching&&rj(e.snapshot,G)&&(0,K.jsx)(KN,{sessionId:G.id,sessionPath:G.path,workingCache:v,revision:e.snapshot.cursor,connected:e.connection===`connected`},JSON.stringify([G.id,G.path])),e.snapshot&&(0,K.jsxs)(`div`,{className:`workbar-chat-context`,hidden:!ze,children:[(0,K.jsx)(`span`,{className:`workbar-chat-title`,title:st,children:st}),(0,K.jsx)(`span`,{className:`workbar-chat-status`,role:`status`,children:t(Ie?`turnState_running`:e.connection)}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>{Ve(),requestAnimationFrame(()=>document.querySelector(`.composer textarea`)?.focus({preventScroll:!0}))},children:t(`workbarContinueInChat`)})]}),e.snapshot&&(0,K.jsx)(RN,{addSourcesRequest:x,planSelectionPending:e.planSelectionPending,workspaceDraft:e.workspaceDraft,draftModel:e.draftModel,createdSession:e.createdSession,modelSelectionPending:e.modelSelectionPending,modelSearch:e.modelSearch,thinkingPendingLevel:e.thinkingPendingLevel,onInspect:ve,onOpenProviders:()=>void Se(`credentials`),onCommandAction:e=>{let t=KJ.getState();return t.sessionSwitching||t.workspaceDraft||!G||t.snapshot?.selectedSession?.path!==G.path||t.snapshot.selectedSession.id!==G.id?!1:(e===`terminal`||e===`review`||e===`side-conversation`?Be(e):e===`subagents`?W():ve(),!0)},onInspectSubagent:W,activeTurn:e.activeTurn,activityObserved:e.connection===`connected`,turnCancellationPending:e.turnCancellationPending,turnTerminalStatus:e.turnTerminalStatus,pendingFollowUpsReceipt:e.pendingFollowUpsReceipt,pendingSteeringReceipt:e.pendingSteeringReceipt,commandDiscovery:e.commandDiscovery,snapshot:e.snapshot,selectedPath:e.selectedPath,selectedWorkspace:G?.cwd??e.selectedWorkspace,sessionSwitching:e.sessionSwitching||e.sessionForkPending,promptAdmissionPending:e.promptAdmissionPending,promptAdmissionRecovery:e.promptAdmissionRecovery,promptAdmissionResolution:e.promptAdmissionResolution,restoredPromptDraft:e.restoredPromptDraft,liveRunning:e.liveRunning,landing:lt,actions:n}),e.sessionForkPending&&(0,K.jsxs)(`div`,{className:`session-fork-progress`,role:`status`,children:[(0,K.jsx)(`span`,{className:`session-fork-progress-spinner`,"aria-hidden":`true`}),t(e.sessionForkCancellation===`too-late`?`sidebarForkFinishing`:e.sessionForkCancellation?`sidebarForkCancelling`:e.sessionForkEnvironment===`worktree`?`sidebarForkWorktreePending`:`forkSessionPending`),e.sessionForkEnvironment&&(0,K.jsx)(`button`,{type:`button`,disabled:e.sessionForkCancellation!==null,onClick:()=>void n.cancelSessionFork(),children:t(`cancel`)})]}),(0,K.jsx)(YN,{notices:e.archiveNotices,actions:n}),e.notice&&(0,K.jsxs)(`div`,{className:typeof e.notice==`string`?`notice`:`notice notice-success`,role:typeof e.notice==`string`?`alert`:`status`,children:[(0,K.jsx)(`span`,{children:typeof e.notice==`string`?e.notice:e.notice.message}),(0,K.jsx)(`button`,{type:`button`,"aria-label":t(`close`),onClick:n.clearNotice,children:(0,K.jsx)(Lt,{})})]})]}),ye&&(0,K.jsx)(zN,{target:V,onClose:be,onOpenProviders:()=>void Se(`credentials`)},`${V.sessionId}:${V.sessionPath}:${V.terminalId??`status`}`),he&&(0,K.jsx)(YI,{sessionId:pe.sessionId,initialId:pe.id,initialKind:pe.kind,observed:e.connection===`connected`,activity:rj(e.snapshot,{id:pe.sessionId,path:pe.sessionPath})?e.snapshot?.runtime.capabilities.subagents:void 0,records:je,workflows:Ae?e.snapshot?.runtime.capabilities.workflows:void 0,liveAvailable:rj(e.snapshot,{id:pe.sessionId,path:pe.sessionPath}),onClose:()=>me(null)},`${pe.sessionId}:${pe.navigation}`),ze&&G&&U&&(0,K.jsx)($q,{visible:ze,requestedTool:U.tool,requestRevision:U.requestRevision,sessionId:G.id,sessionPath:G.path,onBrowserReady:d,canControl:!e.sessionSwitching&&rj(e.snapshot,G),onActivateSession:()=>void n.selectSession(G.path),cwd:G.cwd,snapshot:e.snapshot??void 0,capabilities:rj(e.snapshot,G)?e.snapshot?.runtime.capabilities??{}:{},readingState:U.reading,onActiveToolChange:fe,review:Le,reviewTurn:se??void 0,onWorkspaceReview:()=>ue(null),onReferenceLine:e=>{let t=KJ.getState(),n=t.snapshot?.selectedSession;t.workspaceDraft||t.sessionSwitching||t.selectedPath!==G.path||n?.id!==G.id||n.path!==G.path||!rj(t.snapshot,n)||(B(`chat`),S(t=>({sessionId:G.id,path:G.path,revision:(t?.revision??0)+1,feedback:e})))},conversationCollapsed:T,onRestoreConversation:()=>E(!1),onExpandReview:()=>E(!0),onClose:Ve},`${G.id}:${G.path}`),(0,K.jsxs)(`section`,{"aria-label":t(`resizePanes`),style:{display:`contents`},children:[!e.sidebarCollapsed&&!L&&(!Ge||D>nY)&&(0,K.jsx)(_r,{side:`left`,value:Je,min:JJ,max:qe,defaultValue:qJ,collapseThreshold:XJ,onCollapse:()=>n.toggleSidebar(!1),onChange:e=>I(`sidebar`,e),onDraggingChange:w}),Ge&&!T&&D>nY&&(0,K.jsx)(_r,{side:`right`,value:Xe,min:QJ,max:Ye,defaultValue:ZJ,collapseThreshold:eY,onCollapse:Qe,onExpandPastMax:ze?()=>E(!0):void 0,onChange:e=>I(`auxiliary`,e),onDraggingChange:w})]}),(0,K.jsx)(`button`,{className:`sidebar-scrim`,type:`button`,tabIndex:-1,"aria-hidden":`true`,"aria-label":t(`close`),onClick:n.closeMobileSidebar})]})}),xe&&(0,K.jsx)(jI,{sessionId:te.sessionId,cwd:te.cwd,entry:te.entry,models:e.snapshot?.models??[],currentModel:ge,thinkingLevel:e.thinkingPendingLevel??e.snapshot?.thinking?.level??t(`unknownState`),theme:e.snapshot?.preferences.theme??`system`,preferences:e.snapshot?.preferences,workspaces:e.snapshot?.workspaces??[],onRestoreSession:e=>n.unarchiveSession(e),plan:e.snapshot?.runtime.plan,planSelectionPending:e.planSelectionPending,onExitPlan:()=>n.selectPlanMode(!1),setupOutcome:e.snapshot?.runtime.setup,capabilities:e.snapshot?.runtime.capabilities,setupBusy:e.liveRunning||e.promptAdmissionPending||!!e.activeTurn||e.modelSelectionPending||e.thinkingPendingLevel!==null||e.sessionSwitching,setupBlockedReason:e.promptAdmissionRecovery?t(`setupResolveAdmission`):void 0,modelSelectionPending:e.modelSelectionPending,sessionPath:te.sessionPath,onSelectModel:e=>n.selectModel(e),onConfigureOpenPi:Te,interaction:e.snapshot&&!e.sessionSwitching&&te.sessionId===e.snapshot.currentSessionId?(0,K.jsxs)(`div`,{className:`settings-interaction`,children:[(0,K.jsx)(KN,{sessionId:te.sessionId,sessionPath:te.sessionPath,workingCache:v,revision:e.snapshot.cursor,connected:e.connection===`connected`},JSON.stringify([te.sessionId,te.sessionPath])),(e.activeTurn||e.liveRunning)&&(0,K.jsx)(`button`,{type:`button`,disabled:e.turnCancellationPending,onClick:()=>void n.cancelActiveTurn(),children:t(`stopTurn`)})]}):void 0,onPreferencesChanged:()=>n.refreshSnapshot(),onOpenRuntimeStatus:we,onClose:Ce},`${te.sessionId}:${te.sessionPath}`)]})}var aY={size:`1em`,"aria-hidden":!0},oY={name:`neutral`,__built:!0,tokens:{"--font-size-4xs":`0.375rem`,"--font-size-3xs":`0.4375rem`,"--font-size-2xs":`0.5rem`,"--font-size-xs":`0.625rem`,"--font-size-sm":`0.75rem`,"--font-size-base":`0.875rem`,"--font-size-lg":`1.0625rem`,"--font-size-xl":`1.25rem`,"--font-size-2xl":`1.5rem`,"--font-size-3xl":`1.8125rem`,"--font-size-4xl":`2.1875rem`,"--font-size-5xl":`2.625rem`,"--text-heading-1-size":`var(--font-size-2xl)`,"--text-heading-1-weight":`var(--font-weight-semibold)`,"--text-heading-1-leading":`1.3333`,"--text-heading-2-size":`var(--font-size-xl)`,"--text-heading-2-weight":`var(--font-weight-semibold)`,"--text-heading-2-leading":`1.4`,"--text-heading-3-size":`var(--font-size-lg)`,"--text-heading-3-weight":`var(--font-weight-bold)`,"--text-heading-3-leading":`1.4118`,"--text-heading-4-size":`var(--font-size-base)`,"--text-heading-4-weight":`var(--font-weight-bold)`,"--text-heading-4-leading":`1.4286`,"--text-heading-5-size":`var(--font-size-sm)`,"--text-heading-5-weight":`var(--font-weight-semibold)`,"--text-heading-5-leading":`1.6667`,"--text-heading-6-size":`var(--font-size-xs)`,"--text-heading-6-weight":`var(--font-weight-semibold)`,"--text-heading-6-leading":`1.6`,"--text-body-size":`var(--font-size-base)`,"--text-body-weight":`var(--font-weight-normal)`,"--text-body-leading":`1.4286`,"--text-large-size":`var(--font-size-lg)`,"--text-large-weight":`var(--font-weight-semibold)`,"--text-large-leading":`1.4118`,"--text-label-size":`var(--font-size-base)`,"--text-label-weight":`var(--font-weight-medium)`,"--text-label-leading":`1.4286`,"--text-code-size":`var(--font-size-base)`,"--text-code-weight":`var(--font-weight-normal)`,"--text-code-leading":`1.4286`,"--text-supporting-size":`var(--font-size-sm)`,"--text-supporting-weight":`var(--font-weight-normal)`,"--text-supporting-leading":`1.6667`,"--text-display-1-size":`var(--font-size-5xl)`,"--text-display-1-weight":`var(--font-weight-normal)`,"--text-display-1-leading":`1.2381`,"--text-display-2-size":`var(--font-size-4xl)`,"--text-display-2-weight":`var(--font-weight-normal)`,"--text-display-2-leading":`1.2571`,"--text-display-3-size":`var(--font-size-3xl)`,"--text-display-3-weight":`var(--font-weight-normal)`,"--text-display-3-leading":`1.3793`,"--duration-fast-min":`95ms`,"--duration-fast":`125ms`,"--duration-fast-max":`165ms`,"--duration-medium-min":`225ms`,"--duration-medium":`300ms`,"--duration-medium-max":`400ms`,"--duration-slow-min":`525ms`,"--duration-slow":`700ms`,"--duration-slow-max":`935ms`,"--font-family-body":`Figtree, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif`,"--font-family-heading":`Figtree, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif`,"--font-family-code":`ui-monospace, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace`,"--color-syntax-keyword":`light-dark(#700084, #efa8ff)`,"--color-syntax-string":`light-dark(#005600, #a6d2a2)`,"--color-syntax-comment":`light-dark(#737373, #a3a3a3)`,"--color-syntax-number":`light-dark(#6e3500, #ffb37f)`,"--color-syntax-function":`light-dark(#00458c, #a0caff)`,"--color-syntax-type":`light-dark(#700084, #efa8ff)`,"--color-syntax-variable":`light-dark(#171717, #e5e5e5)`,"--color-syntax-operator":`light-dark(#737373, #a3a3a3)`,"--color-syntax-constant":`light-dark(#6e3500, #ffb37f)`,"--color-syntax-tag":`light-dark(#89001a, #ffaeaa)`,"--color-syntax-attribute":`light-dark(#584400, #eec12f)`,"--color-syntax-property":`light-dark(#005348, #83dac9)`,"--color-syntax-punctuation":`light-dark(#6e6e6e, #a0a0a0)`,"--color-syntax-background":`light-dark(#fafafa, #0a0a0a)`,"--color-background-surface":`light-dark(#ffffff, #262626)`,"--color-background-body":`light-dark(#f1f1f1, #1b1b1b)`,"--color-background-card":`light-dark(#ffffff, #1b1b1b)`,"--color-background-popover":`light-dark(#ffffff, #1b1b1b)`,"--color-background-muted":`light-dark(#f1f1f1, #1b1b1b)`,"--color-accent":`light-dark(#262626, #ebebeb)`,"--color-accent-muted":`light-dark(#f1f1f1, #262626)`,"--color-neutral":`light-dark(#0000000F, #FFFFFF1A)`,"--color-overlay":`light-dark(#00000080, #000000CC)`,"--color-overlay-hover":`light-dark(#0000000D, #FFFFFF0D)`,"--color-overlay-pressed":`light-dark(#0000001A, #FFFFFF1A)`,"--color-text-primary":`light-dark(#171717, #fafafa)`,"--color-text-secondary":`light-dark(#525252, #a3a3a3)`,"--color-text-disabled":`light-dark(#a3a3a3, #525252)`,"--color-text-accent":`light-dark(#262626, #ebebeb)`,"--color-on-dark":`#ffffff`,"--color-on-light":`#171717`,"--color-on-accent":`light-dark(#ffffff, #171717)`,"--color-on-success":`light-dark(#ffffff, #171717)`,"--color-on-error":`light-dark(#ffffff, #171717)`,"--color-on-warning":`#171717`,"--color-icon-accent":`light-dark(#262626, #ebebeb)`,"--color-icon-primary":`light-dark(#171717, #fafafa)`,"--color-icon-secondary":`light-dark(#737373, #a3a3a3)`,"--color-icon-disabled":`light-dark(#a3a3a3, #525252)`,"--color-success":`light-dark(#007004, #9fe59b)`,"--color-error":`light-dark(#a50c25, #ffc6c1)`,"--color-warning":`light-dark(#745b00, #fdcf4f)`,"--color-success-muted":`light-dark(#c5e5c0, #84c9803D)`,"--color-error-muted":`light-dark(#facecb, #ff9e973D)`,"--color-warning-muted":`light-dark(#f8da9d, #deb4333D)`,"--color-border":`light-dark(#00000014, #FFFFFF1A)`,"--color-border-emphasized":`light-dark(#d4d4d4, #525252)`,"--color-skeleton":`light-dark(#ebebeb, #525252)`,"--color-shadow":`light-dark(#0000001A, #0000004D)`,"--color-tint-hover":`light-dark(black, white)`,"--color-background-red":`light-dark(#facecb, #ff9e973D)`,"--color-border-red":`light-dark(#e6bab8, #ff6f6c)`,"--color-icon-red":`light-dark(#89001a, #ff9e97)`,"--color-text-red":`light-dark(#89001a, #ffc6c1)`,"--color-background-orange":`light-dark(#fad0b5, #ffa2583D)`,"--color-border-orange":`light-dark(#e6bda2, #e2883e)`,"--color-icon-orange":`light-dark(#6e3500, #ffa258)`,"--color-text-orange":`light-dark(#6e3500, #ffc9a2)`,"--color-background-yellow":`light-dark(#f8da9d, #deb4333D)`,"--color-border-yellow":`light-dark(#e4c279, #c0990e)`,"--color-icon-yellow":`light-dark(#584400, #deb433)`,"--color-text-yellow":`light-dark(#584400, #fdcf4f)`,"--color-background-green":`light-dark(#c5e5c0, #84c9803D)`,"--color-border-green":`light-dark(#b2d1ac, #69ad67)`,"--color-icon-green":`light-dark(#0c5700, #84c980)`,"--color-text-green":`light-dark(#0c5700, #9fe59b)`,"--color-background-teal":`light-dark(#a5e3d6, #7ec6b83D)`,"--color-border-teal":`light-dark(#94d6c8, #63ab9d)`,"--color-icon-teal":`light-dark(#005348, #7ec6b8)`,"--color-text-teal":`light-dark(#005348, #99e2d3)`,"--color-background-cyan":`light-dark(#a3e0ef, #83c2d43D)`,"--color-border-cyan":`light-dark(#91d3e3, #67a7b8)`,"--color-icon-cyan":`light-dark(#00505f, #83c2d4)`,"--color-text-cyan":`light-dark(#00505f, #9edef0)`,"--color-background-blue":`light-dark(#c4ddfb, #9eb7ff3D)`,"--color-border-blue":`light-dark(#b1c9e7, #6d9cfe)`,"--color-icon-blue":`light-dark(#00458c, #9eb7ff)`,"--color-text-blue":`light-dark(#00458c, #c7d3ff)`,"--color-background-purple":`light-dark(#eccef3, #f297ff3D)`,"--color-border-purple":`light-dark(#d8bbdf, #dd74f0)`,"--color-icon-purple":`light-dark(#700084, #f297ff)`,"--color-text-purple":`light-dark(#700084, #fac1ff)`,"--color-background-pink":`light-dark(#fccadc, #ff99c33D)`,"--color-border-pink":`light-dark(#e7b7c8, #f273aa)`,"--color-icon-pink":`light-dark(#83004b, #ff99c3)`,"--color-text-pink":`light-dark(#83004b, #ffc3da)`,"--color-background-gray":`light-dark(#e5e5e5, var(--color-neutral))`,"--color-border-gray":`light-dark(#d4d4d4, #262626)`,"--color-icon-gray":`light-dark(#525252, #a3a3a3)`,"--color-text-gray":`light-dark(#262626, #e5e5e5)`,"--radius-none":`0px`,"--radius-inner":`0.375rem`,"--radius-element":`0.625rem`,"--radius-container":`0.75rem`,"--radius-page":`1.75rem`,"--radius-full":`9999px`,"--shadow-low":`0 2px 4px light-dark(oklch(0 0 0 / 5%), oklch(0 0 0 / 25%)), 0 4px 8px light-dark(oklch(0 0 0 / 10%), oklch(0 0 0 / 40%)), inset 0 0 0 1px light-dark(transparent, oklch(1 0 0 / 8%))`,"--shadow-med":`0 2px 4px light-dark(oklch(0 0 0 / 5%), oklch(0 0 0 / 35%)), 0 4px 12px light-dark(oklch(0 0 0 / 10%), oklch(0 0 0 / 50%)), inset 0 0 0 1px light-dark(transparent, oklch(1 0 0 / 12%))`,"--shadow-high":`0 4px 6px light-dark(oklch(0 0 0 / 10%), oklch(0 0 0 / 50%)), 0 12px 24px light-dark(oklch(0 0 0 / 15%), oklch(0 0 0 / 70%)), inset 0 0 0 1px light-dark(transparent, oklch(1 0 0 / 15%))`,"--shadow-inset-hover":`inset 0px 0px 0px 2px #0074e24D`,"--shadow-inset-selected":`inset 0px 0px 0px 2px #0074e280`,"--shadow-inset-success":`inset 0px 0px 0px 2px #1981004D`,"--shadow-inset-warning":`inset 0px 0px 0px 2px #ffce2f4D`,"--shadow-inset-error":`inset 0px 0px 0px 2px #e33f4a4D`},components:{heading:{"level:1":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-heading-1-size)`,fontWeight:`var(--text-heading-1-weight)`,lineHeight:`var(--text-heading-1-leading)`},"level:2":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-heading-2-size)`,fontWeight:`var(--text-heading-2-weight)`,lineHeight:`var(--text-heading-2-leading)`},"level:3":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-heading-3-size)`,fontWeight:`var(--text-heading-3-weight)`,lineHeight:`var(--text-heading-3-leading)`},"level:4":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-heading-4-size)`,fontWeight:`var(--text-heading-4-weight)`,lineHeight:`var(--text-heading-4-leading)`},"level:5":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-heading-5-size)`,fontWeight:`var(--text-heading-5-weight)`,lineHeight:`var(--text-heading-5-leading)`},"level:6":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-heading-6-size)`,fontWeight:`var(--text-heading-6-weight)`,lineHeight:`var(--text-heading-6-leading)`},"type:display-1":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-display-1-size)`,lineHeight:`var(--text-display-1-leading)`},"type:display-2":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-display-2-size)`,lineHeight:`var(--text-display-2-leading)`},"type:display-3":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-display-3-size)`,lineHeight:`var(--text-display-3-leading)`}},text:{"type:body":{fontFamily:`var(--font-family-body)`,fontSize:`var(--text-body-size)`,lineHeight:`var(--text-body-leading)`},"type:large":{fontFamily:`var(--font-family-body)`,fontSize:`var(--text-large-size)`,lineHeight:`var(--text-large-leading)`},"type:label":{fontFamily:`var(--font-family-body)`,fontSize:`var(--text-label-size)`,lineHeight:`var(--text-label-leading)`},"type:code":{fontFamily:`var(--font-family-code)`,fontSize:`var(--text-code-size)`,lineHeight:`var(--text-code-leading)`},"type:supporting":{fontFamily:`var(--font-family-body)`,fontSize:`var(--text-supporting-size)`,lineHeight:`var(--text-supporting-leading)`},"type:display-1":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-display-1-size)`,lineHeight:`var(--text-display-1-leading)`},"type:display-2":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-display-2-size)`,lineHeight:`var(--text-display-2-leading)`},"type:display-3":{fontFamily:`var(--font-family-heading)`,fontSize:`var(--text-display-3-size)`,lineHeight:`var(--text-display-3-leading)`}},button:{"variant:destructive":{backgroundColor:`var(--color-error-muted)`,color:`var(--color-error)`}},badge:{"variant:info":{backgroundColor:`light-dark(#0074e2, #6d9cfe)`,color:`light-dark(#ffffff, #171717)`},"variant:neutral":{backgroundColor:`var(--color-background-gray)`,color:`var(--color-text-gray)`},"variant:success":{backgroundColor:`light-dark(#198100, #64af4c)`,color:`light-dark(#ffffff, #171717)`},"variant:warning":{backgroundColor:`#ffce2f`,color:`#171717`},"variant:error":{backgroundColor:`light-dark(#c9303a, #ff705d)`,color:`light-dark(#ffffff, #171717)`},"variant:red":{backgroundColor:`var(--color-background-red)`,color:`var(--color-text-red)`},"variant:orange":{backgroundColor:`var(--color-background-orange)`,color:`var(--color-text-orange)`},"variant:yellow":{backgroundColor:`var(--color-background-yellow)`,color:`var(--color-text-yellow)`},"variant:green":{backgroundColor:`var(--color-background-green)`,color:`var(--color-text-green)`},"variant:teal":{backgroundColor:`var(--color-background-teal)`,color:`var(--color-text-teal)`},"variant:cyan":{backgroundColor:`var(--color-background-cyan)`,color:`var(--color-text-cyan)`},"variant:blue":{backgroundColor:`var(--color-background-blue)`,color:`var(--color-text-blue)`},"variant:purple":{backgroundColor:`var(--color-background-purple)`,color:`var(--color-text-purple)`},"variant:pink":{backgroundColor:`var(--color-background-pink)`,color:`var(--color-text-pink)`},"variant:gray":{backgroundColor:`var(--color-background-gray)`,color:`var(--color-text-gray)`}},statusdot:{"variant:success":{backgroundColor:`light-dark(#198100, #64af4c)`},"variant:warning":{backgroundColor:`#ffce2f`},"variant:error":{backgroundColor:`light-dark(#c9303a, #ff705d)`},"variant:accent":{backgroundColor:`light-dark(#0074e2, #6d9cfe)`}},banner:{"status:info":{"--color-accent-muted":`var(--color-background-blue)`,"--color-text-primary":`var(--color-text-blue)`,"--color-text-secondary":`var(--color-text-blue)`,"--color-accent":`var(--color-text-blue)`},"status:success":{"--color-text-primary":`var(--color-text-green)`,"--color-text-secondary":`var(--color-text-green)`,"--color-success":`var(--color-text-green)`},"status:warning":{"--color-text-primary":`var(--color-text-yellow)`,"--color-text-secondary":`var(--color-text-yellow)`,"--color-warning":`var(--color-text-yellow)`},"status:error":{"--color-text-primary":`var(--color-text-red)`,"--color-text-secondary":`var(--color-text-red)`,"--color-error":`var(--color-text-red)`}},switch:{base:{"--color-background-gray":`var(--color-border-emphasized)`}},progressbar:{base:{"--color-background-muted":`var(--color-border-emphasized)`},"variant:accent":{"--color-accent":`#0074e2`},"variant:success":{"--color-success":`#198100`},"variant:warning":{"--color-warning":`#ffce2f`},"variant:error":{"--color-error":`#c9303a`}},card:{base:{padding:`var(--spacing-3)`}},section:{base:{padding:`var(--spacing-3)`}}},__onDark:{tokens:{"color-scheme":`dark`,"--color-text-primary":`var(--color-on-dark)`,"--color-icon-primary":`var(--color-on-dark)`,"--color-accent":`var(--color-on-dark)`}},__onLight:{tokens:{"color-scheme":`light`,"--color-text-primary":`var(--color-on-light)`,"--color-icon-primary":`var(--color-on-light)`,"--color-accent":`var(--color-on-light)`}},icons:{close:(0,K.jsx)(Lt,{...aY}),chevronDown:(0,K.jsx)(L,{...aY}),chevronLeft:(0,K.jsx)(R,{...aY}),chevronRight:(0,K.jsx)(ee,{...aY}),chevronsLeft:(0,K.jsx)(z,{...aY}),chevronsRight:(0,K.jsx)(B,{...aY}),check:(0,K.jsx)(I,{...aY}),success:(0,K.jsx)(H,{...aY}),error:(0,K.jsx)(ie,{...aY}),warning:(0,K.jsx)(At,{...aY}),info:(0,K.jsx)(Pe,{...aY}),calendar:(0,K.jsx)(P,{...aY}),clock:(0,K.jsx)(se,{...aY}),externalLink:(0,K.jsx)(he,{...aY}),menu:(0,K.jsx)(Ke,{...aY}),moreHorizontal:(0,K.jsx)(W,{...aY}),search:(0,K.jsx)(ht,{...aY}),arrowUp:(0,K.jsx)(k,{...aY}),arrowDown:(0,K.jsx)(w,{...aY}),arrowsUpDown:(0,K.jsx)(D,{...aY}),funnel:(0,K.jsx)(Oe,{...aY}),eyeSlash:(0,K.jsx)(ge,{...aY}),viewColumns:(0,K.jsx)(le,{...aY}),copy:(0,K.jsx)(ue,{...aY}),checkDouble:(0,K.jsx)(F,{...aY}),wrench:(0,K.jsx)(It,{...aY}),stop:(0,K.jsx)(Et,{...aY}),microphone:(0,K.jsx)(Ze,{...aY})}};function sY({children:e}){let t=pr(KJ,e=>e.snapshot?.preferences),n=t?.theme??`system`,r=t?.appearance??yI,i=xI(n,r),a=t?.chatWidth??820,o=t?.chatFontSize??14,[s,c]=(0,_.useState)(()=>window.matchMedia?.(`(prefers-color-scheme: dark)`).matches??!1);(0,_.useEffect)(()=>{let e=window.matchMedia?.(`(prefers-color-scheme: dark)`);if(!e)return;let t=()=>c(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let l=n===`system`?s?`dark`:`light`:n,u=l===`dark`||l===`pine`?`dark`:`light`;return(0,_.useEffect)(()=>{let e=document.documentElement;e.dataset.theme=l,e.dataset.palette=i,e.style.setProperty(`--conversation-content-width`,`${a}px`),e.style.setProperty(`--conversation-font-size`,`${o}px`);let t={};if(r.background&&(t[`--page`]=r.background),r.foreground&&(t[`--text`]=r.foreground),r.background||r.foreground)for(let[e,n]of Object.entries({sidebar:3,"sidebar-hover":7,"sidebar-active":10,border:12,"border-strong":22,muted:65,subtle:52,"settings-secondary-text":75}))t[`--${e}`]=`color-mix(in srgb, var(--text) ${n}%, var(--page))`;r.accent&&(t[`--accent`]=r.accent,t[`--focus`]=r.accent),e.style.setProperty(`--openpi-interface-font`,{codex:`var(--openpi-default-font)`,system:`var(--openpi-default-font)`,sans:`Arial, Helvetica, sans-serif`,serif:`Georgia, 'Times New Roman', serif`,mono:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`}[r.font]);for(let n of[`page`,`text`,`sidebar`,`sidebar-hover`,`sidebar-active`,`border`,`border-strong`,`muted`,`subtle`,`settings-secondary-text`,`accent`,`focus`]){let r=t[`--${n}`];r?e.style.setProperty(`--${n}`,r):e.style.removeProperty(`--${n}`)}},[r,o,a,i,l]),(0,K.jsx)(lr,{i18n:In,children:(0,K.jsx)(ju,{theme:oY,mode:u,children:e})})}var cY=document.getElementById(`root`);if(!cY)throw Error(`OpenPI Web root is missing`);(0,zt.createRoot)(cY).render((0,K.jsx)(_.StrictMode,{children:(0,K.jsx)(sY,{children:(0,K.jsx)(iY,{})})}));export{lt as a,Lt as i,Po as n,$e as o,cr as r,x as s,Lp as t}; \ No newline at end of file diff --git a/web/ui/src/features/transcript/Transcript.tsx b/web/ui/src/features/transcript/Transcript.tsx index b697156ae..74ddb0281 100644 --- a/web/ui/src/features/transcript/Transcript.tsx +++ b/web/ui/src/features/transcript/Transcript.tsx @@ -18,6 +18,7 @@ import { } from "lucide-react"; import { Fragment, + memo, type ReactNode, useCallback, useEffect, @@ -100,6 +101,7 @@ type PersistedEntry = NonNullable< interface DisplayEntry { compaction?: true; forkSnapshotBoundary?: true; + persisted?: true; key: string; entryId?: string; timingKey?: string; @@ -173,9 +175,50 @@ interface RenderRow { commandHandledInputId?: string; commandHandledCommandId?: string; forkSnapshotBoundary?: true; + persisted?: true; timing?: WebTurnTiming; } +interface CachedHistoryRows { + slots: readonly unknown[]; + rows: RenderRow[]; + token: object; + turn: number; + latestUserPrompt: string | undefined; + latestUserIndex: number; + retryRowKey: string | undefined; + turnItems: TurnNavigationItem[]; + attemptContents: [string, RenderRow[]][]; +} + +let transcriptRowRenderObserver: ((rowKey: string) => void) | undefined; + +export function observeTranscriptRowRenders( + observer: ((rowKey: string) => void) | undefined, +) { + const previous = transcriptRowRenderObserver; + transcriptRowRenderObserver = observer; + return () => { + transcriptRowRenderObserver = previous; + }; +} + +function sameSlot(left: unknown, right: unknown) { + if (Object.is(left, right)) return true; + if (!Array.isArray(left) || !Array.isArray(right)) return false; + if (left.length !== right.length) return false; + for (let index = 0; index < left.length; index++) + if (!sameSlot(left[index], right[index])) return false; + return true; +} + +function sameSlots(left: readonly unknown[], right: readonly unknown[]) { + if (left.length !== right.length) return false; + for (let index = 0; index < left.length; index++) + if (!sameSlot(left[index], right[index])) return false; + return true; +} + type ActiveTurn = NonNullable; function record(value: unknown): Record { @@ -1345,8 +1388,8 @@ function persistedTranscriptProjection( group.push(entry); exactNative.set(signature, group); } - const baseEntries = persisted.flatMap( - (entry: PersistedEntry): DisplayEntry[] => { + const baseEntries = persisted + .flatMap((entry: PersistedEntry): DisplayEntry[] => { if (entry.forkSnapshotBoundary) return [ { @@ -1396,8 +1439,8 @@ function persistedTranscriptProjection( message, }, ]; - }, - ); + }) + .map((entry) => ({ ...entry, persisted: true as const })); const indexById = new Map(); const lookupIndexes = new Map(); baseEntries.forEach((entry, index) => { @@ -2053,6 +2096,31 @@ function ProcessSequence({ ); } +const MemoRowFrame = memo(function MemoRowFrame({ + rowKey, + token, + children, +}: { + rowKey: string; + token: object; + children: ReactNode; +}) { + transcriptRowRenderObserver?.(rowKey); + return children; +}); + +function frameRow(row: RenderRow, token: object): RenderRow { + if (row.content == null) return row; + return { + ...row, + content: ( + + {row.content} + + ), + }; +} + function groupRows(rows: RenderRow[], active: boolean) { const blocks: Array<{ process: boolean; rows: RenderRow[] }> = []; for (const row of rows) { @@ -2727,6 +2795,18 @@ export function Transcript(props: TranscriptProps) { scope: hydrationScope, keys: new Map(), }); + const entryRowCache = useRef({ + scope: hydrationScope, + rows: new Map(), + }); + const reviewTurnRef = useRef(props.onReviewTurn); + reviewTurnRef.current = props.onReviewTurn; + const onReviewTurn = useCallback( + (promptEntryId: string, filePath?: string) => { + reviewTurnRef.current?.(promptEntryId, filePath); + }, + [], + ); if (nativeRowKeys.current.scope !== hydrationScope) nativeRowKeys.current = { scope: hydrationScope, keys: new Map() }; const { entries, projectedPrompts } = useMemo( @@ -2770,6 +2850,60 @@ export function Transcript(props: TranscriptProps) { return () => observer.disconnect(); }, []); + const rowContext = useMemo( + () => ({ + active, + running, + selectedExecution, + retry, + activityObserved: props.activityObserved, + historyPaused, + onResend: props.onResend, + onEdit: props.onEdit, + onRegenerate: props.onRegenerate, + onFork: props.onFork, + forkAvailable: props.forkAvailable, + forkPending: props.forkPending, + onInspectSubagent: props.onInspectSubagent, + subagents: props.snapshot.runtime.capabilities.subagents, + workflows: props.snapshot.runtime.capabilities.workflows?.items, + expandThinking: props.snapshot.preferences.expandThinking, + subagentResultDisplay: props.snapshot.preferences.subagentResultDisplay, + bashToolDisplay: props.snapshot.preferences.bashToolDisplay, + fileMutationDisplay: props.snapshot.preferences.fileMutationDisplay, + thinkingLevel: props.snapshot.thinking?.level, + selectedId, + selectedPath, + selectedCwd, + t, + }), + [ + active, + running, + selectedExecution, + retry, + props.activityObserved, + historyPaused, + props.onResend, + props.onEdit, + props.onRegenerate, + props.onFork, + props.forkAvailable, + props.forkPending, + props.onInspectSubagent, + props.snapshot.runtime.capabilities.subagents, + props.snapshot.runtime.capabilities.workflows?.items, + props.snapshot.preferences.expandThinking, + props.snapshot.preferences.subagentResultDisplay, + props.snapshot.preferences.bashToolDisplay, + props.snapshot.preferences.fileMutationDisplay, + props.snapshot.thinking?.level, + selectedId, + selectedPath, + selectedCwd, + t, + ], + ); const { rows, turns } = useMemo(() => { const records = recordedSubagents(entries.map((entry) => entry.message)); const failures = providerFailures(entries, running && !historyPaused); @@ -2847,8 +2981,17 @@ export function Transcript(props: TranscriptProps) { assistantCandidate = index; }); if (assistantCandidate >= 0) lastAssistantByTurn.add(assistantCandidate); + const recordsSignature = [...records.values()] + .map( + (item) => + `${item.id}\0${item.title}\0${item.state ?? ""}\0${item.result ?? ""}\0${item.receipt ?? ""}`, + ) + .join("\n"); - const rendered = entries.flatMap((entry, index): RenderRow[] => { + const produceEntryRows = ( + entry: DisplayEntry, + index: number, + ): RenderRow[] => { const message = entry.message; if (entry.forkSnapshotBoundary) return [ @@ -3762,7 +3905,124 @@ export function Transcript(props: TranscriptProps) { ]; } return []; + }; + if (entryRowCache.current.scope !== hydrationScope) + entryRowCache.current = { + scope: hydrationScope, + rows: new Map(), + }; + const historyCache = entryRowCache.current.rows; + const seenEntryKeys = new Set(); + const rendered = entries.flatMap((entry, index): RenderRow[] => { + const hydrationKey = entry.entryId + ? JSON.stringify([selectedId, selectedPath, entry.entryId]) + : ""; + const failure = failures.groups.get(index); + const toolDeps: unknown[] = []; + let highlighted = Boolean( + highlightedEntry && entry.entryId === highlightedEntry, + ); + if (entry.message.role === "assistant") { + for (const part of entry.message.parts ?? []) { + if (part.type !== "toolCall" || !part.id) continue; + const resultEntry = results.get(part.id); + if (highlightedEntry && resultEntry?.entryId === highlightedEntry) + highlighted = true; + const related = new Set([part.id]); + const liveDeps: unknown[] = []; + for (const item of liveTools) { + if ( + item.call.id !== part.id && + !(item.parentToolCallId && related.has(item.parentToolCallId)) + ) + continue; + if (item.call.id) related.add(item.call.id); + liveDeps.push( + item.call.id, + item.state, + item.result, + item.parentToolCallId, + ); + } + toolDeps.push( + part.id, + resultEntry?.message, + part.name.startsWith("subagent") || part.name.startsWith("workflow") + ? recordsSignature + : undefined, + liveDeps, + ); + } + } else if ( + entry.message.role === "toolResult" && + entry.message.toolCallId + ) { + toolDeps.push(pairedToolIds.has(entry.message.toolCallId)); + } + const slots = [ + rowContext, + entry.message, + entry.key, + entry.entryId, + entry.timestamp, + entry.timing, + entry.compaction, + entry.forkSnapshotBoundary, + entry.optimistic, + entry.persisted, + index, + highlighted, + hydrationKey ? hydratedMessages[hydrationKey] : undefined, + displayedThinkingDuration(entry, props.thinkingDurations), + lastAssistantByTurn.has(index), + failures.finalErrors.has(index), + failure?.state, + failure + ? failure.attempts.map((attempt) => attempt.key).join("\0") + : undefined, + turn, + latestUserPrompt, + latestUserIndex, + toolDeps, + ]; + const hit = historyCache.get(entry.key); + if (hit && sameSlots(hit.slots, slots)) { + turn = hit.turn; + latestUserPrompt = hit.latestUserPrompt; + latestUserIndex = hit.latestUserIndex; + if (hit.retryRowKey) retryRowKey = hit.retryRowKey; + for (const item of hit.turnItems) turnItems.push(item); + for (const [key, value] of hit.attemptContents) + attemptContents.set(key, value); + seenEntryKeys.add(entry.key); + return hit.rows; + } + const turnItemsBefore = turnItems.length; + const attemptKeysBefore = new Set(attemptContents.keys()); + const produced = produceEntryRows(entry, index).map((row) => + entry.persisted ? { ...row, persisted: true as const } : row, + ); + const token = {}; + const framed = produced.map((row) => frameRow(row, token)); + const attemptAdded: [string, RenderRow[]][] = []; + for (const [key, value] of attemptContents) + if (!attemptKeysBefore.has(key)) attemptAdded.push([key, value]); + historyCache.set(entry.key, { + slots, + rows: framed, + token, + turn, + latestUserPrompt, + latestUserIndex, + retryRowKey, + turnItems: turnItems.slice(turnItemsBefore), + attemptContents: attemptAdded, + }); + seenEntryKeys.add(entry.key); + return framed; }); + for (const key of historyCache.keys()) + if (!seenEntryKeys.has(key)) historyCache.delete(key); let nativeEnd = rendered.length; while (nativeEnd > 0 && rendered[nativeEnd - 1]!.pendingPrompt) nativeEnd--; const pendingPreviews = rendered.length - nativeEnd; @@ -3857,6 +4117,8 @@ export function Transcript(props: TranscriptProps) { selectedCwd, hydratedMessages, highlightedEntry, + hydrationScope, + rowContext, t, ]); @@ -4355,7 +4617,7 @@ export function Transcript(props: TranscriptProps) { changesByPrompt, selected, props.activityObserved !== false ? visibleTimedTurn : undefined, - props.onReviewTurn, + onReviewTurn, props.activityObserved !== false, )} {running &&